@Controller和@RestController的区别
2018-03-04 17:59
465 查看
@Controller和@RestController的区别?
官方文档:
@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
意思是:
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
1)如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
例如:本来应该到success.jsp页面的,则其显示success.
2)如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
3)如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
在@controller注解中,返回的是字符串,或者是字符串匹配的模板名称,即直接渲染视图,与html页面配合使用的,在这种情况下,前后端的配合要求比较高,java后端的代码要结合html的情况进行渲染,使用model对象(或者modelandview)的数据将填充user视图中的相关属性,然后展示到浏览器,这个过程也可以称为渲染;
例子:
对应视图user.jsp中的html代码:
而在@restcontroller中,返回的应该是一个对象,即return一个user对象,这时,在没有页面的情况下,也能看到返回的是一个user对象对应的json字符串,而前端的作用是利用返回的json进行解析渲染页面,java后端的代码比较自由。
例子:
访问网址得到的是json字符串{“name”:”bob”,”sex”:”boy”},前端页面只需要处理这个字符串即可。
官方文档:
@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
意思是:
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
1)如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
例如:本来应该到success.jsp页面的,则其显示success.
2)如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
3)如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
在@controller注解中,返回的是字符串,或者是字符串匹配的模板名称,即直接渲染视图,与html页面配合使用的,在这种情况下,前后端的配合要求比较高,java后端的代码要结合html的情况进行渲染,使用model对象(或者modelandview)的数据将填充user视图中的相关属性,然后展示到浏览器,这个过程也可以称为渲染;
例子:
@Controller @RequestMapping(method = RequestMethod.GET,value="/") public String getuser(Model model) throws IOException { model.addAttribute("name",bob); model.addAttribute("sex",boy); return "user";//user是模板名 }
对应视图user.jsp中的html代码:
<html xmlns:th="http://www.thymeleaf.org"> <body> <div> <p>"${name}"</p> <p>"${sex}"</p> </div> </body> </html>
而在@restcontroller中,返回的应该是一个对象,即return一个user对象,这时,在没有页面的情况下,也能看到返回的是一个user对象对应的json字符串,而前端的作用是利用返回的json进行解析渲染页面,java后端的代码比较自由。
例子:
@RestController @RequestMapping(method = RequestMethod.GET, value = "/") public User getuser( ) throws IOException { User bob=new User(); bob.setName("bob"); bob.setSex("boy"); return bob; }
访问网址得到的是json字符串{“name”:”bob”,”sex”:”boy”},前端页面只需要处理这个字符串即可。
相关文章推荐
- @Controller和@RestController的区别
- @Controller和@RestController的区别?
- @Controller和@RestController的区别?
- @Controller和@RestController的区别?
- @Controller和@RestController的区别
- @Controller和@RestController的区别
- @Controller和@RestController的区别?
- @Controller和@RestController的区别
- springmvc中controller 使用@RestController 和 @Controller 返回结果的区别
- @Controller和@RestController的区别?
- @Controller和@RestController的区别?
- @Controller和@RestController的区别
- @Controller和@RestController的区别
- @Controller和@RestController的区别?
- @Controller和@RestController的区别?
- @Controller和@RestController的区别?
- @Controller和@RestController的区别?
- @Controller和@RestController的区别?
- @Controller和@RestController的区别?
- @Controller和@RestController的区别?