Return View from Spring MVC @RestController

Since @RestController is the composition of @Controller and @ResponseBody , I believe that if I want my controller to work as an MVC and REST Controller, just annotating with @RestController should be accurate. It is right?

Since @RestController is the composition of @Controller and @ResponseBody, I think that internally means that it is good for

  • Receiving http request (due to @Controller )
  • Sending a response in JSON format (due to @ResponseBody ), although it can be changed if necessary
+5
source share
2 answers

@RestController not intended to return allowed permissions. It is supposed to return the data that will be written to the response body, therefore, the inclusion of @ResponseBody . You cannot selectively disable @ResponseBody for individual handler methods when @ResponseBody already a class level annotation.

You can get around it by returning a ModelAndView that 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 regular handlers that return views and REST controllers for RESTful stuff. Or, comment on the class with a simple @Controller and put @ResponseBody in the methods you really need.

+9
source

@RestController annotation, which marks this class as a controller, where each method returns a / pojo domain object instead of a view. This means that we no longer use view-resolvers, we can’t directly send html in response, but we send a domain object converted to a format that consumers understand.

+2
source

Source: https://habr.com/ru/post/1233458/


All Articles