Spring RESTful Web Service with JSON 给出 HTTP 406 错误代码

问题描述:

我正在使用 Spring 3.2.5 创建一个 RESTful Web 服务.为了实现它,我使用了 @ResponseBody 标签.当我使用 InternalResourceViewResolver 并尝试加载 Html 响应时,它工作正常.但是当我调用一个标记为 @ResponseBody 的 URL 时,它会给出 HTTP 406 错误代码,错误文本为

I am using Spring 3.2.5 to create a RESTful web service. To implement it I've used @ResponseBody tag. When I use InternalResourceViewResolver and try to load Html response then it is working fine. But when I call a URL which is marked as @ResponseBody then it gives HTTP 406 error code with error text as

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

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

我的 lib 目录中也包含了 Jackson jar 文件.

I have included Jackson jar files in my lib directory as well.

这是我处理服务请求的控制器方法.

Here is my controller method which handles service request.

@ResponseBody
@RequestMapping (value = "/resp.htm")
public Data jsonResp() {
    Data d = new Data();

    d.setName("TEst");
    d.setAddr("Address....");

    return d;
}

问了很多问题&回答,我已经尝试了很多,但它仍然给出相同的结果.然后我遇到了一种新的答案,它声明使用 ContentNegotiatingViewResolver.通过使用它,我能够以预期的格式查看响应.那是 JSON 格式.

There are lots of questions have been asked & answered, I've tried many of them, but it still gives the same result. Then I came across a new kind of answer, which was stating to use ContentNegotiatingViewResolver. By using it I am able to view response in intended format. That is JSON format.

使用ContentNegotiatingViewResolver后,servlet调度器代码如下所示:

After using ContentNegotiatingViewResolver, servlet dispatcher code looks like this:

<bean
    class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="order" value="1" />
    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json" />
        </map>
    </property>

    <property name="defaultViews">
        <list>
            <!-- JSON View -->
            <bean
                class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
            </bean>
        </list>
    </property>
    <property name="ignoreAcceptHeader" value="true" />
</bean>

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="order" value="2" />
    <property name="prefix" value="/WEB-INF/view/" />
    <property name="suffix" value=".jsp" />
</bean>

那么,我的问题是,每当我们需要使用 Spring 的 Web Service 功能时,我们是否必须要求具有 ContentNegotiatingViewResolver?

So, my question is, whenever we require to use Spring's Web Service feature, do we must require to have ContentNegotiatingViewResolver?

添加 gson 在您的类路径中.以及 jackson

Add gson in your class path. as well as jackson