本篇内容主要讲解“SpringMVC请求域对象的数据共享怎么实现”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SpringMVC请求域对象的数据共享怎么实现”吧!
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的实例是由mvc框架自动创建并作为控制器方法参数传入,无需也不能自己创建。
如自己创建,则无法共享数据。
//使用ModelMap对象的方式
@RequestMapping("/")
public String toIndexModel(ModelMap modelMap){
//设置共享数据
modelMap.addAttribute("result","ModelMapResult");
return "index";
}
到此,相信大家对“SpringMVC请求域对象的数据共享怎么实现”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。