diff --git a/spring-framework-reference/src/beans.xml b/spring-framework-reference/src/beans.xml
index ff489acd72b..c30b2fc358d 100644
--- a/spring-framework-reference/src/beans.xml
+++ b/spring-framework-reference/src/beans.xml
@@ -6411,6 +6411,57 @@ public class CachingMovieCatalog implements MovieCatalog {
per-class.
+
+ Defining FactoryBeans with annotations
+
+ FactoryBeans can be defined in code using the
+ @FactoryMethod method level annotation. Factory bean
+ definiton supports using standard as well as custom qualifiers using
+ annotations. The scope of the object produces and if it should be a scoped
+ AOP proxy are determined by the presence of @Scope
+ and @ScopedProxy annotations. The default scope for
+ methods with @FactoryMethod can also be inherited
+ from the class level. The following example shows a variety of usages of the
+ @FactoryMethod annotation.
+
+ @Component
+public class FactoryMethodComponent {
+
+ private static TestBean staticTestBean = new TestBean("staticInstance",1);
+
+ @Autowired @Qualifier("public")
+ public TestBean autowiredTestBean;
+
+ private static int i;
+
+ @FactoryMethod @Qualifier("static")
+ public static TestBean staticInstance()
+ {
+ return staticTestBean;
+ }
+
+ @FactoryMethod @Qualifier("public")
+ public TestBean getPublicInstance() {
+ return new TestBean("publicInstance");
+ }
+
+ @FactoryMethod @BeanAge(1)
+ protected TestBean getProtectedInstance() {
+ return new TestBean("protectedInstance", 1);
+ }
+
+ @FactoryMethod @Scope("prototype")
+ private TestBean getPrivateInstance() {
+ return new TestBean("privateInstance", i++);
+ }
+
+ @FactoryMethod @Scope("request") @ScopedProxy
+ private TestBean getPrivateInstance() {
+ return new TestBean("privateInstance", i++);
+ }
+}
+
+
diff --git a/spring-framework-reference/src/new-in-3.xml b/spring-framework-reference/src/new-in-3.xml
index 0835c6b62d8..9ebb20528aa 100644
--- a/spring-framework-reference/src/new-in-3.xml
+++ b/spring-framework-reference/src/new-in-3.xml
@@ -171,7 +171,7 @@
- IoC enhancements/Spring JavaConfig
+ IoC enhancements/Java based bean metadata
@@ -191,65 +191,72 @@
-
- Core APIs updated for Java 5
+
+ Core APIs updated for Java 5
- BeanFactoryinterface returns typed bean
- instancesas far as possible
-
- T getBean(Stringname, Class<T> requiredType)
- Map<String, T> getBeansOfType(Class<T> type)
-
-
-
- Spring's TaskExecutorinterface extends
- java.util.concurrent.Executor now
-
- extended AsyncTaskExecutor supports standard Callables with Futures
-
-
-
- New Java 5 based converter API and SPI
-
- stateless ConversionService and Converters
- superseding standard JDK PropertyEditors
-
-
-
- Typed ApplicationListener<E>
-
-
-
+ BeanFactoryinterface returns typed bean instancesas far as
+ possible
+
+ T getBean(Stringname, Class<T> requiredType)
+
-
- Spring Expression Language
+
+ Map<String, T> getBeansOfType(Class<T>
+ type)
+
+
- Spring introduces an expression language which is similar to Unified
- EL in its syntax but offers significantly more features. The expression
- language can be used when defining XML and Annotation based bean
- definitions and also serves as the foundation for expression language
- support across the Spring portfolio. Details of this new functionality can
- be found in the chapter Spring Expression
- Language (SpEL).
+ Spring's TaskExecutorinterface extends
+ java.util.concurrent.Executor now
+
+ extended AsyncTaskExecutor supports standard Callables with
+ Futures
+
+
- The Spring Expression Language was created to provide the Spring community with a single well
- supported expression language that can used across all the products in the Spring portfolio. Its language
- features are driven by the requirements of the projects in the Spring portfolio, including tooling
- requirements for code completion support within the eclipse based SpringSource Tool Suite.
-
- The following is an example of how the Expression Language can be used to configure some properties
- of a database setup
-
-
-
-
-]]>
-
- This functionality is also available if you prefer to configure your components using
- annotations:
- New Java 5 based converter API and SPI
+
+ stateless ConversionService and Converters
+
+
+
+ superseding standard JDK PropertyEditors
+
+
+
+ Typed ApplicationListener<E>
+
+
+
+ Spring Expression Language
+
+ Spring introduces an expression language which is similar to
+ Unified EL in its syntax but offers significantly more features. The
+ expression language can be used when defining XML and Annotation based
+ bean definitions and also serves as the foundation for expression
+ language support across the Spring portfolio. Details of this new
+ functionality can be found in the chapter Spring Expression Language (SpEL).
+
+ The Spring Expression Language was created to provide the Spring
+ community with a single well supported expression language that can used
+ across all the products in the Spring portfolio. Its language features
+ are driven by the requirements of the projects in the Spring portfolio,
+ including tooling requirements for code completion support within the
+ eclipse based SpringSource Tool Suite.
+
+ The following is an example of how the Expression Language can be
+ used to configure some properties of a database setup <bean class="mycompany.RewardsTestDatabase">
+ <property name="databaseName"
+ value="#{systemProperties.databaseName}"/>
+ <property name="keyGenerator"
+ value="#{strategyBean.databaseKeyGenerator}"/>
+</bean>
+
+
+ This functionality is also available if you prefer to configure
+ your components using annotations: @Repository
public class RewardsTestDatabase {
@Value("#{systemProperties.databaseName}")
@@ -258,29 +265,47 @@ public class RewardsTestDatabase {
@Value("#{strategyBean.databaseKeyGenerator}")
public voidsetKeyGenerator(KeyGenerator kg) { … }
}
-]]>
-
-
+
+
-
- The Inversion of Control (IoC) container
+
+ The Inversion of Control (IoC) container
- Some core JavaConfig features have been added to the Spring Framework now. This means that the following
- annotations are now directly supported:
-
-
- @Configuration
- @Bean
- @Primary
- @Lazy
- @Import
- @Value
-
-
+
+ Java based bean metadata
-
- Here is an example of a Java class providing basic configuration using the new JavaConfig features:
- Some core features from the JavaConfig project have been added to the
+ Spring Framework now. This means that the following annotations are
+ now directly supported:
+
+ @Configuration
+
+
+
+ @Bean
+
+
+
+ @Primary
+
+
+
+ @Lazy
+
+
+
+ @Import
+
+
+
+ @Value
+
+
+
+ Here is an example of a Java class providing basic configuration
+ using the new JavaConfig features: @Configuration
public class AppConfig{
@Value("#{jdbcProperties.url}") String jdbcUrl;
@Value("#{jdbcProperties.username}") String username;
@@ -310,47 +335,83 @@ public class AppConfig{
username, password);
}
}
-]]>
+ To get this to work you need to add the following component
+ scanning entry in your minimal application context XML file.
+ <context:component-scan
+ base-package="com.myco.config"/>
+
- To get this to work you need to add the following component scanning entry in your minimal
- application context XML file.
-
- ]]>
-
-
+
+ Factory Bean definitions using annotations
-
-
-
- The Web Tier
-
- Work in progress ...
-
-
- Comprehensive REST support
-
- Work in progress ...
+ FactoryBeans can be defined within a Spring component definition
+ and registered using standard component-scanning techniques. See Factory Bean Definitions
+ using annotations for more information
+
-
- @MVC additions
+
+ The Web TierWork in progress ...
+
+
+ Comprehensive REST support
+
+ Server-side support for building RESTful applications has been
+ provided as an extension of the existing annotation driven MVC web
+ framework. Client-side support is provided by the
+ RestTemplate class in the spirit of other
+ template classes such as JdbcTemplate and
+ JmsTemplate. Both server and client side REST
+ functionality make use of
+ HttpConverters to facilitate the
+ conversion between objects and their representation in HTTP request
+ and replies.
+
+ The MarhsallingHttpMessageConverter uses
+ the Object to XML mapping functionality in the
+ org.springframework.oxm package. This functionality
+ had previously been part of Spring Web Services. More information on
+ the use of the org.springframework.oxm can be found
+ in that projects reference
+ documentation.
+
+ Refer to the section on REST support
+ for more information.
+
+
+
+ @MVC additions
+
+ Additional annotations such as
+ @CookieValue and
+ @RequestHeaders have been added. See Mapping cookie values with the
+ @CookieValue annotation and Mapping request header attributes with
+ the @RequestHeader annotation for more information.
+
+ Work in progress ...
+
+
+
+
+ Declarative model validation
+
+ Hibernate Validator, JSR 303
+
+ Work in progress...
+
+
+
+ Early support for Java EE 6
+
+ JSF 2.0, JPA 2.0, etc
+
+ Work in progress...
-
-
- Declarative model validation
-
- Hibernate Validator, JSR 303
-
-
-
- Early support for Java EE 6
-
- JSF 2.0, JPA 2.0, etc
-
-
-
\ No newline at end of file
diff --git a/spring-framework-reference/src/rest.xml b/spring-framework-reference/src/rest.xml
index 956ec7c92ab..d2b88dabd68 100644
--- a/spring-framework-reference/src/rest.xml
+++ b/spring-framework-reference/src/rest.xml
@@ -6,29 +6,34 @@
IntroductionThe goal of Spring's REST support is to make the development of
- 'RESTful' Web services and applications easier. Client-side access to
- RESTful resources is greatly simplified using Spring
- RestTemplate. RestTemplate
- follows in the footsteps of other 'Template' classes in Spring such as
- JdbcTemplate and
+ RESTful Web services and applications easier.
+
+ Client-side access to RESTful resources is greatly simplified using
+ Spring RestTemplate.
+ RestTemplate follows in the footsteps of other
+ template classes in Spring such as JdbcTemplate and
JmsTemplate. Instead of dealing with a verbose
- lower level API such as Apache Commons HttpClient to create RESTful
- request, RestTemplate provides one liner methods that are purpose built
- for RESTful programming. On the server-side, Spring's REST support is
- based upon Spring's existing annotation based MVC framework. (For those
- interested in the rational for that decision, and say not implenting
- JAX-RS, read Arjen Putsma's SpringSource TeamBlog HttpClient
+ to create RESTful request, RestTemplate provides one liner methods that
+ are purpose built for RESTful programming.
+
+ On the server-side, Spring's REST support is based upon Spring's
+ existing annotation based MVC framework. (For those interested in the
+ rational for that decision, and for not implementing JAX-RS, read Arjen
+ Poutsma's SpringSource TeamBlog entry.)
With little effort, you can marshall data out of a RESTful request using
- @RequestMapping and @PathVariable annotations and return different views
- as determined by the request's Context-Type header.
+ @RequestMapping and
+ @PathVariable annotations and return different
+ views as determined by the request's Context-Type
+ header.
In this chapter we describe all the features of Spring's REST
support. It is divided into two main two chapters, one for the server-side
and one for the client-side. For those new to Spring's MVC framework, you may want to read through the
reference documentation on annotation-based
- controller configuration to undestand the general programming
+ controller configuration to understand the general programming
model.
@@ -41,13 +46,13 @@
linkend="mvc-servlet">DispatcherServlet.
- URI templates
+ URI Templates
- RESTful services use URIs to name resourses. To faciliate
+ RESTful services use URIs to name resources. To facilitate
accessing the information contained in a URI, its structure follows
conventions so that it can easily be described in a parameterized form.
The proposed
- RFC for URI Templates defines how a URI is parameterized. For
+ RFC for URI Templates defines how an URI is parameterized. For
example, the URI Templatehttp://www.example.com/users/{userid}
@@ -57,11 +62,11 @@
http://www.example.com/users/fred
- When processing an request the URI can be compared to an expected
+ When processing a request the URI can be compared to an expected
URI Template in order to extract a collection of variables.
- Spring uses the @RequestMapping annotation
- to define the URI Template for the request.
+ Spring uses the @RequestMapping method
+ annotation to define the URI Template for the request.
The@PathVariable annotation is used to extract
the value of the template variables and assign their value to a method
variable. A Spring controller method to process above example is shown
@@ -78,9 +83,9 @@ public String getUser(@PathVariable String userId) {
Mapping RESTful URLs with the @PathVariable annotation
- The @PathVariable method level annotation
- is used to indicate that a method parameter should be bound to the
- value of a URI template variable.
+ The @PathVariable method parameter
+ annotation is used to indicate that a method parameter should be bound
+ to the value of a URI template variable.The following code snippet shows the use of a single
@PathVariable in a controller method:
@@ -95,9 +100,9 @@ public String findOwner(@PathVariable String ow
The URI Template "/owners/{ownerId}"
specifies the variable name ownerId. When the controller handles this
- request, the value of ownerId is set the the value in the request URI.
- For example, when a request comes in for /owners/fred, the value
- 'fred' is bound to the method parameter String
+ request, the value of ownerId is set the value in the request URI. For
+ example, when a request comes in for /owners/fred, the value 'fred' is
+ bound to the method parameter String
ownerId.The matching of method parameter names to URI Template variable
@@ -113,8 +118,8 @@ public String findOwner(@PathVariable("ownerId"
The name of the method parameter does not matter in this case,
- so you may also use create a controlled method with the signature
- shown below
+ so you may also use a controller method with the signature shown
+ below@RequestMapping("/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
@@ -157,6 +162,93 @@ public class RelativePathUriTemplateController {
not correct.
+
+
+ Mapping the request body with the @RequestBody
+ annotation
+
+ The @RequestBody method parameter
+ annotation is used to indicate that a method parameter should be bound
+ to the value of the HTTP request body. For example,
+
+ @RequestMapping(value = "/something", method = RequestMethod.PUT)
+public void handle(@RequestBody String body, Writer writer) throws IOException {
+ writer.write(body);
+}
+
+ The conversion of the request body to the method argument is
+ done using a HttpMessageConverter.
+ HttpMessageConverter is responsible for
+ converting for converting from the HTTP request message to an object
+ and converting from an object to the HTTP response body.
+ DispatcherServlet supports annotation based
+ processing using the
+ DefaultAnnotationHandlerMapping and
+ AnnotationMethodHandlerAdapter. In Spring 3 the
+ AnnotationMethodHandlerAdapter has been
+ extended to support the @RequestBody and has
+ several HttpMessageConverters
+ registered by default, these are
+
+
+
+ ByteArrayHttpMessageConverter -
+ converts byte arrays
+
+
+
+ StringHttpMessageConverter - converts
+ strings
+
+
+
+ FormHttpMessageConverter - converts
+ form data to/from a MultiValueMap<String, String>
+
+
+
+ SourceHttpMessageConverter - convert
+ to/from a javax.xml.transform.Source;
+
+
+
+ MarshallingHttpMessageConverter -
+ convert to/from an object using the
+ org.springframework.oxm package.
+
+
+
+ More information on these converters can be found in the section
+ Message Converters.
+
+
+ The MarshallingHttpMessageConverter
+ requires a Marshaller and
+ Unmarshaller from the
+ org.springframework.oxm package to be
+ configured on an instance of
+ AnnotationMethodHandlerAdapter in the
+ application context. For example
+
+ <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
+ <property name="messageConverters">
+ <util:list id="beanList">
+ <ref bean="stringHttpMessageConverter"/>
+ <ref bean="marshallingHttpMessageConverter"/>
+ </util:list>
+ </property
+</bean>
+
+<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>
+
+<bean id="marshallingHttpMessageConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
+ <property name="marshaller" ref="castorMarshaller" />
+ <property name="unmarshaller" ref="castorMarshaller" />
+</bean>
+
+<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller"/>
+
+
@@ -205,7 +297,7 @@ public class RelativePathUriTemplateController {
view based on the file extension or Accept header of
the HTTP request. ContentNegotiatingViewResolver
does not perform the view resolution itself, but instead delegates to a
- list of view resolvers set using the property
+ list of view resolvers set using the bean property
ViewResolvers.
The ContentNegotiatingViewResolver selects
@@ -221,7 +313,7 @@ public class RelativePathUriTemplateController {
Context-Type was 'text/xml' is a compatible match.To support the resolution of a view based on a file extension,
- ContentNegotiatingViewResolver's property
+ ContentNegotiatingViewResolver's bean property
MediaTypes is used to specify a mapping of file
extensions to media types. For more information on the algorithm to
determine the request media type, refer to the API documentation for
@@ -309,7 +401,7 @@ public class ContentController {
Views
- Several views were added to Spring 3 to help support creating
+ Several views were added in Spring 3 to help support creating
RESTful services. They are:
@@ -325,29 +417,34 @@ public class ContentController {
MarshallingView - returns an XML
- representation using Spring's Objecct/XML mapping (OXM)
+ representation using Spring's Object to XML mapping (OXM)
functionality
- Available separately is the JacksonJsonView
- included as part of the Spring JavaScript project.
+
+ Available separately is the
+ JacksonJsonView included as part of the Spring
+ JavaScript project.
+ Feed ViewsBoth AbstractAtomFeedView and
AbstractRssFeedView inherit from the base class
- AbstractFeedView<T> and are used to
- provide Atom and RSS Feed views respectfully. They are based on
- java.net's ROME project
- and located in the package org.springframework.web.servlet.view.feed.
- The AbstractAtomFeedView requires you to
+ AbstractFeedView and are used to provide Atom
+ and RSS Feed views respectfully. They are based on java.net's ROME project and are located
+ in the package
+ org.springframework.web.servlet.view.feed.
+
+ AbstractAtomFeedView requires you to
implement the buildFeedEntries method and
optionally override the buildFeedMetadata
method (the default implementation is empty), as shown below
- public class SampleContentAtomView extends AbstractAtomFeedView {
+ public class SampleContentAtomView extends AbstractAtomFeedView {
@Override
protected void buildFeedMetadata(Map<String, Object> model, Feed feed, HttpServletRequest request) {
@@ -365,7 +462,7 @@ public class ContentController {
Similar requirements apply for implementing
AbstractRssFeedView, as shown below
- public class SampleContentAtomView extends AbstractRssFeedView {
+ public class SampleContentAtomView extends AbstractRssFeedView {
@Override
protected void buildFeedMetadata(Map<String, Object> model, Channel feed, HttpServletRequest request) {
@@ -387,15 +484,22 @@ public class ContentController {
automatically be written to the response object after the method
returns.
- For an example implementation of creating a Atom view please
- refer to Alef Arendsen's SpringSource TeamBlog For an example of creating a Atom view please refer to Alef
+ Arendsen's SpringSource TeamBlog entry.XML Marshalling View
- The MarhsallingView
+ The MarhsallingView uses a XML
+ Marshaller defined in the
+ org.springframework.oxm package to render the
+ response content as XML. The object to be marshalled can be set
+ explicitly using MarhsallingView's
+ modelKey bean property. Alternatively, the view
+ will iterate over all model properties marhsall only those types that
+ are supported by the Marshaller.
@@ -471,7 +575,7 @@ public String deletePet(@PathVariable int ownerId, @PathVariable int petId) {
renders the view again, and compares the two hashes. If they are equal,
a 304 is returned. It is important to note that this
filter will not save processing power, as the view is still rendered.
- The only thing it saves is bandwith, as the rendered response is not
+ The only thing it saves is bandwidth, as the rendered response is not
sent back over the wire.
Deep ETags are a bit more complicated. In this case, the ETag is
@@ -486,62 +590,354 @@ public String deletePet(@PathVariable int ownerId, @PathVariable int petId) {
Exception Handling
- @ExceptionHandler
+ The @ExceptionHandling method annotation is
+ used within a controller to specify which method will be invoked when an
+ exception of a specific type is thrown during the execution of
+ controller methods. For example
+
+ @Controller
+public class SimpleController {
+
+ // other controller method omitted
+
+ @ExceptionHandler(IOException.class)
+ public String handleIOException(IOException ex, HttpServletRequest request) {
+ return ClassUtils.getShortName(ex.getClass());
+ }
+}
+
+ will invoke the 'handlerIOException' method when a
+ java.io.IOException is thrown.
+
+ The @ExceptionHandler value can be set to
+ an array of Exception types. If an exception is thrown matches one of
+ the types in the list, then the method annotated with the matching
+ @ExceptionHandler will be invoked. If the
+ annotation value is not set then the exception types listed as method
+ arguments are used.
+
+ Much like standard controller methods annotated with a
+ @RequestMapping annotation, the method arguments
+ and return values of @ExceptionHandler methods
+ are very flexible. For example, the
+ HttpServletRequest can be access in Servlet
+ environments and the PortletRequest in Portlet
+ environments. The return type can be a String,
+ which is interpreted as a view name or a
+ ModelAndView object. Please refer to the API
+ documentation for more details. Accessing RESTful services on the Client
- Spring provides a client-side API blah blah
+ The RestTemplate is the core class for
+ client-side access to RESTful services. It is conceptually similar to
+ other template classes in Spring, such as
+ JdbcTemplate and JmsTemplate
+ and other template classes found in other Spring portfolio projects.
+ RestTemplate's behavior is customized by providing
+ callback methods and configuring the
+ HttpMessageConverter used to marshal
+ objects into the HTTP request body and to unmarshall any response back
+ into an object. As it is common to use XML as a message format, Spring
+ provides a MarshallingHttpMessageConverter that
+ uses the Object-to-XML framework that is part of the
+ org.springframework.oxm package. This gives you a
+ wide range of choices of XML to Object mapping technologies to choose
+ from.
+
+ This section describes how to use the
+ RestTemplate and its associated
+ HttpMessageConverters.RestTemplate
- blah blah
+ Invoking RESTful services in Java is typically done using a helper
+ class such as Jakarta Commons HttpClient. For
+ common REST operations this approach is too low level as shown
+ below.
+
+ String uri = "http://example.com/hotels/1/bookings";
+
+PostMethod post = new PostMethod(uri);
+String request = // create booking request content
+post.setRequestEntity(new StringRequestEntity(request));
+
+httpClient.executeMethod(post);
+
+if (HttpStatus.SC_CREATED == post.getStatusCode()) {
+ Header location = post.getRequestHeader("Location");
+ if (location != null) {
+ System.out.println("Created new booking at :" + location.getValue());
+ }
+}
+
+ RestTemplate provides higher level methods that correspond to
+ each of the six main HTTP methods that make invoking many RESTful
+ services a one-liner and enforce REST best practices.
+
+
+
+ The names of RestTemplate methods follow a
+ naming convention, the first part indicates what HTTP method is being
+ invoked and the second part indicates what is returned. For example, the
+ method getForObject will perform a GET, convert
+ the HTTP response into an object type of your choice, and returns that
+ object. The method postForLocation will do a
+ POST, converting the given object into a HTTP request, and returns the
+ response HTTP Location header where the newly created object can be
+ found In case of an exception processing the HTTP request, an exception
+ of the type RestClientException will be
+ thrown.
+
+ Objects passed to and returned from these methods are converted to
+ and from HTTP messages by
+ HttpMessageConverter instances.
+ Converters for the main mime types are registered by default, but you
+ can also write your own converter and register it via the
+ messageConverters bean property. The default
+ converter instances registered with the template are
+ ByteArrayHttpMessageConverter,
+ StringHttpMessageConverter,
+ FormHttpMessageConverter and
+ SourceHttpMessageConverter. You can override
+ these defaults using the messageConverters bean
+ property as would be required if using the
+ MarshallingHttpMessageConverter.
+
+ Each method takes URI template arguments in two forms, either as a
+ String variable length argument or a
+ Map<String,String>. For example,
+
+ String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}",
+ String.class,"42", "21");
+
+
+ using variable length arguments and
+
+ Map<String, String> vars = Collections.singletonMap("hotel", 42);
+String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{hotel}", String.class, vars);
+
+
+ using a Map<String,String>.
+
+ To create an instance of RestTemplate you
+ can simply call the default constructor. This will use standard Java
+ classes from the java.net package as the underlying
+ implementation to create HTTP requests. This can be overridden by
+ specifying an implementation of
+ ClientHttpRequestFactory. Spring provides
+ the implementation
+ CommonsClientHttpRequestFactory that uses the
+ Jakarta Commons HttpClient to create requests.
+ CommonsClientHttpRequestFactory is configured
+ using an instance of
+ org.apache.commons.httpclient.HttpClient which
+ can in turn be configured with credentials information or connection
+ pooling functionality.
+
+ The previous example using Jakarta Commons
+ HttpClient directly rewritten to use the
+ RestTemplate is shown below
+
+ uri = "http://example.com/hotels/{id}/bookings";
+
+RestTemplate template = new RestTemplate();
+
+Booking booking = // create booking object
+
+URI location = template.postForLocation(uri, booking, String.class, "1");
+
+
+ The general callback interface is
+ RequestCallback and is called when the
+ execute method is invoked.
+
+ public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
+ ResponseExtractor<T> responseExtractor,
+ String... urlVariables)
+
+
+// also has an overload with urlVariables as a Map<String, String>.
+
+ The RequestCallback interface is
+ defined as
+
+ public interface RequestCallback {
+ void doWithRequest(ClientHttpRequest request) throws IOException;
+}
+
+ and allows you to manipulate the request headers and write to the
+ request body. When using the execute method you do not have to worry
+ about any resource management, the template will always close the
+ request and handle any errors. Refer to the API documentation for more
+ information on using the execute method and the meaning of its other
+ method arguments.HTTP Message Conversion
- blah blah
+ Objects passed to and returned from the methods getForObject(),
+ postForLocation(), and put() and are converted to HTTP requests and from
+ HTTP responses by HttpMessageConverters.
+ The HttpMessageConverter interface is
+ show below to give you a better feel for its functionality
+
+ public interface HttpMessageConverter<T> {
+
+ // Indicate whether the given class is supported by this converter.
+ boolean supports(Class<? extends T> clazz);
+
+ // Return the list of MediaType objects supported by this converter.
+ List<MediaType> getSupportedMediaTypes();
+
+ // Read an object of the given type form the given input message, and returns it.
+ T read(Class<T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException;
+
+ // Write an given object to the given output message.
+ void write(T t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;
+
+}
+
+ Concrete implementations for the main media (mime) types are
+ provided in the framework and are registered by default with the
+ RestTemplate on the client-side and with
+ AnnotationMethodHandlerAdapter on the
+ server-side.
+
+ The implementations of
+ HttpMessageConverters are described in the
+ following sections. For all converters a default media type is used but
+ can be overridden by setting the
+ supportedMediaTypes bean propertyStringHttpMessageConverter
-
-
-
+ A HttpMessageConverter
+ implementation that can read and write Strings from the HTTP request
+ and response. By default, this converter supports all text media types
+ (text/*), and writes with a
+ Content-Type of
+ text/plain.FormHttpMessageConverter
-
-
-
+ A HttpMessageConverter
+ implementation that can read and write form data from the HTTP request
+ and response. By default, this converter reads and writes the media
+ type (application/x-www-form-urlencoded). Form data
+ is read from and written into a MultiValueMap<String,
+ String>. ByteArrayMessageConverter
-
-
-
+ A HttpMessageConverter
+ implementation that can read and write byte arrays from the HTTP
+ request and response. By default, this converter supports all media
+ types (*/*), and writes with a
+ Content-Type of
+ application/octet-stream. This can be overridden by
+ setting the supportedMediaTypes property, and
+ overriding getContentType(byte[]). MarshallingHttpMessageConverter
-
-
-
+ A HttpMessageConverter
+ implementation that can read and write XML using Spring's
+ Marshaller and
+ Unmarshaller abstractions from the
+ org.springframework.oxm package. This converter
+ requires a Marshaller and
+ Unmarshaller before it can be used.
+ These can be injected via constructor or bean properties. By default
+ this converter supports (text/xml) and
+ (application/xml).SourceHttpMessageConverter
-
+ A HttpMessageConverter
+ implementation that can read and write
+ javax.xml.transform.Source from the HTTP
+ request and response. Only DOMSource,
+ SAXSource, and
+ StreamSource are supported. By default, this
+ converter supports (text/xml) and
+ (application/xml).