带有 JSON 和 JSP 的 Spring MVC 控制器 [英] Spring MVC Controller with JSON and JSP

查看:64
本文介绍了带有 JSON 和 JSP 的 Spring MVC 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

控制器中的相同方法是否可以同时用于 JSP 和其他 MIME 类型(如 XML 和 JSON)?

Can the same method in a controller be used for both JSP and other MIME types (like XML and JSON)?

我知道以下几种在 Spring MVC 中解析视图的方法.

I know of the following ways to resolve views in Spring MVC.

  1. 返回带有视图名称的 String 并将属性添加到 ModelModelMap
  2. 返回带有视图名称和模型的 ModelAndView
  3. 返回带有 @ResponseBody 注释的 Object
  1. Return a String with the view name and add attributes to the Model or ModelMap
  2. Return a ModelAndView with the view name and model
  3. Return an Object with a @ResponseBody annotation

我在处理 JSP 时使用 1 或 2,当我想返回 JSON 或 XML 时使用 3.

I use 1 or 2 when I am dealing with JSP and 3 when I want to return JSON or XML.

我知道我可以使用两种方法并使用 @RequestMapping(headers="accept=application/xml")@produces 批注来定义它们的 MIME 类型句柄,但是否可以只用一种方法来做到这一点?

I know I can use two methods and with the @RequestMapping(headers="accept=application/xml") or @produces annotations to define which MIME types they handle, but is it possible to do this in just one method?

控制器逻辑非常简单,映射两个不同的方法返回相同的模型似乎是不必要的重复,或者这只是它的完成方式?

The controller logic is pretty simple and it seems like unnecessary duplication to have two different methods mapped which return the same exact model, or is this just simply the way it's done?

推荐答案

是的,这在 Spring MVC 3.x 中很简单...

Yes, this is straight forward in Spring MVC 3.x...

您基本上只为普通 JSP 页面视图编写控制器方法,然后在 Dispatcher servlet 配置中配置一个 ContentNegotiatingViewResolver bean,它查看请求的 MIME 类型(或文件扩展名)和返回适当的输出类型.

You basically write your controller methods for just normal JSP page views and then you configure a ContentNegotiatingViewResolver bean in your Dispatcher servlet config., which looks at the requested mime-type (or file extension) and returns the appropriate output type.

按照此处的说明操作:Spring 3 MVC ContentNegotiatingViewResolver 示例

这篇关于带有 JSON 和 JSP 的 Spring MVC 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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