提示:学习记录
Request:一次请求
Session:一次会话(浏览器开启到关闭)
ServletContext(Application):服务器开启到关闭
1、向request域共享数据
使用以下方法向Request请求域共享数据:
- 原生ServletAPI
- ModelAndView
- Model
- Map<T,T>
- ModelMap
控制器方法:
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
request.setAttribute("username","jerry");
request.setAttribute("password",123);
return "target";
}
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("username","jack");
modelAndView.addObject("password","abc");
modelAndView.setViewName("target");
return modelAndView;
}
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("username","harry");
model.addAttribute("password","kkk");
return "target";
}
@RequestMapping("/testMap")
public String testMap(Map<String,String> map){
map.put("username","Bob");
map.put("password","mmm");
return "target";
}
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("username","herry");
modelMap.addAttribute("password","123");
return "target";
}
index.html 视图层:
<a th:href="@{/testServletAPI}">测试原生ServletAPI向request请求域中共享参数</a><br>
<a th:href="@{/testModelAndView}">测试ModelAndView向request请求域共享参数</a><br>
<a th:href="@{/testModel}">测试Model向request请求域共享参数</a><br>
<a th:href="@{/testModelMap}">测试testModelMap向request请求域共享参数</a><br>
2、向session和application中共享数据
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("username","lili");
session.setAttribute("password","uiui");
return "target";
}
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext servletContext = session.getServletContext();
servletContext.setAttribute("username","Moly");
servletContext.setAttribute("password","oo");
return "target";
}
index.html:
<a th:href="@{/testSession}">测试原生ServletAPI向session请求域中共享参数</a><br>
<a th:href="@{/testApplication}">测试向Application请求域中共享参数</a><br>
可以在转发的target.html视图页面显示出所共享的参数username和password:
<!-- 获取存储在request域中的数据-->
<p th:text="${username}"></p>
<p th:text="${password}"></p>
<!-- 获取存储在session域中的数据-->
<p th:text="${session.username}"></p>
<p th:text="${session.password}"></p>
<!-- 获取存储在application域中的数据-->
<p th:text="${application.username}"></p>
<p th:text="${application.password}"></p>
|