SPRING MVC3.2案例讲解--SPRING MVC3的各种URL映射+JSP视图跳转(3)
来源:互联网 发布:淘宝店铺推广技巧 编辑:程序博客网 时间:2024/05/20 18:54
本章节主要讲解使用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 ,进群前请标注开发的软件所属行业及工作经验!!