简体   繁体   中英

Returning view from Spring MVC @RestController

As @RestController is composition of @Controller and @ResponseBody , I believe if I want my controller to work as both MVC and REST controller just annotating with @RestController should be fine. Is that correct?

As @RestController is composition of @Controller and @ResponseBody, I think it internally means that it's good for

  1. Receiving the http request (because of @Controller )
  2. Sending the response in JSON format (because of @ResponseBody ) though it can be changed if required

@RestController is not meant to be used to return views to be resolved. It is supposed to return data which will be written to the body of the response, hence the inclusion of @ResponseBody . You can not selectively disable the @ResponseBody on individual handler methods when @ResponseBody is already annotation on class level.

You can work around it by returning ModelAndView , which will work even in @RestController , but you really shouldn't :

@RequestMapping
public ModelAndView renderFooList() {
    ModelAndView mav = new ModelAndView("foo/list");
    mav.addObject("foos", fooService.getFoos());
    return mav;
}

It would be better to create separate controllers for normal handlers returning views and REST controllers for the RESTful stuff. Or to annotate the class with plain @Controller and put @ResponseBody on the methods where you actually need it.

@RestController annotation, which marks this class as a controller where every method returns a domain object/pojo instead of a view. It means that we are no more using view-resolvers, we are no more directly sending the html in response but we are sending domain object converted into format understood by the consumers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM