個(gè)人網(wǎng)站建設(shè)教程網(wǎng)站排名查詢站長(zhǎng)之家
處理請(qǐng)求的過(guò)程:
獲取請(qǐng)求參數(shù),調(diào)用service處理業(yè)務(wù)邏輯,往域?qū)ο笾泄蚕頂?shù)據(jù),最后實(shí)現(xiàn)渲染頁(yè)面跳轉(zhuǎn)。
請(qǐng)求域中共享數(shù)據(jù)
ModelAndView向request域?qū)ο蠊蚕頂?shù)據(jù)
ModelAndView:往域?qū)ο蠊蚕頂?shù)據(jù),并實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)和渲染頁(yè)面。
- 使用ModelAndView時(shí),可以使用其Model功能向請(qǐng)求域共享數(shù)據(jù)。
- 使用View功能設(shè)置邏輯視圖實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn),但是控制器方法的返回值一定要
將ModelAndView作為方法的返回值。
index.html
<a th:href="@{/test/mav}">測(cè)試通過(guò)ModelandView向請(qǐng)求域共享數(shù)據(jù)</a>
controller
@RequestMapping("/test/mav")
// 如果要用ModelAndView,必須將ModelAndView進(jìn)行返回public ModelAndView testMAV(){ModelAndView mav=new ModelAndView();
// 向請(qǐng)求域中共享數(shù)據(jù)mav.addObject("testRequestScope","hello,ModelAndView");mav.setViewName("success");return mav;}
success.html
<p th:text="${application.testApplicationScope}"></p>
Model向request域?qū)ο蠊蚕頂?shù)據(jù)
DispatcherServlet調(diào)用方法的時(shí)候直接創(chuàng)建這個(gè)Model對(duì)象。
<a th:href="@{/test/model}">測(cè)試通過(guò)Model向請(qǐng)求域共享數(shù)據(jù)</a><br>
@RequestMapping("/test/model")
// 方法的返回值是String,現(xiàn)在用的是ModelAndView里面的Model功能public String testModel(Model model){model.addAttribute("testRequestScope","hello,Model");return "success";}
ModelMap向request域?qū)ο蠊蚕頂?shù)據(jù)
跟Model的向request域?qū)ο蠊蚕頂?shù)據(jù)一樣。
Map向request域?qū)ο蠊蚕頂?shù)據(jù)
@RequestMapping("/test/map")
// 方法的返回值是String,現(xiàn)在用的是ModelAndView里面的Model功能public String testModel(Map<String,Object > map){ //直接創(chuàng)建model對(duì)象map.put("testRequestScope","hello,map");return "success";}
注:這三種類型都是:org.springframework.validation.support.BindingAwareModelMap類型
ServletAPI向request域?qū)ο蠊蚕頂?shù)據(jù)
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
request.setAttribute("testScope", "hello,servletAPI");
return "success";
}
會(huì)話域和應(yīng)用域共享數(shù)據(jù)
直接使用servletAPI,相比較而言,springmvc提供的方式并沒(méi)有使用servletAPI簡(jiǎn)單。
<a th:href="@{/test/session}">測(cè)試向會(huì)話域共享數(shù)據(jù)</a><br>
<a th:href="@{/test/application}">測(cè)試通過(guò)應(yīng)用域共享數(shù)據(jù)</a><br>
@RequestMapping("/test/session")public String testSession(HttpSession session){session.setAttribute("testSessionScope","hello,session");return "success";}@RequestMapping("/test/application")public String testApplication(HttpSession session){ServletContext servletContext = session.getServletContext();servletContext.setAttribute("testApplicationScope","hello,application");return "success";}
<h1>success.html</h1>
<p th:text="${session.testSessionScope}"></p>
<p th:text="${application.testApplicationScope}"></p>