本文主要是介绍@RestController 和 @Controller的区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. Controller, RestController的共同点
都是用来表示spring某个类的是否可以接收HTTP请求
2. Controller, RestController的不同点
@Controller标识一个Spring类是Spring MVC controller处理器
@RestController: a convenience annotation that does nothing more than adding the@Controller
and@ResponseBody
annotations。 @RestController是@Controller和@ResponseBody的结合体,两个标注合并起来的作用。
restcontroller与controller
假定一个user对象,对象有很多属性(name,sex,age,birth,address,tel)
在我的了解中,这二者的区分为:@restcontroller为@controller和@responsebody的结合
在@controller注解中,返回的是字符串,或者是字符串匹配的模板名称,即直接渲染视图,与html页面配合使用的,
在这种情况下,前后端的配合要求比较高,java后端的代码要结合html的情况进行渲染,使用model对象(或者modelandview)的数据将填充user视图中的相关属性,然后展示到浏览器,这个过程也可以称为渲染;
java示例代码如下:
@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后端的代码比较自由。
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”},前端页面只需要处理这个字符串即可
这篇关于@RestController 和 @Controller的区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!