向request域共享数据
方式如下:
- ServletAPI
- ModelAndView
- Model
- map
- ModelMap
ServletAPI
- Controller
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
request.setAttribute("key", "value");
return "success";
}
- index.html
<a th:href="@{/testServletAPI}">通过ServletAPI向Request域共享数据</a>
- success.html
success <br/>
<p th:text="${key}"></p>
ModelAndView
- controller
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView modelAndView = new ModelAndView();
//添加数据
modelAndView.addObject("key", "value");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
Model
- controller
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("key", "value");
return "success";
}
map
- controller
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
map.put("key", "value");
return "success";
}
ModelMap
- controller
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("key", "value");
return "success";
}
向session域共享数据
- controller
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("key", "value");
return "success";
}
- success.html
<p th:text="${session.key}"></p>
向application域共享数据
- Controller
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext servletContext = session.getServletContext();
servletContext.setAttribute("key", "value");
return "success";
}
- success.html
<p th:text="${application.key}"></p>