Learn with our tutorials and training

developerWorks provides tutorials, articles and other
technical resources to help you grow your development skills
on a wide variety of topics and products. Learn about a specific
product or take a course and get certified. So, what do you want to learn
about?

Featured products

Featured destinations

Find a community and connect

Learn from the experts and share with other developers in one of our
dev centers. Ask questions and get answers with dW answers. Search for local events
in your area. All in developerWorks communities.

Introduction

A companion article, "Build RESTful web services using Spring 3," introduced the "Spring way" to build
RESTful web services. It also explained how to use
ContentNegotiatingViewResolver to produce multiple
representations, which is an important feature for RESTful web services.
This article explains another way to produce multiple representations
using HttpMessageConverter, and examples in the article show
how to use RestTemplate with
HttpMessageConverter to communicate with services.

REST support in Spring MVC

This section provides an overview of the major Spring features, or
annotations, that support RESTful web services.

@Controller

Use the @Controller annotation to annotate the class that
will be the controller in MVC and handle the HTTP
request.

@RequestMapping

Use the @RequestMapping annotation to annotate the
function that should handle certain HTTP methods, URIs, or HTTP
headers. This annotation is the key to the Spring REST support. You
change the method parameter to handle other HTTP methods.

Refer
to the Spring documentation for a complete list of the supported
annotations or objects that can be injected into the
method.

Multiple representation support

Representing the same resource with different MIME types is an important
aspect of RESTful web services. Generally, you would use the same URI with
a different "accept" HTTP header to fetch the resource with different
representation. You can also use a different URI, or a URI with different
request parameters.

"Build RESTful web services using Spring 3" introduced
ContentNegotiatingViewResolver, which can pick a different
view resolver to handle the same URI (with the difference of the accept
header). Thus, ContentNegotiatingViewResolver can be used to
produce multiple representations.

There's also another way to produce multiple representations—by
combining the HttpMessageConverter and
c@ResponseBody annotation. With this method you don't need to
use the View technologies.

HttpMessageConverter

HTTP requests and responses are text based, meaning a browser and server
communicate by exchanging raw texts. With Spring, however, methods in the
controller class return pure 'String' type and domain models (or other
Java built-in objects). How can Spring serialize/de-serialize the objects
to raw texts? This is handled by HttpMessageConverter. Spring
has bundled implementations that can meet your common needs. Table 1 shows
some examples.

Table 1. HttpMessageConverter examples

With...

You can...

StringHttpMessageConverter

Read/write a string from
request and response. By default, it supports the media type
text/* and writes with a Content-Type of text/plain.

FormHttpMessageConverter

Read/write form data from
request and response. By default, it reads the media type
application/x-www-form-urlencoded and writes data into
MultiValueMap<String,String>.

Build RESTful web services

In this section, learn to build a simple RESTful web service that can
produce multiple representations. Some of the resources used in the sample
application were built in "Build RESTful web services using Spring 3." You can also download the sample code.

First, you must configure the HttpMessageConverter. To produce
multiple representations, customize several
HttpMessageConverter instances to convert the object to
different media types. This section covers the JSON, ATOM, and XML media
types.

JSON

Let's start with the simplest example. JSON is a lightweight
data-interchange format that's easy for humans to read and write. Listing
1 shows the code that configures a JSON converter.

In the configuration, three converters are registered.
MappingJacksonHttpMessageConverter is used to convert the
object to JSON and vice versa. This built-in converter uses Jackson's
ObjectMapper to map JSON to the JavaBean, so you must add the
following Jackson JAR files to the classpath.

org.codehaus.jackson.jar

org.codehaus.jackson.mapper.jar

The next step is to write a method to handle the request that asks for JSON
representation. Listing 2 shows the details.

XML

Spring's built-in converter MarshallingHttpMessageConverter is
used to map between an object and XML (OXM). The example uses JAXB 2 as
the marshaller/un-marshaller for the converter. Listing 4 shows the
configuration.

It's important to understand that JAXB 2 does not have good support for
mapping the java.util.List<T> to XML. Common practice is to add a
wrapper class for the collection of objects. Refer to "Build RESTful web
services using Spring 3" or download the source code for details of this JAXB
annotated class.

What about the method in the controller that handles the request? Take a
look back at the code in Listing 2. It's not
surprising to find that you don't need to add any code here. You just need
to add another supported media type in the Accept header, as
follows.

headers=”Accept=application/json, application/xml”

The converter will map the object properly to the type you request (JSON or
XML). Listing 5 shows the desired result when you request the
application/xml representation.

ATOM feed

An ATOM feed is another popular format for exchanging data in RESTful web
services. An Atom feed document is a representation of an Atom feed,
including metadata about the feed, and some or all of the entries
associated with it. Its root is the atom:feed element. There
is also an ATOM Publish Protocol (APP) to define the exchange format and
behaviors. (Defining the ATOM and APP formats is outside the scope of this
article.

The example uses AtomFeedHttpMessageConverter to convert the
ATOM feed, which leverages the ROME ATOM API. Therefore, you must include
the JAR file sun.syndication.jar in your classpath. Listing 6 shows the
configuration of this converter.

The @RequestBody annotation is used in the
addEmp() and updateEmp() methods. It takes the
HTTP request body and tries to convert it to the object class using the
registered HttpMessageConverter. In the next section, you'll
use RestTemplate to communicate with these services.

Use RestTemplate to communicate with REST services

"Build RESTful web services using Spring 3" introduced how to use CURL and the REST client to test
REST services. At the programming level, Jakarta Commons' HttpClient is
typically used to do so (but that's outside the scope of this article).
You can also use a Spring REST client called RestTemplate. It
is conceptually similar to other template classes in Spring, such as
JdbcTemplate and JmsTemplate.

RestTemplate also uses the HttpMessageConverter.
You could pass the object class in the requests and let the converters
handle the mappings.

Configuring the RestTemplate

Listing 10 shows the configuration of RestTemplate. It also
uses the three converters introduced previously.

Code samples

The following code samples help illustrate how to use
RestTemplate. Refer to the RestTemplate API for a detailed explanation of the
APIs used.

Listing 11 shows how to add headers to the request and then to invoke the
request. Using the MarshallingHttpMessageConverter you could
get the response and convert it to the typed class. You can use different
media types to test other representations.

Listing 14. DELETE an existing
employee

Summary

In this article, you learned about the HttpMessageConverter
that was introduced in Spring 3. It provides both client and server-side
support for multiple representations. Using the source
code provided, you can explore the differences between the
implementation of HttpMessageConverter in this article and
the implementation using ContentNegotiatingViewResolver in
"Build RESTful web services using Spring 3."