我创建了这个REST映射,以便它可以接受URI末尾的文件名…
@RequestMapping(value="/effectrequest/{name}/{imagename:[a-zA-Z0-9%\\.]*}",
headers="Accept=*/*", method=RequestMethod.GET,
produces = "application/json")
public @ResponseBody EffectRequest effectRequest(
@PathVariable("name") String name,
@PathVariable("imagename") String imageName)
{
return new EffectRequest(2, "result");
}
它使用MappingJackson2HttpMessageConverter返回JSON内容.我用这个映射测试jQuery AJAX调用…
var effectName = 'Blur';
var imageName = 'Blah.jpg';
var requestUri = '/effectrequest/' + effectName + '/' + imageName;
alert(requestUri);
$(document).ready(function() {
$.ajax({
url: /*[+ [[${hostname}]] + requestUri +]*/
}).then(function(data) {
$('.effect').append(data.id);
$('.image').append(data.content);
});
});
这将生成一个http://localhost/effectrequest/Blur/Blah.jpg的URI,并在调试会话中,在上面的effectRequest()方法中正确接收文件名.但是,客户端或jQuery AJAX调用从服务器收到HTTP 406错误(不可接受),即使RequestMapping中有produce =“application / json”.
经过多次调试后,我缩小了范围 – 当我修改测试javascript代码以生成http://localhost/effectrequest/Blur/Blah.json的URI时,它可以工作.因此,Tomcat或MappingJackson2HttpMessageConverter通过查看URI末尾的文件扩展名并确定我发回的JSON内容不是一个好匹配来导致HTTP 406错误.
无论如何都要覆盖此行为而不必编码. (点)在文件名中?
解决方法:
默认情况下,Spring MVC在尝试确定响应请求的媒体类型时,更喜欢使用请求的路径.这在javadoc for ContentNegotiationConfigurer.favorPathExtension()
中描述:
Indicate whether the extension of the request path should be used to determine the requested media type with the highest priority.
By default this value is set to true in which case a request for
/hotels.pdf
will be interpreted as a request for"application/pdf"
regardless of the Accept header.
在你的情况下,这意味着/effectrequest/Blur/Blah.jpg的请求被解释为对image / jpeg的请求,这使得MappingJackson2HttpMessageConveter尝试编写它无法做的图像/ jpeg响应.
您可以使用通过扩展WebMvcConfigurerAdapter访问的ContentNegotiationConfigurer轻松更改此配置.例如:
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。