I am trying to send a complex object to ajax controller for spring mvc search engine, with 3 variables: the current page, items per page and the search parameters. The problem is that with the declaration of the controller method does not take me the params variable as a Map.
As I can send the structure to collect on the controller 3 variables separately?
Error:
Required Map parameter 'params' is not present
var dataToSend = {
'page': 1,
'itemsPerPage': 10,
'params': {
'codItem': "10",
'nameItem': "foo"
}
};
$.ajax({
url: form.attr("action"),
type: 'POST',
data: JSON.stringify(dataToSend),
dataType: 'json',
cache: false
}).success(function(data) {
callback(data);
});
public @ResponseBody HashMap<String, Object> search(@RequestParam(value="params") Map<String, String> params, @RequestParam(value = "page") int page, @RequestParam(value = "itemsPerPage") int itemsPerPage){
};
You could simply inject the
HttpServletRequest
into your Controller method and read the body yourself as shown below :OutPut :
{"page":1,"itemsPerPage":10,"params":{"codItem":"10","nameItem":"foo"}}
You can read this attributes by converting this string into JSON Object by using JSON API sunch as GSON. Or create POJO that contain all your attributes define in JSON and convert your Json strig directly to POJO object.
Sample Code :
May this help you.
To do this properly you need to use JSON library. Spring is bundled with Jackson.
First you need to create class to represent your JSON.
You need to change $.ajax, send data like this { data : JSON.stringify(dataToSend)}, becouse parameter need, a name.
In your controller method write this:
If you have getter for MyJson params field you can iterate over json.getParams() map.
I have solved the problem as follows:
The problem is that it works for the structure of the example, if I try to pick up the form parameters, sends me not as a json:
Result:
And serializeArray():
itemsPerPage 5 page 1
As I can send it as in the structure of dataToSend? the only way is to go through the parameters?
My enviroment: AngularJs, SpringMVC, Gson jsonobject
Usually if i send a complex json object from font end to back end, i will do a generic way like below to handle it.
first:
i use angularJs to submit a formatted json string, i believe using jquery ajax will be the same, just need to be sure that data u sent is json formatted string. https://docs.angularjs.org/api/ng/function/angular.toJson
second:
u can watch the json content is pass to mvc controller, and in controller u can use Gson to convert and to json object.