大多数类似的问题似乎与我遇到的问题相反。
我正在使用 @RestController
构建一个基于 Spring Boot 的 web 应用程序. JSON 响应运行良好,但现在我想支持通过模板(特别是 Thymeleaf)返回 HTML。所有示例都显示了这样的构建方法:
@RequestMapping(method = RequestMethod.GET)
String index()
{
return "index";
}
这工作正常,只要它所在的类用
@Controller
注释.如果我用 @RestController
注释,我得到了文字字符串“index”。这是有道理的,因为 @RestController
暗示 @ResponseBody
.总的来说,我对此有一些疑问……
@Controller
是正确的做法吗?和明确的 @ResponseBody
用于返回 JSON 的方法的注释? 建议表示赞赏。谢谢!
最佳答案
Is the right thing to do to use @Controller and explicit @ResponseBody annotations on the methods designed to return JSON?
只要你的 Controller 很小并且只包含很少的方法。
I worry that my Controller classes will grow quite large, as I’ll have two implementations for most of the GET methods (one to return the HATEOAS JSON, one to return HTML with a lot more stuff in the model). Are there recommended practices for factoring this?
如果它们长大并变得难以阅读,就会分成一个
@Controller
返回 HTML 页面和 @RestController
返回 JSON。总而言之,关注可读性。从技术上讲,这两种方法都是正确的。
关于spring - 在 Spring Boot 中从 @RestController 有条件地返回 JSON 和 (HTML) 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40260292/