spring @Controller和@RestController注释之间的区别。
@Controller注释可以同时用于Web MVC和REST应用程序吗? 如果是,我们如何区分它是Web MVC还是REST应用程序?
spring @Controller和@RestController注释之间的区别。
@Controller注释可以同时用于Web MVC和REST应用程序吗? 如果是,我们如何区分它是Web MVC还是REST应用程序?
当前回答
@Controller返回View。@RestController返回ResponseBody。
其他回答
如果你使用@RestController,你不能返回一个视图(通过在Spring/springboot中使用Viewresolver),并且在这种情况下不需要@ResponseBody。
如果你使用@Controller你可以在Spring web MVC中返回一个视图。
@Controller在使用jsp的遗留系统中使用。它可以返回视图。 @RestController用于标记该控制器正在提供JSON响应类型的REST服务。所以它将@Controller和@ResponseBody注释包装在一起。
@RestController是@Controller和@ResponseBody的组合,如果我们在方法签名中不使用@ResponseBody,那么我们需要使用@RestController。
而不是使用@Controller和@ResponseBody, @RestController让你在Spring 4.0和更高版本中公开Rest api。
正如您在Spring文档(Spring RestController documentation)中看到的,RestController注释与Controller注释相同,但假设@ResponseBody默认是活动的,因此所有Java对象都被序列化为响应体中的JSON表示。