Spring MVC Ajax POST

21,989

Solution 1

You need to specify the below code inside of the request mapping annotation

@RequestMapping(value = "/register/checkUsername.html", method = RequestMethod.POST,  consumes=MediaType.APPLICATION_JSON_VALUE)

you no need to specify the produces attribute because @Responsebody will produce the content based on the request object content type[optional]. if you want other then it then only you have to mention it.

; charset=utf-8 is the default one in Ajax call. you no need mention it separately. try do these changes.

Solution 2

use @ResponseBody need object to json, seems missing some jar file (jackson-mapper-asl.jar and jackson-core-asl.jar) try to import it

Solution 3

First check if your controller is returning a JSON. You can use any REST client and see what is the return header. If not then add the Jackson mapper bean.

Also, try setting the Accept header in the ajax call.

$.ajax({
  headers: { 
    Accept : "application/json",
    Content-Type: "application/json"
  },
  data: "data",
  ...
})

Solution 4

in .js(java script) ajax function

var variable="test";
$.ajax({
    url: baseUrl + "nameController/test1",
    async: false,
    data: {val: variable},
    dataType: 'html',
    success: function (dat) {
        console.log(dat);
    }
});

you create nameController.java controller

@RequestMapping(value = "test1", method = RequestMethod.POST)
public @ResponseBody
String checkRoomStatusReservation(@RequestParam(value = "val", required = true) String parse) {
    System.out.println("parse"+parse);
    //value from parse=test
return parse;
}

you can try this

Share:
21,989
Rapidistul
Author by

Rapidistul

Updated on September 03, 2020

Comments

  • Rapidistul
    Rapidistul almost 4 years

    I'm trying to post a JSON Object, with Ajax, to an Rest Spring MVC Controller, but I met some troubles.

    Let's present you my code:

    Controller

    @RequestMapping(value = "/register/checkUsername.html", method = RequestMethod.POST,  produces=MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody JsonResponse checkUsername(@RequestBody JsonUsername username) {
        String usernameString = username.getUsername();
        JsonResponse response = new JsonResponse();
        response.setMessage(usernameString + "Available");
        return response;
    }
    

    Ajax Function

       function displayUsernamError(data) {
        var json = "<h4>Eroare</h4><pre>"
                + JSON.stringify(data, null, 4) + "</pre>";
        $('#usernameError').html(json);
    }
    
    function checkUsername(){
        var username = document.getElementById("username");
        var search = {
                "username" : username.value
        }
    
        $.ajax({
                type : "POST",
                contentType : 'application/json; charset=utf-8',
                dataType : 'json',
                url : "http://localhost:8080/skill-assessment/register/checkUsername.html",
                data : JSON.stringify(search),
                success : function(result) {
                    console.log("SUCCESS: ", data);
                    displayUsernamError(result);
                },
                error: function(e){
                    console.log("ERROR: ", e);
                    displayUsernamError(e);
                },
                done : function(e) {
                    console.log("DONE");
                }
        });
    }
    

    And finally the html form:

    <form:form modelAttribute="user" method="POST" enctype="utf8">
            <tr>
                <td><label>Username</label></td>
                <td><form:input path="name" id="username" /></td>
                <td>
                <p id="usernameError">
                </p>
                </td>
            </tr>
            <button type="button" onClick="checkUsername()">Register</button>
        </form:form>
    

    So, I'm calling the checkUsername method when I press click on the Register button, only for test.

    The ajax function is called and this send the JSON to the controller. I used the debug and the controller seems to get the JSON Object.

    The problem is with the controller Response, because in the error div from my html page, I get this error:

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

    Where is the problem? Who can give me an idea?