Reputation: 1356
I have a javascript function that makes a post to a controller API. Here´s the code:
exports.importList = function (req, res) {
res.setHeader('Content-Type', 'application/json');
var agencyId = req.user.agency_id;
var userId = req.user.id;
data = {
id_list: req.body.ids,
remoteHost:'127.0.0.1',
userId : userId,
agencyId:agencyId
};
call = '/ilist/importer/list/'; //Spring route
fetcher.post(call, 'post', data, function (err, result) {
console.log(data);
})
}
req.body.ids
is an array of string values, so the data I want to send to my Controller has this structure:
{ id_list: [ '2147041', '2155271' ],
remoteHost: '127.0.0.1',
userId: 'user',
agencyId: 1 }
My controller method:
@RequestMapping(value="/list/", method = RequestMethod.POST, headers = "Accept=application/json")
public @ResponseBody RemaxResponse importPropertyList(@RequestBody ArrayList<String> data ) {
List<Long> ids = new ArrayList<>();
for (String id : data.id_list) {
ids.add(Long.valueOf(id));
}
response = ilistIImporterService.importPropertyList(ids);
return response;
}
I need to take in my Controller the array of strings and store it in an array of integer, and the other parameters store in integer variables. Now, I'm getting that the data I send from javascript is sintactically incorrect. What's the proper way to do this?
Upvotes: 1
Views: 212
Reputation: 73241
If you want to send the whole object, I'd create a pojo and use that as @RequestBody
like
public @ResponseBody RemaxResponse importPropertyList(@RequestBody RequestObject data ) {
Now spring can parse the whole data nicely to the given pojo, and you can simply use the getters
to obtain the data you need.
A pojo could look like
public class RequestObject {
private List<Long> idList = null;
private String remoteHost;
private String userId;
private Integer agencyId;
public List<Long> getIdList() {
return idList;
}
public void setIdList(List<Long> idList) {
this.idList = idList;
}
public String getRemoteHost() {
return remoteHost;
}
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Integer getAgencyId() {
return agencyId;
}
public void setAgencyId(Integer agencyId) {
this.agencyId = agencyId;
}
}
Upvotes: 3