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!
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.
@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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With