HTTP 状态 406.Spring MVC 4.0、jQuery、JSON [英] HTTP Status 406. Spring MVC 4.0, jQuery, JSON

查看:34
本文介绍了HTTP 状态 406.Spring MVC 4.0、jQuery、JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的控制器发送 JSON.我有以下配置.

I want to send JSON from my controller. I have the following configuration.

spring-servlet.xml :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <mvc:annotation-driven/>

    <mvc:resources mapping="/resources/**" location="/resources/"/>
    <context:component-scan base-package="com.castle.controllers"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

.js :

function testAjax() {
    var data = {userName: "MyUsername", password:"Password"};
    $.ajax({
        url: 'ajax/test.htm',
        dataType : 'json',
        type : 'POST',
        contentType: "application/json",
        data: JSON.stringify(data),
        success: function(response){
            alert('Load was performed.');
        }
    });
}

UserTest.java:

public class UserTest {
    private String userName;
    private String password;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

TestAjaxController.java :

@Controller
@RequestMapping("/ajax")
public class TestAjaxController {

    @RequestMapping(method = RequestMethod.POST, value = "/test.htm")
    public @ResponseBody
    UserTest testAjaxRequest(@RequestBody UserTest user) {
        return user;
    }
}

pom.xml :

    <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-asl</artifactId>
                <version>1.9.13</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-core-asl</artifactId>
                <version>1.9.13</version>
</dependency>

当我执行此请求时,我进入了表示为 UserTest 对象的控制器 JSON.但是回来后:

When i do this request, i get in my Controller JSON represented as UserTest object. But on return :

HTTP 状态 406 - 此请求标识的资源只能生成具有根据请求接受"标头不可接受的特征的响应.

HTTP Status 406 - The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

我做错了什么?我知道,这种情况有很多问题,但我2天都无法修复......

What i'm doing wrong? I know, there is a lot of questions about such cases, but i can't fix it for 2 days...

更新我找到了解决方案!!它只需要返回一个对象.不是 User 对象什么的.但返回对象;

UPDATE I Have found the solution!! It's only need to return an Object. Not a User object or something. But return Object;

 public @ResponseBody Object testAjaxRequest(@RequestBody UserTest user) {
        List<UserTest> list = new ArrayList<>();
        list.add(user);
        list.add(user);
        list.add(user);
        return list;

推荐答案

这里的主要问题是路径 "/test.htm" 在检查值之前将首先使用内容协商Accept 标头.对于像 *.htm 这样的扩展,Spring 将使用 org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy 并解析返回的可接受媒体类型是 text/htmlMappingJacksonHttpMessageConverter 产生的不匹配,即.application/json 因此返回 406.

The main issue here is that the path "/test.htm" is going to use content negotiation first before checking the value of an Accept header. With an extension like *.htm, Spring will use a org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy and resolve that the acceptable media type to return is text/html which does not match what MappingJacksonHttpMessageConverter produces, ie. application/json and therefore a 406 is returned.

简单的解决方案是将路径更改为类似 /test 的内容,其中基于路径的内容协商不会为响应解析任何内容类型.相反,基于标头的不同 ContentNegotiationStrategy 将解析 Accept 标头的值.

The simple solution is to change the path to something like /test, in which content negotiation based on the path won't resolve any content type for the response. Instead, a different ContentNegotiationStrategy based on headers will resolve the value of the Accept header.

复杂的解决方案是更改在处理您的 @ResponseBodyRequestResponseBodyMethodProcessor 中注册的 ContentNegotiationStrategy 对象的顺序.

The complicated solution is to change the order of the ContentNegotiationStrategy objects registered with the RequestResponseBodyMethodProcessor which handles your @ResponseBody.

这篇关于HTTP 状态 406.Spring MVC 4.0、jQuery、JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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