Spring MVC + Jquery Ajax shows 406 error?

2019-08-18 05:28发布

问题:

I have searched a lot and cant find a solution.Similar threads are also in our stack overflow.But no use.So I have created a new thread.

My JSP is ,

<boby>
<% System.out.println("request.getContextPath() : "+request.getContextPath()); %>
<h1>Spring_JsonTest Example</h1>
    <table>
        <tr><td colspan="2"><div id="error" class="error"></div></td></tr>
        <tr><td>Enter your name : </td><td> <input type="text" id="name"><br/></td></tr>
        <tr><td>Your Education : </td><td> <input type="text" id="education"><br/></td></tr>
        <tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
        <tr><td colspan="2"><div id="info" class="success"></div></td></tr>
    </table>    
</body>

My Jquery is ,

function doAjaxPost() {  
      // get the form values  
      var name = $('#name').val();
      var education = $('#education').val();

      $.ajax({  
        type: "POST",  
        url: contexPath + "/AddUser.html",  
        data: "name=" + name + "&education=" + education,
        success: function(response){
          // we have the response 
          if(response.status == "SUCCESS"){
          userInfo = "<ol>";
          for( i =0 ; i < response.result.length ; i++){
              userInfo += "<br><li><b>Name</b> : " + response.result[i].name + 
              ";<b> Education</b> : " + response.result[i].education;
          }
          userInfo += "</ol>";
          $('#info').html("User has been added to the list successfully. " + userInfo);
          $('#name').val('');
              $('#education').val('');
              $('#error').hide('slow');
              $('#info').show('slow');
          }else{
          errorInfo = "";
          alert("Success response : "+response)
          for( i =0 ; i < response.result.length ; i++){
              errorInfo += "<br>" + (i + 1) +". " + response.result[i].code;
          }
          $('#error').html("Please correct following errors: " + errorInfo);
          $('#info').hide('slow');
          $('#error').show('slow');
          }       
        },  
        error: function(xhr, ajaxOptions, thrownError)
            alert("status :"+xhr.status+"\nthrownError : "+thrownError+"\nresponseText : "+xhr.responseText);
            alert('Error: ' +xhr.description);  
        } 
      });  
    }  

My Controller is ,

@Controller
public class UserController {
    private List<User> userList = new ArrayList<User>(); 

    @RequestMapping(value="/AddUser.html",method=RequestMethod.POST)
    public @ResponseBody JsonResponse addUser(@ModelAttribute(value="user") User user, BindingResult result ){
        System.out.println("Add user POST method");
        JsonResponse res = new JsonResponse();
        ValidationUtils.rejectIfEmpty(result, "name", "Name can not be empty.");
        ValidationUtils.rejectIfEmpty(result, "education", "Education not be empty");
        if(!result.hasErrors()){
            userList.add(user);
            res.setStatus("SUCCESS");
            res.setResult(userList);
        }else{
            res.setStatus("FAIL");
            res.setResult(result.getAllErrors());
        }

        return res;
    }

}

My JsonResponse.java is,

package com.tps.jsonTest.service;

public class JsonResponse {
    private String status = null;
    private Object result = null;
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public Object getResult() {
        return result;
    }
    public void setResult(Object result) {
        System.out.println("Result : "+result.toString());
        this.result = result;
    }

}

and My User.java is,

package com.tps.jsonTest.service;

public class User {

    private String name = null;
    private String education = null;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEducation() {
        return education;
    }
    public void setEducation(String education) {
        this.education = education;
    }

}

In my console,

Add user POST method
Name : Anand
Education : B.E
Result : [com.tps.jsonTest.service.User@df2940]

Jar files I have used are,

commons-logging-1.1.1.jar
jackson-core-asl-1.9.12.jar
jackson-mapper-asl-1.9.12.jar
log4j-1.2.9.jar
servlet-api-2.4.jar
spring-aop-3.2.2.RELEASE.jar
spring-beans-3.2.2.RELEASE.jar
spring-context-3.2.2.RELEASE.jar
spring-context-support-3.2.2.RELEASE.jar
spring-core-3.2.2.RELEASE.jar
spring-expression-3.2.2.RELEASE.jar
spring-web-3.2.2.RELEASE.jar
spring-webmvc-3.2.2.RELEASE.jar

In my browser the error would be,

I cant parse the object using jquery and it moves on the error.Hope our stack users will help me.

Good answers are definitely appreciated.Thank you.

回答1:

This is a problem in Spring 3.2.2 or 3.2.3 or 3.2.4. I have tried the same example in Spring 3.0.0 and Spring 3.1.4 it is working fine. So change the spring jars and give a try.

Regards Madhu



回答2:

I had the same issue. I am using Spring 3.2 with UrlBasedViewResolver.

For all ajax calls it was giving 406. I tried changing headers, dataType all above solutions but nothing worked. Then I found jackson jars are missing. I added below 2 jars and it started working fine for me.

jackson-core-asl-1.9.4.jar jackson-mapper-asl-1.9.4.jar



回答3:

Your problem is that the content-type of the response is not acceptable to the request.

Your ajax call does not specify the dataType, so jQuery infers based on the url extension that the response should be of content type text/html, but your server does not know how to convert a pojo into an html!

The solution should be to simply add dataType='json' to your ajax call.

Hope this helps.



回答4:

Since your doing a POST, then your data should not be in query string format. Pass a json object for the data parameter instead.

data:{name: name, 
      education: education}