Spring MVC 中的内容协商 [英] Content negotiation in Spring MVC

查看:62
本文介绍了Spring MVC 中的内容协商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring 3 编写一个 RESTful Web 应用程序,我的应用程序的一部分需要根据请求的媒体类型来处理数据.

I am writing a RESTful web application with Spring 3, and part of my application needs to process the data according to the requested media type.

@RequestMapping(...)
public String process() {
  if(requested_media_type_is_xml) {
     processXml();
  }
  else if(requested_media_type_is_json) {
     processJson();
  }
  return something;
}

Aka,如果客户端请求不同的媒体类型,我的应用程序逻辑是完全不同的,所以在这种情况下似乎 Spring 的 ContentNegotiatingViewResolver 或消息转换器不是很有用,因为我想将请求路由到不同的处理代码而不是运行相同的代码片段并根据请求的媒体类型以不同的格式呈现它们.

Aka, my application logic is completely different if client requests different media type, so it seems Spring's ContentNegotiatingViewResolver or message converter are not very useful in this case because I want to route the request to different processing code rather than run the same code snippet and render them with different format according to the requested media type.

据我所知,例如在 JAX-RS、Jersey 中,您可以为此使用 @Consume 批注.我想知道 Spring 的方法是什么?谢谢.

As far as I know, in JAX-RS, Jersey for example, you can use @Consume annotation for this. I wonder what is the Spring way to do this? Thanks.

推荐答案

@RequestMapping 注释有一个可选的 headers 属性,允许您将映射缩小到请求特定的标题,例如匹配 XML:

The @RequestMapping annotation has an optional headers attribute that allows you to narrow the mapping to requests with specific headers, e.g. to match XML:

@RequestMapping(value = "/something", headers = "content-type=application/xml")

您还可以指定多个变体:

You can also specify multiple variants:

@RequestMapping(value = "/something", headers = [{"content-type=application/xml","content-type=text/xml"}])

它的级别有点低,但可以完成工作.

It's a little bit low level, but does the job.

这篇关于Spring MVC 中的内容协商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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