0

What is the most elegant way to read JSON objects in spring mvc when you have only 1 parameter.

When I have many I create an object that will read the post request sent by ajax but in this case, given the fact I am only sending the username parameter, it seems very ugly.

var dataObject = JSON.stringify({
    'username' : 'quentin'
});

$.ajax({
    url : ctx + '/users/edit',
    type : 'POST',
    beforeSend : function(xhr) {
        xhr.setRequestHeader(header, token);
    },
    data : dataObject
});

An attempt is

@RequestMapping(value = "/users/edit", method = RequestMethod.POST)
public String editUser(@RequestBody String username) {

    System.out.println(username);
    return "users/edit";
}

This is obviously wrong and gives the below as result

%7B%22username%22%3A%22quentin%22%7D=

1 Answer 1

1

Please check your content-type Try one of the two.

$.ajax({
        url :'/users/edit',
        type : 'POST',
        contentType: "application/json", //either
        beforeSend: function(xhr) {
         //xhr.setRequestHeader("Content-Type", "application/json"); //or
        },
        data : dataObject,
        success: function(data) {

        }  
});

Before

%7B%22username%22%3A%22quentin%22%7D=

After

{"username":"quentin"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.