0

I am using spring mvc. I need to pass a json object from my jsp page to controller.

My ajax code:

function createJSON() {
    jsonObj = [];
    item = {};
    $(".values").each(function() {

        var code = $(this).attr('id');
        item[code] = $('#' + code).val();
    });

    var content=JSON.stringify(item)


    $.ajax({
        type: 'POST',
        contentType : 'application/json; charset=utf-8',
        url: "/pms/season/submit", 
        data: content,
        dataType: "json",
        success : function(data) {  
            alert(response);   
        },  
        error : function(e) {  
            alert('Error: ' + e);   
        }  
    });                                                         
}

My controller code:

@RequestMapping(value = "/submit", method = RequestMethod.POST)
public void saveNewUsers( @RequestParam ("json") String json) {
    System.out.println( "json  ::::"+json );
}   

But it's not working.

1
  • When you say it is not working -- what is it doing? You can improve your question if you describe how it is going wrong Commented Aug 18, 2015 at 12:33

1 Answer 1

3

@RequestParam("json") means that you are intending to include a request parameter called json in the URI, i.e. /submit?json=...

I think you intend to get the request body, i.e. @RequestBody.

I would then suggest that, unless you really need the raw JSON string, you would have the @RequestBody translated to a Java object for you:

public void saveNewUsers(@RequestBody MyDto myDto) {
...
}

where MyDto would have getters/setters and fields matching the JSON class.

You can over omit the @RequestBody annotation if you annotate the controller with @RestController, instead of @Controller.

If you definitely want the raw JSON string, then take a look at this previous question: Return literal JSON strings in spring mvc @ResponseBody

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.