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

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。
转自:https://blog.csdn.net/qq_37495786/article/details/80449457

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值