406在Spring MVC中返回JSON时不可接受的错误

时间:2017-05-10 08:22:21

标签: java json spring spring-mvc

我正在处理将仅用作restful服务的应用程序,并且响应必须以JSON.y p

返回

我在Spring MVC上并按照这篇文章来实现相同的

https://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/

我在我的POM中添加了Jackson jar,启用了响应体和mvc注释驱动的注释。 但仍然在触发网址时我得到406不可接受的错误。

我尝试使用rest客户端进行触发,并使用“application / json”为Content-Type和Accept添加请求标头。

下面是我的带有依赖项部分的POM

<!-- Spring 3 dependencies -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

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

我的春季配置文件

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<mvc:annotation-driven />
<context:component-scan base-package="com.sap.cf.casestudy.controller" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

我的控制器代码

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sap.cf.casestudy.domain.Employee;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @RequestMapping(method = RequestMethod.GET ,headers="Accept=application/json")
    public @ResponseBody Employee getEmployee() {

        List<Employee> empList = getEmployeeData();
        return empList.get(0);


        //return "employeelist";

    }

    private List<Employee> getEmployeeData(){
        List<Employee> employeeList = new ArrayList<Employee>();
        Employee emp1 = new Employee();
        emp1.setFirstName("Saurav");
        emp1.setLastName("Sarkar");
        employeeList.add(emp1);

        Employee emp2 = new Employee();
        emp2.setFirstName("John");
        emp2.setLastName("Doe");
        employeeList.add(emp1);

        return employeeList;
    }

}

此外,我有一个员工类的POJO,其中firstname和lastname为私有方法,setter / getter为public方法。

最诚挚的问候, Saurav

3 个答案:

答案 0 :(得分:0)

我的简单设定。希望这有点帮助

<强>的pom.xml

<!-- Jackson -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.3</version>
</dependency>

<强> servlet的context.xml中

<!-- DispatcherServlet Context: defines this servlet's request-processing 
    infrastructure -->
<context:component-scan base-package="com.urong.sample" />

<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven>
    <mvc:message-converters>
        <beans:bean
            class="org.springframework.http.converter.StringHttpMessageConverter">
            <beans:property name="supportedMediaTypes">
                <beans:list>
                    <beans:value>text/html;charset=UTF-8</beans:value>
                </beans:list>
            </beans:property>
        </beans:bean>
        <beans:bean
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
    </mvc:message-converters>
</mvc:annotation-driven>

<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
    up static resources in the ${webappRoot}/resources directory -->
<mvc:resources location="/resources/" mapping="/resources/**" />
<mvc:default-servlet-handler />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
    in the /WEB-INF/views directory -->
<!-- Your Resolves -->

<强>控制器

@RequestMapping(value = "/call", method = RequestMethod.POST)
public @ResponseBody String callTest(@RequestBody CompanyLocation location) {
    // use location. this sample object


    return "your return String";
}

客户端(我的javascript)

function callTest() {
    var companyIdx = $('#companyIdx').val();
    var locationIdx = $('#locationIdx').val();

    var data = {
    idx : locationIdx,

    postCode : $('#postCode').val(),
    address : $('#address').val(),
    detailAddress : $('#detailAddress').val(),

    tel : $('#tel').val(),
    fax : $('#fax').val(),
    email : $('#email').val(),
    language : $("#language").val(),

    latitude : $('#latitude').val(),
    longtitude : $('#longtitude').val()

    };

    data = JSON.stringify(data);

    $.ajax({
        url : "/sample/call,
        type : 'POST',
        data : data,
        contentType : 'application/json',

        success : function(response) {

            // use response.

        },

        error : function(request, status, error) {

        },
        complete : function(data) {

        }

    });
}

答案 1 :(得分:0)

我可以用上面的代码解决问题。

问题是类路径中没有杰克逊映射器jar。 所以它没有用。

在Eclipse For Maven项目中,您必须强制更新,以便jar可以进入类路径。

理想情况下,spring框架中应该有关于未加载的类的错误。错误本身就是误导。

最诚挚的问候, Saurav

答案 2 :(得分:0)

Spring 4.3.10:我使用以下设置来解决问题。

步骤1:添加以下依赖项

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

步骤2:在MVC DispatcherServlet上下文配置中添加以下内容:

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>

<bean id="contentNegotiationManager"
        class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <property name="favorPathExtension" value="false"/>
        <property name="favorParameter" value="true"/>
        <property name="ignoreAcceptHeader" value="false" />
    </bean>

从Spring 3.2开始,根据默认配置,favorPathExtension设置为true,因此如果请求uri具有任何适当的扩展名,如.htm,spring将优先考虑扩展名。在第2步中,我添加了contentNegotiationManager bean来覆盖它。