Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally returning both JSON and (HTML) templates from @RestController in Spring Boot

Most of the similar questions seem to have the opposite problem I’m having.

I’m building a Spring Boot-based webapp using @RestController. The JSON responses work well, but now I want to support returning HTML via templates (Thymeleaf, specifically). All the examples show building methods like this:

@RequestMapping(method = RequestMethod.GET)
String index()
{
    return "index";
}

And that works fine, so long as the class it’s in is annotated with @Controller. If I annotate with @RestController, I get the literal string "index" back. This makes sense, since @RestController implies @ResponseBody.

I have a few questions about this in general…

  • Is the right thing to do to use @Controller and explicit @ResponseBody annotations on the methods designed to return JSON?

  • I worry that my Controller classes will grow quite large, as I’ll have two implementations for most of the GET methods (one to return the HATEOAS JSON, one to return HTML with a lot more stuff in the model). Are there recommended practices for factoring this?

Advice is appreciated. Thanks!

like image 251
Rick Avatar asked Mar 11 '23 19:03

Rick


2 Answers

Is the right thing to do to use @Controller and explicit @ResponseBody annotations on the methods designed to return JSON?

It is as long as your controllers are small and contain only few methods.

I worry that my Controller classes will grow quite large, as I’ll have two implementations for most of the GET methods (one to return the HATEOAS JSON, one to return HTML with a lot more stuff in the model). Are there recommended practices for factoring this?

If they grow and become hard to read split into one @Controller returning HTML pages and @RestController returning JSON.

To summarise, focus on readability. Technically both approaches are correct.

like image 138
Maciej Walkowiak Avatar answered Mar 13 '23 22:03

Maciej Walkowiak


@RestController
public class SampleController {    

@GetMapping(value = "/data/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public CustomClass get(@PathVariable String id) {
    return newsService.getById(id);
}

@GetMapping(value = "/data/{id}", produces = MediaType.TEXT_HTML_VALUE)
public String getHTML(@PathVariable String id) {
    return "HTML";
}

}

like image 33
Vazgen Torosyan Avatar answered Mar 14 '23 00:03

Vazgen Torosyan