Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller for JSON and HTML with Spring Boot

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

Can Spring Boot do this? If so, how?

I know how to return JSON:

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

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.

like image 228
John Avatar asked Dec 03 '14 18:12

John


1 Answers

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

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

like image 181
Maciej Walkowiak Avatar answered Sep 21 '22 06:09

Maciej Walkowiak