java - 文件扩展名上的spring requestmapping http错误406

标签 java ajax json http-headers spring-boot

我已经创建了这个 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在调试 session 中,文件名在上面的 effectRequest() 方法中被正确接收。但是,客户端或 jQuery AJAX 调用从服务器接收到 HTTP 406 错误( Not Acceptable ),即使 RequestMapping 中有 produces = "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 尝试编写它无法执行的 image/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);
    }
}

关于java - 文件扩展名上的spring requestmapping http错误406,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121450/

相关文章:

java - 在 Hibernate/JPA 中删除对象并自动取消子对象

python - 具有多个嵌套对象的 Django Rest Framework 可写嵌套序列化程序

javascript - Ajax 动态选择表单未提交值

json - 如何从 Groovy 中的 JSON(字符串)获取值

java - 我正在尝试使用 ServletConfig 接口(interface)加载我的 sql jdbc 驱动程序

java - Android 中的游标 NotSerializedException

php - 使用 jquery ajax 和 php 将动画表单提交到 mysql 数据库

django - 将具有反向一对一字段的 Django 模型序列化为 JSON

javascript - 回调中的 Socket.io-emit 给出 SyntaxError : Unexpected end of JSON input

java - 未找到 bean NoSuchBeanDefinitionException