I was curious how to do it using the @RequestBody and @ResponseBody annotations, since this seemed like the most straightforward approach. Luckily, I found a nice link which basically explains the whole process, and adds in some Javascript for good measure. Here's the link:
http://codetutr.com/2013/04/09/spring-mvc-easy-rest-based-json-services-with-responsebody/
Although the code posted doesn't include using both annotions in the same method, it is explained in the comments section. I implemented it as follows:
@RequestMapping(value="person", method=RequestMethod.POST)
@ResponseBody
public Person postPerson(@RequestBody Person person) {
System.out.println("posting " + person.toString());
personService.save(person);
return person;
}
Note how both the input and output parameters are Java objects. This serialization to and from JSON in made possible by the inclusion of a jackson-mapper jar file in the classpath. Also, annotations must be turned on, and the request from the application must include a header indicating it's expecting JSON. See the posted link for more details.
No comments:
Post a Comment