Posted on by & filed under Content - Highlights and Reviews, Web Development.

Spring Web MVC is a framework (part of the Spring framework) that leverages the Model-View-Controller pattern to separate the presentation layer from business logic in a web application. Spring MVC comes with a central component, named DispatcherServlet, in charge of handling the user requests. The DispatcherServlet consults the HandleMapping component to dispatch a request to a Controller. The Controller can write data into a Model map and can return a view name. The DispatcherServlet sends the view name to a ViewResolver and finally the ViewResolver locates a View that renders the model data.

The current version of Spring MVC (version 3) contains a few simplifications for creating RESTful web services.

Annotations for RESTful web services

With Spring 3, developers are strongly encouraged to use annotations. In Spring MVC some of those annotations, such as @Controller, @RequestMapping, @PathVariable, @RequestBody and @ResponseBody, come in really handy to produce and interact with RESTful web services. Find below a code sample of an MVC controller class used to generate a REST style web service.

The @Controller annotation is used to mark the BookController class as a MVC controller. This controller is mapped to the /books URI through the @RequestMapping annotation, so that all the requests with a URI path starting with /books will be dispatched to the above controller.

The @RequestMapping annotation doesn’t annotate just a class, but can also be used to map a URI to a method in the controller. In our example, all of the methods (getBook, setBook, updateBook and deleteBook) of the BookController will be invoked for the same resource, but they have different HTTP methods associated to them through the RequestMethod. This is because REST allows you to access resources using various HTTP methods (GET, POST, PUT, DELETE). Each of those methods is associated to the CRUD (Create, Read, Update and Delete) operations for the domain model (Book class in this case).

Maybe the most interesting annotation for REST features though is @PathVariable that handles URL templates. In the above code, the path variable {name} is mapped to a String object (@PathVariable(“name”) String name). Therefore all of the URI such as /books/xx or /books/yy will map to the methods in the controller.

The @ResponseBody annotation is used to marshall the return value into the HTTP response body. Spring comes with converters that convert the Java object into a format understandable for a client. The @RequestBody annotation, instead, unmarshalls the HTTP response body into a Java object injected in the method.

What you return from the methods in the controller is typically the view name that displays what you store in the Model model.

I mentioned previously how all of the four HTTP methods are used in REST and how we can map them to different actions, but you may also wonder how you can make a PUT or DELETE request, as in HTML, if only GET and POST are allowed. Spring MVC 3 offers a Servlet Filter, called HiddenHttpMethodFilter, to set a hidden parameter containing the wanted HTTP method when you submit a request. In your view, you just need to specify the method in the method attribute of the Spring form tag, as shown here:

Content negotiation and RestTemplate

In a RESTful scenario, we commonly mention the concept of Content Negotiation. The idea behind it is that the client may need a resource, but under different representations such as /books/xx.html or /books/xx.json or even /books/xx.xml. The server needs to serve the right content format containing the same content across the different requests. Spring MVC uses the ContentNegotiatingViewResolver for content negotiation. This view resolver, different from the other view resolvers, doesn’t dispatch to a view, but delegates to another view resolver in charge of taking care of a specific format.

The ContentNegotiatingViewResolver observes the file extension or the Accept header (set by the client) and compare the media type requested with the available ones. If the appropriate media type is found, the related ViewResolver will provide the proper view. For example, requesting a .html resource, a resolver such as InternalResourceViewResolver may be called; requesting a .json resource, the MappingJacksonJsonView view will handle the request; but requesting a .xml resource, the MarshallingView will be invoked.

In AJAX applications, this can be especially valuable:
returning a Java object and adding the @ResponseBody annotation, the ContentNegotiatingViewResolver understands how to convert the Java object into JSON using the MappingJacksonJsonView.

Bear in mind that, behind the scene, MappingJacksonJsonView uses the MappingJacksonHttpMessageConverter to read and write JSON into Java objects.

MappingJacksonHttpMessageConverter is one of the implementation of the common interface HttpMessageConverter, used to convert objects into HTTP request body and HTTP response into objects. This interface is also used by the Spring RestTemplate class, which emulates a client calling RESTful services. RestTemplate contains different methods invoking the various HTTP methods. Find below an example using the getForObject method for a GET request:

You now have some guidance for using Spring MVC (version 3) when creating RESTful web services.

Safari Books Online has the content you need

Here are some Spring books from Safari Books Online:

Totally revised for Spring 3.0, Spring in Action, Third Edition is a hands-on guide to the Spring Framework. It covers the latest features, tools, and practices including Spring MVC, REST, Security, Web Flow, and more.
The release of Spring Framework 3 has ushered in many improvements and new features. Spring Recipes: A Problem-Solution Approach, Second Edition continues upon the bestselling success of the previous edition but focuses on the latest Spring 3 features for building enterprise Java applications.
Spring Batch in Action is an in-depth guide to writing batch applications using Spring Batch. Written for developers who have basic knowledge of Java and the Spring lightweight container, the book provides both a best-practices approach to writing batch jobs and comprehensive coverage of the Spring Batch framework.
Spring Web Services 2 Cookbook includes a wide variety of recipes that covers most important topics used in real-world applications. It is a well-rounded guide covering a lot of ground in the Spring Web Services domain using systematic arranged chapters and focused recipes.
Getting Started with Roo is a short introduction to Roo that will hopefully motivate you to dive deeper and possibly become an active contributor on the project. After all, a lot of the power in Spring Roo comes from addons and yours would be warmly welcomed.

About this author

Sebastiano Armeli-Battana is software engineer focused on JavaScript and Java development and he is really passionate about Web technologies. He works as consultant in SMS Management & Technology adopting Java technologies and he also works as Web freelancer. He is the author of a jQuery plugin called JAIL and he maintains his personal site at http://www.sebastianoarmelibattana.com.

Tags: MVC, RESTful web services, spring, Spring Web MVC,

Trackbacks/Pingbacks

  1.  Spring MVC Tip: Returning JSON from a Spring Controller « Safari Books Online's Official Blog
  2.  Spring MVC Tip: Using The Spring RestTemplate « Safari Books Online's Official Blog