带有Spring Boot的JSON和HTML控制器

Joh*_*ohn 5 spring json spring-mvc spring-boot

我正在编写一个应用程序,其中包括我需要对某些对象进行CRUD操作.我需要能够为人类用户提供HTML页面,为其他应用程序提供JSON.现在我的网址对于"阅读"看起来像这样:

GET  /foo/{id}      -> Serves HTML
GET  /rest/foo/{id} -> Serves JSON
etc.
Run Code Online (Sandbox Code Playgroud)

这似乎有点多余.我宁愿有这样的事情:

GET /foo/{id}.html OR /foo/{id} -> Serves HTML
GET /foo/{id}.json              -> Serves JSON
Run Code Online (Sandbox Code Playgroud)

Spring Boot可以这样做吗?如果是这样,怎么样?

我知道如何返回JSON:

@RequestMapping(value = "/foo/{id}", method = RequestMethod.GET, produces = "application/json")
public Object fetch(@PathVariable Long id) {
    return ...;
}
Run Code Online (Sandbox Code Playgroud)

我也知道如何返回HTML:

@RequestMapping("/app/{page}.html")
String index(@PathVariable String page) {
    if(page == null || page.equals(""))
        page = "index";
    return page;
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何让控制器根据请求做一个或另一个.

Mac*_*iak 19

这是Spring Boot的默认行为.唯一的事情是你必须标记其中一个@RequestMapping产生JSON.例:

@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";
    }
}
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请访问:http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvchttp://spring.io/blog/2013/06/03/content-negotiation-使用的视图

  • 它并非完全正确.如果要调用经典HTML页面,您可能需要执行其他操作.ContentNegotiationViewResolver只是其中一个选项,这就是为什么我链接解释这两种方法的文章. (3认同)