Alex Collins is a enterprise Java developer and currently works in the UK. He has worked in the insurance, publishing, telecoms and supply chain. In his spare time he codes in Python, Clojure and Scala (but not at the same time) and enjoys a multitude of sports. His catchphrase is K.I.S.S! Alex has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

Spring 3 and JSON

  • submit to reddit

Spring 3 has brought some excellent features to the table but one that really shines is its REST integration.

You may or may not be wondering what REST really means, I know I did when I heard it banded about for the first time. My first thought - and one that remains today - was that it's another "web 2.0" like marketing phrase that doesn't really mean anything; not entirely fair perhaps, not everyone's as cynical as I.

REST, in essence, means using the HTTP specification properly. For a while now POST has been used as a 'catch all' approach for development, when as per section 9.5 of the spec. it's purely for creating data and is an idempotent method i.e. it shouldn't be used for everything and there are other methods for specific purposes (OK there's more to REST than this, but let's start on familiar ground);

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line 

 So what this basically says is: the server should take the contents of the request body and create an item as it sees fit. You may think this is what we're doing all along, but when - speaking hypothetically - you submit a form to delete a user from your CMS app, POST isn't the right method, DELETE is.

Part of REST is also about abstracting resources so that the data model doesn't matter - a resource will accept JSON, XML or AIML, it's all the same - and behave in the same way. This further opens the door for cross-device interoperability. One example would be to utilise the Accept header from the client to determine how to respond; a request for application/xml would return an XML document. Similarly, your service could respond based on file extensions - .pd, .json, .html and so on.

Spring therefore has extended its annotation based MVC API to provide REST support out of the box, and it's wonderful. For any given controller, you can annotate a method as you would normally but with additional touches you can treat a JSON or standard request the same.


 This annotation, applied at the method parameter level, maps the request body to a type of your choosing. Taking JSON as an example, and a simple bean whose getters & setters (encapsulating your fields) match the properties of the request, Spring will map the request into your bean without any interference your end. It's very neat and tidy. Something like the following would work nicely (in fact, having this and only the mvc:annotation-driven element plus context scanning in my dispatcher-servlet.xml was all I needed to get up and running;

@RequestMapping(value = "/user", RequestMethod.POST)
public String addUser(@RequestBody User user) {
    // do something with,; etc
    return "success";


Much the same as @RequestBody, this serialises the response as necessary. If the client sent its Accept header containing application/json then Spring will convert the response - say a UserBean - to a JSON message ready for the client to consume. All you'd need to do for this is use @ResponseBody on your method's return value - lovely and simple.

Path Variables, Atom, RSS and more

That's not all that's in Spring's bag of RESTful treats (pun?!), most notably of which would be its path variable support. If you've used frameworks in Ruby or Python then this is old hat, but forus Java developers it's not so common.

Given a URI, you include the identifier for the resource you're referring to. So, if you wanted to retrieve an employee you might use a URL structure like "/employee/" and instead of using GET parameters you include the identifier you need e.g. "/employee/alex-collins" or "/employee/1337". This makes for a very customisable site. Here's how you'd use it in an annotated controller:

@RequestMapping(value = "/employee/{id}", RequestMethod.GET)
public @ResponseBody Employee getEmployee(@PathVariable long empID) {
    Employee employee = employeeService.getByID(empID);
    return employee;

 All very fun stuff of course, and there's more. You can get more info over at the Spring documentation.

In the mean time - what's your opinion? Like Spring 3? Using something easier or much more fun? Have you utilised Spring MVC in your organisation for a similar purpose?

Published at DZone with permission of its author, Alex Collins.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Alessandro Santini replied on Fri, 2010/09/17 - 1:50am

I do not use Spring 3 (still did not pass our IP legal check) but the syntax of the resources is very similar to JSR-311.

 P.S.: I think that the method signature

 public @ResponseBody getEmployee(@PathVariable long empID)

misses its return type? (or is it a new syntax I am unaware of?)

Alex Collins replied on Fri, 2010/09/17 - 2:59am in response to: Alessandro Santini

Thanks Alessandro! I've updated the code, it was missing the return type :)

Michael Mok replied on Sun, 2010/09/19 - 9:39pm

Not sure if you have can share your experience with throwing exceptions and returning error messages. I think JAX-RS have a better way of catering for that. Note I have not used any in a serious manner but from googling forums, looks like Spring encapsulate the exeption messages and make it difficult to extract on the client side.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.