Spring RESTful Web Service with JSON gives HTTP 40

2019-08-29 16:27发布

问题:

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.

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;
}

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.

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>

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

回答1:

Add gson in your class path. as well as jackson



回答2:

The annotation @ResponseBody used with custom class types, generally uses MappingJackson2HttpMessageConverter to convert the object to JSON and return it in application/json content.

Since your request doesn't contain an Accept header for application/json, Spring deems the content it's creating as unacceptable and instead returns a 406.

You could simply change your request to add the Accept header. (You can't do this easily in a browser).



回答3:

In my case the request had .html suffix and received this error. Once removed, it worked fine.



回答4:

All you need to do is to add jackson libraries to your classpath find them Here