Java – SpringMVC – 请求域共享
简介
Servlet 中的请求域共享,指的是 ServletRequest 中的请求参数。
在SpringMVC中,有多种方法对 ServletRequest 加入请求参数。
Servlet 请求域共享
在SpringMVC中使用 Servlet 请求域共享方法如下
@RequestMapping("/servletRequest")
public String testServletAPI(HttpServletRequest request){
request.setAttribute("scope", "hello,servletAPI");
return "success";
}
关于Servlet请求域问题,可以参考Servlet请求与响应文章
SpringMVC 请求域共享
ModelAndView
SpringMVC 中推荐使用的一种请求域共享方法,ModelAndView 包含 request 请求域数据,和页面跳转功能
在以往控制器方法中返回 String 类型,都会被SpringMVC后台封装成ModelAndView对象并响应。
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
/**
* ModelAndView有Model和View的功能
* Model主要用于向请求域共享数据
* View主要用于设置视图,实现页面跳转
*/
ModelAndView mav = new ModelAndView();
//向请求域共享数据
mav.addObject("testScope", "hello,ModelAndView");
//设置视图,实现页面跳转
mav.setViewName("index");
return mav;
}
在HTML页面中,可以通过thymeleaf 语法获得 attributeName 的值
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>Hello SpringMVC</h1>
接收共享域数据:<input type="text" name="" th:value="${testScope}">
</body>
</html>
Model
SpringMVC 支持单设置Model参数值,无需设置View.
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testScope", "hello,Model");
return "success";
}
ModelMap
SpringMVC 支持单设置ModelMap参数值,无需设置View.
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testModelMap","hello,ModelMap");
return "index";
}
Map
SpringMVC 支持单设置Map<>参数值,无需设置View.
@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
map.put("testMap","hello,Map");
return "index";
}
Model、ModelMap和Map的关系
Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的,所以使用任意一种方法都可以实现请求域共享数据。
public interface Model{}
public class ModelMap extends LinkedHashMap<String, Object> {}
public class ExtendedModelMap extends ModelMap implements Model {}
public class BindingAwareModelMap extends ExtendedModelMap {}
session域共享
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testSessionScope", "hello,session");
return "success";
}
关于 session域 请参考以下文章
application域共享
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("testApplicationScope", "hello,application");
return "success";
}
共有 0 条评论