本章節主要講解使用springmvc進行controller到view的轉向,涉及程式碼封裝含JSP視圖,
和上一章節最大的配置點不同是:
無任何視圖指向的Controller @ResponseBody是關鍵代碼,表示直接返回內容,不轉向JSP視圖
@Controllerpublic class MappingController {@RequestMapping("/mapping/path")public @ResponseBody String byPath() {return "Mapped by path!";}}
指向具體視圖的Controller,無@ResponseBody,表示會指向某個JSP視圖
@Controller@RequestMapping("/views/*")public class ViewsController {@RequestMapping(value="html", method=RequestMethod.GET)public String prepare(Model model) {model.addAttribute("foo", "bar");model.addAttribute("fruit", "apple");return "views/html";}
基於視圖轉向的四種用法:
1.自己制定轉向的視圖
// http://127.0.0.1:8010/views/html --->對應 views/html.jsp@RequestMapping(value="html", method=RequestMethod.GET)public String prepare(Model model) {model.addAttribute("foo", "bar");model.addAttribute("fruit", "apple");return "views/html";}
2.spring指向預設的視圖,通過org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator實現預設視圖的轉向,見日誌資訊:
DEBUG DispatcherServlet Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@55a58f]
// http://127.0.0.1:8010/views/viewName --->對應 views/viewName.jsp@RequestMapping(value="/viewName", method=RequestMethod.GET)public void usingRequestToViewNameTranslator(Model model) {model.addAttribute("foo", "bar");model.addAttribute("fruit", "apple");}
3.URI的 @PathVariable 的擷取,注意參數名稱必須一致。如:
// http://127.0.0.1:8010/views/pathVariables/bar/apple --->對應 views/html.jsp@RequestMapping(value="pathVariables/{foo}/{fruit}", method=RequestMethod.GET)public String pathVars(@PathVariable String foo, @PathVariable String fruit) {// No need to add @PathVariables "foo" and "fruit" to the model// They will be merged in the model before renderingreturn "views/html";}
4. 利用URL的@PathVariable給JAVABEAN賦值
//http://127.0.0.1:8010/views/dataBinding/bar/apple --->對應 views/dataBinding.jsp@RequestMapping(value="dataBinding/{foo}/{fruit}", method=RequestMethod.GET)public String dataBinding(@Valid JavaBean javaBean, Model model) {// JavaBean "foo" and "fruit" properties populated from URI variables return "views/dataBinding";}
public class JavaBean {@NotNullprivate String foo;@NotNullprivate String fruit;//注意此處有GET SET 方法,篇幅有限,不在文章中贅訴}
群:J2EE系統架構 203431569 ,進群前請標註開發的軟體所屬行業及工作經驗。。
大小: 70.7 KB 查看圖片附件