Spring框架中使用@RequestMapping时如何匹配通配符accept header
我有三个资源:
@RequestMapping(value = "sample", method = RequestMethod.GET, headers = "Accept=text/html")
public ResponseEntity<String> sampleResourceHtml()
@RequestMapping(value = "sample", method = RequestMethod.GET, headers = "Accept=application/xml")
public ResponseEntity<String> sampleResourceXml()
@RequestMapping(value = "sample", method = RequestMethod.GET, headers = "Accept=application/json")
public ResponseEntity<String> sampleResourceJson()
当 HTTP 客户端使用 Accept=*/* 访问 url 时,Web 应用程序返回 404
在这种情况下,我想调用 sampleResourceHtml()
更改 "Accept=text/html "
到 "Accept=text/html, */*"
将使我的 web 应用程序接受带有 Accept=*/* 的请求,这就是我想要的,但它也会接受带有 Accept 的请求=foo/bar 这是不是我想要的。
如何修改我的代码,以便为包含通配符的请求返回支持的媒体类型,而不为不支持的请求返回意外的媒体类型?
I have three resources:
@RequestMapping(value = "sample", method = RequestMethod.GET, headers = "Accept=text/html")
public ResponseEntity<String> sampleResourceHtml()
@RequestMapping(value = "sample", method = RequestMethod.GET, headers = "Accept=application/xml")
public ResponseEntity<String> sampleResourceXml()
@RequestMapping(value = "sample", method = RequestMethod.GET, headers = "Accept=application/json")
public ResponseEntity<String> sampleResourceJson()
When a HTTP client accesses the url with Accept=*/* the webapp returns a 404
In this case I want to invoke sampleResourceHtml()
Changing "Accept=text/html"
to "Accept=text/html, */*"
will make my webapp accept requests with Accept=*/* which is what I want, however it will also accept requests with Accept=foo/bar which is not what I want.
How do I modify my code to return a supported media type for requests containing wildcards without returning an unexpected media type for unsupported requests?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能会发现使用 AnnotationMethodHandlerAdapter,以便自动处理 Accept 标头,并由 Spring 完成转换,而不是以编程方式完成。
例如,您可以使用以下配置:
并修改控制器以返回 Spring 将转换为所需类型的对象。
注意:您将需要类路径上的相关库。
You might find it easier to configure this in your context with the AnnotationMethodHandlerAdapter, so that the Accept header is automatically handled and the conversion done by Spring and not programmatically.
For example, you could use the following configuration:
And modify the controller to return the object which Spring will convert to the required type.
Note: You will need the relevant libraries on the classpath.