【发布时间】:2015-02-01 10:24:02
【问题描述】:
我正在编写一个应用程序,其中我需要对某些对象进行 CRUD 操作。我需要能够为人类用户提供 HTML 页面,并为其他应用程序提供 JSON。现在我的“阅读”网址如下所示:
GET /foo/{id} -> Serves HTML
GET /rest/foo/{id} -> Serves JSON
etc.
这似乎有点多余。我宁愿有这样的东西:
GET /foo/{id}.html OR /foo/{id} -> Serves HTML
GET /foo/{id}.json -> Serves JSON
Spring Boot 可以做到这一点吗?如果有,怎么做?
我知道如何返回 JSON:
@RequestMapping(value = "/foo/{id}", method = RequestMethod.GET, produces = "application/json")
public Object fetch(@PathVariable Long id) {
return ...;
}
我也知道如何返回 HTML:
@RequestMapping("/app/{page}.html")
String index(@PathVariable String page) {
if(page == null || page.equals(""))
page = "index";
return page;
}
但我不确定如何让控制器根据请求执行其中一项操作。
【问题讨论】:
标签: json spring spring-mvc spring-boot