当前位置: 代码迷 >> 综合 >> 《spring-boot学习》@RestController 和@Controller的区别
  详细解决方案

《spring-boot学习》@RestController 和@Controller的区别

热度:44   发布时间:2023-11-17 13:20:38.0

@Controller和@RestController的区别?

package hello;import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;@RestController
public class HelloController {@RequestMapping("/")public String index() {return "Greetings from Spring Boot!";}}

官方文档解释:

1.The class is flagged as a @RestController, meaning it’s ready for use by Spring MVC to handle web requests. @RequestMapping maps / to the index() method. When invoked from a browser or using curl on the command line, the method returns pure text. That’s because @RestController combines @Controller and @ResponseBody, two annotations that results in web requests returning data rather than a view.(该类被标记为a @RestController,意味着Spring MVC可以使用它来处理Web请求。@RequestMapping映射/到该index()方法。当从浏览器调用或在命令行上使用curl时,该方法将返回纯文本。这是因为@RestController结合@Controller@ResponseBody两个注释会导致Web请求返回数据而不是视图。)

2.the @RestControllerannotation is a stereotype annotation that combines @ResponseBody and @Controller, in other words the Controller returns an object in the response body instead of returning a view.(@RestController注释是结合了原型注释@ResponseBody@Controller,换句话说,控制器在响应体返回一个对象,而不是返回的视图。)

总结:

1)@Controller类中的方法可以直接通过返回String跳转到jsp、ftl、html等模版页面。在方法上加@ResponseBody注解,也可以返回实体对象。

2)@RestController类中的所有方法只能返回String、Object、Json等实体对象,不能跳转到模版页面。

3)@RestController相当于@ResponseBody + @Controller。


  相关解决方案