Reputation: 744
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.
Upvotes: 0
Views: 3181
Reputation: 642
@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
Upvotes: 3