Problem with Spring 3 + JSON : HTTP status 406?

前端 未结 5 2221
一整个雨季
一整个雨季 2021-02-09 01:20

I\'m trying to get a list of Cities by sending the State name through Ajax in my SpringMVC 3.0 project. For the purpose, I\'ve used the following call (using jQuery) in my JSP:

相关标签:
5条回答
  • 2021-02-09 01:44

    Using jQuery , you can set contentType to desired one (application/json; charset=UTF-8' here) and set same header at server side.

    REMEMBER TO CLEAR CACHE WHILE TESTING.

    0 讨论(0)
  • 2021-02-09 01:46

    As Peter had written in his comment, the cause of the problem is inability of Spring to load Jackson. It is not loaded by dependencies by default. After I've added the dependency

      <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.2</version>
      </dependency>
    

    the JSON was returned after typing the address in the browser, without any tricks with Accept headers (as it is supposed to do).

    Tested on Tomcat 7.0.

    0 讨论(0)
  • 2021-02-09 01:48

    The problem is not on server side, but on the client one.

    Take a look at the error message carefully: The requested resource (generated by server side) is only capable of generating content (JSON) not acceptable (by the client!) according to the Accept headers sent in the request.

    Examine your request headers:

    Accept  */*
    

    Try this way:

    function getCities() {
        jq(function() {
            jq.post(
                "getCities.html",                          // URL to post to
                { stateSelect: jq("#stateSelect").val() }, // Your data
                function(data) {                           // Success callback
                    jq("#cities").replaceWith('<span id="cities">Testing</span>');
                },
                "json"                                     // Data type you are expecting from server
            );
        });
    }
    

    This will change your Accept header to the following (as of jQuery 1.5):

    Accept: application/json, text/javascript, */*; q=0.01
    

    This will explicitly tell the server side that you are expecting JSON.

    0 讨论(0)
  • 2021-02-09 01:53

    You have incorrect response content type it supposed to be application/json.

    You need to add jackson to your /lib directory.

    and you should have

    <mvc:annotation-driven /> 
    

    In your serlvet-name.xml file.

    In addition I recommend you to map your request as get and try to browse it with Google Chrome,to see if it returns correct result. It has very good json representation.

    0 讨论(0)
  • 2021-02-09 01:55

    I too had a similar problem while using the Apache HTTPClient to call few services. The problem is the client and not the server. I used a HTTPRequester with header accepting application/json and it worked fine.

    0 讨论(0)
提交回复
热议问题