欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

关于SpringMVC请求域对象的数据共享问题

程序员文章站 2022-06-23 20:41:42
springmvc支持路径中的占位符。可以通过路径的方式来传参。restful风格。使用{}做占位符在路径中指定参数,使用@pathvariable注解在参数列表中指定。

springmvc支持路径中的占位符。

可以通过路径的方式来传参。restful风格。使用{}做占位符在路径中指定参数,使用@pathvariable注解在参数列表中指定。

<a th:href="@{/test/1}">传了参数</a>
@requestmapping("/test/{id}")
public string test(@pathvariable("id")integer id){
    system.out.println(id);
    return "index";
}

如果使用了占位符则请求地址必须有值,否则会报404错误。

获取请求参数

使用servletapi获取(基本不用)

@requestmapping("/testparam")
public string param(httpservletrequest request){
    string username = request.getparameter("username");
    string password = request.getparameter("password");
    return "index";
}

通过控制器的形参获取(保证参数名相同的情况下)牛逼

<a th:href="@{/testparam(username='admin',password='123')}">传了参数</a>
@requestmapping("/testparam")
public string testparam(string username,string password){
    system.out.println("username:"+username+",password:"+password);
    return "index";
}

requestparam

请求参数和控制器形参创建映射关系。

  • value
  • required
  • defaultvalue

使用实体类接受请求参数

@requestmapping("/testpojo")
public string testpojo(user user){
    system.out.println(user);
    return "index";
}

配置过滤器,处理乱码问题

<filter>
    <filter-name>characterencodingfilter</filter-name>
    <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class>
    <!--设置字符集-->
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
    <!--强制响应字符集-->
    <init-param>
        <param-name>forceresponseencoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>characterencodingfilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

域对象共享数据

使用原生servletapi向request域对象共享数据(不用)

@requestmapping("/test")
public string test(httpservletrequest request){
    request.setattribute("hello","hello");
    return "index";
}

使用modelandview对象

返回值类型为modelandview

//使用modelandview对象的方式
@requestmapping("/")
public modelandview toindex(httpservletrequest request){
    modelandview mav = new modelandview();
    //设置共享数据
    mav.addobject("result","mavresult");
    //设置视图名称
    //视图名称=逻辑视图名称。
    mav.setviewname("index");
    return mav;
}

使用model对象

model是一个接口,因此不能像modelandview那样去new。

//使用model对象的方式
@requestmapping("/")
public string toindexmodel(model model){
    //设置共享数据
    model.addattribute("result","modelresult");
    return "index";
}

使用map集合

//使用map对象的方式
@requestmapping("/")
public string toindexmodel(map<string,object> map){
    //设置共享数据
    map.put("result","mapresult");
    return "index";
}

使用modelmap

modelmap的实例是由mvc框架自动创建并作为控制器方法参数传入,无需也不能自己创建。

如自己创建,则无法共享数据。

//使用modelmap对象的方式
@requestmapping("/")
public string toindexmodel(modelmap modelmap){
    //设置共享数据
    modelmap.addattribute("result","modelmapresult");
    return "index";
}

到此这篇关于springmvc请求域对象的数据共享的文章就介绍到这了,更多相关springmvc请求域对象内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!