java 从 Spring MVC @RestController 返回视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33062509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning view from Spring MVC @RestController
提问by M Sach
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?
由于@RestController
是组成@Controller
和@ResponseBody
,我相信如果我想我的控制器工作既是MVC和REST控制器只是标注@RestController
应该罚款。那是对的吗?
As @RestController
is composition of @Controller
and @ResponseBody,
I think it internally means that it's good for
由于@RestController
是组成@Controller
和@ResponseBody,
我认为它在内部意味着它的好
- Receiving the http request (because of
@Controller
) - Sending the response in JSON format (because of
@ResponseBody
) though it can be changed if required
- 接收http请求(因为
@Controller
) - 以 JSON 格式发送响应(因为
@ResponseBody
),但如果需要可以更改
回答by Bohuslav Burghardt
@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.
@RestController
并不意味着用于返回要解决的视图。它应该返回将写入响应正文的数据,因此包含@ResponseBody
. @ResponseBody
当@ResponseBody
已经在类级别进行注释时,您不能有选择地禁用单个处理程序方法。
You can work around it by returning ModelAndView
, which will work even in @RestController
, but you really shouldn't:
您可以通过返回来解决它ModelAndView
,即使在 中也可以使用@RestController
,但您真的不应该:
@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.
最好为返回视图的普通处理程序创建单独的控制器,为 RESTful 内容创建 REST 控制器。或者用普通的注解类@Controller
并把@ResponseBody
方法放在你真正需要的地方。
回答by NightsWatch
@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.
@RestController 注释,将此类标记为控制器,其中每个方法返回域对象/pojo 而不是视图。这意味着我们不再使用视图解析器,我们不再直接发送 html 作为响应,而是发送转换为消费者理解的格式的域对象。