从Spring MVC @RestController返回视图 [英] Returning view from Spring MVC @RestController

查看:445
本文介绍了从Spring MVC @RestController返回视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

As @RestController @Controller @ResponseBody ,我相信如果我希望我的控制器工作,因为
MVC和REST控制器只需用 @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 @Controller @ResponseBody,我认为它内部意味着它有利于

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


  1. 接收http请求(因为 @Controller

  2. 以JSON格式发送响应(因为 @ResponseBody )虽然可以根据需要进行更改

  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 并不意味着用于返回要解析的视图。它应该返回将被写入响应主体的数据,因此包含 @ResponseBody 。当 @ResponseBody 已经在类级别注释时,您无法有选择地禁用单个处理程序方法上的 @ResponseBody

@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.

你可以通过返回 ModelAndView 解决它,它甚至可以在 @RestController中工作,但你真的不应该

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;
}

为返回视图和REST控制器的普通处理程序创建单独的控制器会更好对于RESTful的东西。或者使用普通的 @Controller 注释该类,并将 @ResponseBody 添加到您实际需要的方法上。

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.

这篇关于从Spring MVC @RestController返回视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆