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

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

问题描述

由于 @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?

由于 @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;
}

最好为返回视图的普通处理程序创建单独的控制器,为 RESTful 内容创建 REST 控制器.或者用普通的 @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天全站免登陆