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

百般思念 提交于 2019-12-10 11:26:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!