Reputation: 1487
What I would like to achieve is to pass parameters from jquery to a Spring Controller. I was successful in passing simple parameter (one string) from jquery to Spring bu how can I do the same with complex data?
For example: in Spring I expect a POJO as input parameter and this POJO has a String property and a List property.
POJO:
public class SimplePojo {
private String one;
private List<String> two;
...
}
Spring Controller:
@RequestMapping(value = "/something", method = RequestMethod.POST)
public @ResponseBody String check(@RequestParam(????) SimplePojo input) { ... }
JQuery
jq.post("/something", ????, function(data){ ... });
I put question marks to the places where I have no idea what to write :)
Could you please help me?
Thanks, Viktor
Upvotes: 1
Views: 1635
Reputation: 8146
In js :
ajax.get('api/checkout_patron/patron_id='+self.patronId())
In java :
@RequestMapping(method= RequestMethod.GET,value = "/patron_id={patron_id}")
public @ResponseBody
Response getPatron(@PathVariable String patron_id){
}
Here js request I have mapped using :
@Controller
@RequestMapping(value = "/api/checkout_patron")
on before class declaration.
Here I am using knockout js
, so I am using this pattern to pass request.
Second Small Example with my technique :
var form={
sourceName : self.sourceName(),
sourceEmail :self.email()
}
ajax.post('api/source',JSON.stringify(form)).done(function(response){
});
Here Get data :
@RequestMapping(method= RequestMethod.POST,consumes = "application/json")
public @ResponseBody
ResponseEntity<IWebApiResponse> addBudget(@RequestBody AddBudgetSourceForm form){
//your code to process data
}
AddBudgetSourceForm class :
public class AddBudgetSourceForm {
private String sourceName;
private String sourceEmail;
// getter and setter
}
Keep one thing in mind that name of form class and in js form
data-bind should be same (i.e. left side of parameter in js form that have been stringified).
UPDATE :
You can do something like following :
List<String> var = new ArrayList<>();
var.add(form.getSourcename());
var.add(form.getSourceEmail());
and yes you can send data like that in json.
If you are sending single data for each thing then don't use List
.
Instead of that use List<classname>
and define all required variable in class
with getter-setter
.
Upvotes: 2