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