问题
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!
回答1:
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.
回答2:
@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";
}
}
回答3:
Instead of a String
you can return a View
or a ModelAndView
:
@RequestMapping(method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
ModelAndView index()
{
return new ModelAndView("index");
}
That allows you to return HTML from controllers annotated with @RestController
.
来源:https://stackoverflow.com/questions/40260292/conditionally-returning-both-json-and-html-templates-from-restcontroller-in-s