我正在编写一个应用程序,其中我需要对某些对象进行 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; 
} 

但我不确定如何让 Controller 根据请求做一个或另一个。

请您参考如下方法:

这是 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"; 
    } 
} 

阅读更多: http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc和 http://spring.io/blog/2013/06/03/content-negotiation-using-views


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!