Spring Boot中的return new ModelAndView("xxx") 和 return "xxx"的区别

来源:互联网 发布:windows怎么截图窗口 编辑:程序博客网 时间:2024/06/07 20:34
1. return new modelAndView("XXX") 是包括视图和数据的,
  而return "XXX" 只是视图,他会根据你配置文件里试图解析器的配置,帮你匹配好前缀,后缀然后跳转到XXX这个页面。
  比如 return "index",你配置文件里的前缀是“/templates/”,后缀是“.html,就会跳转到XXX/templates/index.html页面。
  return new modelAndView("index"),这个modelAndView 里面包括视图名view,和数据model,
  里面的view 和return "index"是一样的流程,只不过同时也会传递过去model这个数据。


2. return "XXX"  只能使用@Controller注解,不能使用 @RestController注解,否则就会返回把视图名称当字符串返回,并不会渲染视图。return new modelAndView("XXX")  使用 @RestController 和 @Controller注解都可以正常渲染视图。
   比如 一个类class加了@RestController, @RestController注解内包含了@ResponseBody。 
   @ResponseBody的意思是返回的不是视图,也就是视图解析器不回去查找该视图名的模板,

   而是以response.getWriter().write("这里就是你写的字符串");方式返回,常用于ajax求情的返回内容。

 

示例:

a) 使用@RestController注解

@RestControllerpublic class PersonController {    @RequestMapping("mytest")    public String indexHtml(Map<String, Object> map) {        map.put("msg", "this is a thymeleaf test");        return "hello";    }    @RequestMapping("mymodelviewtest")    public ModelAndView hello(Map<String, Object> map) {        map.put("msg", "this is model view test");        return new ModelAndView("hello");    }}


return "hello" 返回视图名hello,并没有渲染视图hello.html。



return new ModelAndView("hello") 正常显示了视图内容。


b) 使用@Controller注解:

@Controllerpublic class PersonController {    @RequestMapping("mytest")    public String indexHtml(Map<String, Object> map) {        map.put("msg", "this is a thymeleaf test");        return "hello";    }    @RequestMapping("mymodelviewtest")    public ModelAndView hello(Map<String, Object> map) {        map.put("msg", "this is model view test");        return new ModelAndView("hello");    }}


return "hello"  正常显示了视图内容。


return new ModelAndView("hello") 正常显示了视图内容。




 
阅读全文
0 0
原创粉丝点击