使用Spring Boot的JSON和HTML控制器 [英] Controller for JSON and HTML with Spring Boot
问题描述
我正在编写一个应用程序,其中我需要对某些对象进行CRUD操作.我需要能够为人类用户提供HTML页面,并为其他应用程序提供JSON.现在,我的网址看起来像阅读":
I am writing an application where among other things I need to do CRUD operations with certain objects. I need to be able to serve both HTML pages for human users, and JSON for other applications. Right now my URLs look like this for "Read":
GET /foo/{id} -> Serves HTML
GET /rest/foo/{id} -> Serves JSON
etc.
这似乎有点多余.我宁愿有这样的东西:
This seems a little redundant. I would rather have something like this:
GET /foo/{id}.html OR /foo/{id} -> Serves HTML
GET /foo/{id}.json -> Serves JSON
Spring Boot可以做到吗?如果可以,怎么办?
Can Spring Boot do this? If so, how?
我知道如何返回JSON:
I know how to return JSON:
@RequestMapping(value = "/foo/{id}", method = RequestMethod.GET, produces = "application/json")
public Object fetch(@PathVariable Long id) {
return ...;
}
我也知道如何返回HTML:
I also know how to return HTML:
@RequestMapping("/app/{page}.html")
String index(@PathVariable String page) {
if(page == null || page.equals(""))
page = "index";
return page;
}
但是我不确定如何让控制器根据请求来做一个或另一个.
But I'm not sure how to have a controller do one or the other based on the request.
推荐答案
这是Spring Boot的默认行为.唯一的事情是您必须标记@RequestMapping
之一以生成JSON.示例:
It's a default behavior for Spring Boot. The only thing is that you have to mark one of @RequestMapping
to produce JSON. Example:
@Controller
class HelloController {
// call http://<host>/hello.json
@RequestMapping(value = "/hello", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public MyObject helloRest() {
return new MyObject("hello world");
}
// call http://<host>/hello.html or just http://<host>/hello
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String helloHtml(Model model) {
model.addAttribute("myObject", new MyObject("helloWorld"));
return "myView";
}
}
更多信息,请访问: http://spring. io/blog/2013/05/11/content-negotiation-using-spring-mvc 和
Read more at: http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc and http://spring.io/blog/2013/06/03/content-negotiation-using-views
这篇关于使用Spring Boot的JSON和HTML控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!