Passing Javascript object and object list to Spring controller
2017.01.23 22:23
Passing Javascript object and object list to Spring controller
Passing one Java object from Spring controller to Javascript is quite straightforward, all we have to do is add Jackson dependency in POM file. If the request is for JSON object, Spring automatically converts the Java object to JSON.
When we need to pass Javascript object or object list to Spring controller which will convert this Javascript object or list to Java object or object list, this also can be done using Jackson. First we have to add Jackson dependency to POM file:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
With this Spring will be able to perform the automatic conversion to Java object. The Java object has to use JsonIgnoreProperties annotation so it'll exclude this class name and make it possible to conform to exact JSON format:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
When sending a single object (not list) that Spring controller will accept as a Java object, the JSON format has to be only pair of curly braces with properties inside , avoid using JSON.stringify() which actually adds one more property with object name and Jackson can't match. Following is the Javascript code snippet to pass an object from Javascript to Spring controller:
var person = {"name":"John"};
$.ajax({
url:"/abc/addPerson",
type: 'POST',
data: person,
dataType: "html",
contentType: 'application/json',
mimeType: 'application/json',
success: function(data){
console.log(data);
return false;
}
});
And in Spring controller:
@RequestMapping(value = "/addPerson",
method = RequestMethod.POST)
public @ResponseBody
String addPerson(
@RequestBody Person person)
throws ParseException, IOException {
log.debug("Adding new person");
try {
// perform add operation
return "Successfully added person";
} catch (Exception ex) {
//
}
}
Note that the parameter is with @RequestBody, @RequestParam didn't work for me.
Now, when sending a list of Javascript person object, on Spring controller using Person List will not work because Jackson cannot parse a list, it needs an object to perform parsing. To achieve this we have to create an object which will hold the persons list and Jackson will simply transform it to Java list of Person object. The class will look like this:
@JsonIgnoreProperties(ignoreUnknown = true)
public class PersonList {
List<Person> persons;
public List<Person> getPersons() {
return persons;
}
public void setPersons(List<Person> persons) {
this.persons= persons;
}
}
Now the JSON should have this persons block which will have all persons with properties. Using JSON.stringify() will simply do this:
var persons= [];
var person1 = {"name":"John"};
var person2 = {"name":"Doe"};
persons.push(person1);
persons.push(person2);
persons = JSON.stringify({
'persons' : persons
});
$.ajax({
url:"/abc/addPersons",
type: 'POST',
data: persons,
dataType: "html",
contentType: 'application/json',
mimeType: 'application/json',
success: function(data){
console.log(data);
return false;
}
});
In the controller:
@RequestMapping(value = "/addPersons",
method = RequestMethod.POST)
public @ResponseBody
String addPersons(
@RequestBody PersonList persons)
throws ParseException, IOException {
log.debug("Adding new persons");
try {
// perform add operation
return "Successfully added persons";
} catch (Exception ex) {
//
}
}
That's all, it'll now get the list of Person object in PersonList class.
[출처] https://www.linkedin.com/pulse/passing-javascript-object-list-spring-controller-rashedul-hasan-khan본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.

