在 Spring Boot 中从 @RestController 有条件地返回 JSON 和 (HTML) 模板 [英] Conditionally returning both JSON and (HTML) templates from @RestController in Spring Boot

查看:68
本文介绍了在 Spring Boot 中从 @RestController 有条件地返回 JSON 和 (HTML) 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数类似的问题似乎与我遇到的问题相反.

Most of the similar questions seem to have the opposite problem I’m having.

我正在使用 @RestController 构建一个基于 Spring Boot 的 web 应用程序.JSON 响应运行良好,但现在我想支持通过模板(特别是 Thymeleaf)返回 HTML.所有示例都显示如下构建方法:

I’m building a Spring Boot-based webapp using @RestController. The JSON responses work well, but now I want to support returning HTML via templates (Thymeleaf, specifically). All the examples show building methods like this:

@RequestMapping(method = RequestMethod.GET)
String index()
{
    return "index";
}

这样就可以了,只要它所在的类用 @Controller 注释.如果我用 @RestController 注释,我会得到文字字符串index".这是有道理的,因为 @RestController 意味着 @ResponseBody.

And that works fine, so long as the class it’s in is annotated with @Controller. If I annotate with @RestController, I get the literal string "index" back. This makes sense, since @RestController implies @ResponseBody.

总的来说,我对此有一些疑问......

I have a few questions about this in general…

  • 在旨在返回 JSON 的方法上使用 @Controller 和显式 @ResponseBody 注释是否正确?

  • Is the right thing to do to use @Controller and explicit @ResponseBody annotations on the methods designed to return JSON?

我担心我的控制器类会变得非常大,因为对于大多数 GET 方法我将有两种实现(一种用于返回 HATEOAS JSON,一种用于返回包含模型中更多内容的 HTML).是否有建议的做法来解决这个问题?

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?

感谢您的建议.谢谢!

推荐答案

@RestController
public class SampleController {    

@GetMapping(value = "/data/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public CustomClass get(@PathVariable String id) {
    return newsService.getById(id);
}

@GetMapping(value = "/data/{id}", produces = MediaType.TEXT_HTML_VALUE)
public String getHTML(@PathVariable String id) {
    return "HTML";
}

}

这篇关于在 Spring Boot 中从 @RestController 有条件地返回 JSON 和 (HTML) 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆