RESTful MVC Features in Spring 3.0 and 3.1

Below is a feature summary you must know to use Spring’s MVC RESTful Web Services. This article will show the features available, but not discuss pros & cons, use-cases or sell you on the benefits of REST.



PUT & POST in Browser Based Clients

Browsers do not allow PUT & DELETE – In web.xml configure HiddenHttpMethodFilter & on the page add the following inside your form <input type="hidden" name="_method" value="PUT"/>, with form submit set to POST. If using the Spring <form:form> tag, the hidden field is created for you, use any of the standard 7 HTTP verbs as desired.



Receiving Values in the URL Path, the RESTful Way

@PathVariable in Controller methods to extract values from the path.



You Rarely Need to Write Custom Parsers

<mvc:annotation-driven/> – automatically registers several marshallers simply with presence of corresponding jar in classpath

Type group:artifact:current-version
JAXB2 com.sun.xml.bind:jaxb-impl:2.2.4
JAXP javax.xml:jaxp-api:1.4.2
Atom/RSS rome:rome:1.0
JSON org.codehaus.jackson:jackson-mapper-asl:1.8.3



Configure – Don’t Code

Automatic Marshalling & Unmarshalling of XML, JSON, ATOM/RSS data
Controller annotations: @RequestBody & @ResponseBody
Example of JAXB2 Configuration in my OXM blog post named http://gordondickens.com/wordpress/2011/02/07/sending-beans-as-xml-with-jmstemplate/



Sending HTTP Response Codes to Clients

Success response status with @ResponseStatus controller method annotation.
Exception handling with @ExceptionHandler annotation on controller methods OR custom classes, also with annotated @ResponseStatus.
Note: @ResponseStatus disables the default behavior of void controller methods automatically returning the view.



Content Negotiation

Accept Header in Browser Based Clients

The HTML Accept header is not a reliable option for browser based clients to request content type. See Content Negotiation below.

Managing Client Content Type Requests

The HTTP Accept header is the typical REST vehicle for receiving the client’s requested MIME content type (application/JSON, application/XML, etc.)

Content Negotiation – Flexible Config Options

Spring’s ContentNegotiatingViewResolver for configuring client request data format. Several methods beyond the standard “Accept” header which will not work if you have browser based clients (Accept header, url extension, parameter, Java Activation Framework). URL extension (referred to as file extension) allows a URL to be appended with a string which can be mapped to a MIME type.

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="mediaTypes">
    <map>
      <entry key="json" value="application/json" />
      <entry key="xml" value="application/xml" />
      <entry key="htm" value="text/html" />
    </map>
  </property>
  <property name="defaultContentType" value="text/html" />
</bean>

The same shortcut keys can be used in a parameter where URL can have “?format=json”. For JAF, the jar contains a /lib/mime.types file with mapped types already defined.

Type group:artifact:current-version
Java Activation javax.activation:activation:1.1.1
Java Mail javax.mail:mail:1.4.1



Client Side with RestTemplate

Spring’s RestTemplate is for client side development. In the Spring Template style, simply, set the URL, invoke the method & process the results. The main extension points in Spring Templates are done through Callbacks.

HTTP Method RestTemplate Method
DELETE delete(java.lang.String, java.lang.Object...)
GET getForObject(java.lang.String, java.lang.Class, java.lang.Object...), getForEntity(java.lang.String, java.lang.Class, java.lang.Object...)
HEAD headForHeaders(String url, String... urlVariables)
OPTIONS optionsForAllow(String url, String... urlVariables)
POST postForLocation(String url, Object request, String... urlVariables)

RestTemplate Callbacks

Callback Description Interface
RequestCallback Called when execute method is invoked public interface RequestCallback { void doWithRequest(ClientHttpRequest request) throws IOException;
}
AcceptHeaderRequestCallback Processing the Accept headers public void doWithRequest(ClientHttpRequest request)
HttpEntityRequestCallback Writes provided object to output stream public void doWithRequest(ClientHttpRequest httpRequest)



REST Improvements in Spring 3.1

Customizable @MVC

  • Custom @ExceptionHandler support for @Controller methods
  • Custom @ExceptionHandler support for @RequestBody & @ResponseBody
  • You can write a BeanPostProcessor to change AnnotationMethodHandlerAdapter after construction
  • Auto-detection of custom HttpMessageConverters – for example custom MyMappingJacksonHttpMessageConverter
  • Support for custom message codes resolver with <mvc:annotation-driven/>
<mvc:annotation-driven>
    <mvc:custom-web-argument-resolvers>
        <bean class="org.example.MyWebArgumentResolver"/>
    </mvc:custom-web-argument-resolvers>
</mvc:annotation-driven>
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>
<mvc:annotation-driven message-codes-resolver="org.example.MyMessageCodesResolver"/>

REST Enhancements

  • Interceptors for RestTemplate
  • ClientHttpRequestInterceptor – ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
  • bufferRequestBody property to the SimpleClientHttpRequestFactory to handle large payloads with RestTemplate
  • New WebRequest.checkNotModified(String) // only had long support previously
  • New @ResponseEntity
  • To support OAuth with ClientHttpRequestInterceptors



Other REST Concepts



HATEOAS

Hypermedia as the Engine of Application State

WADL

Web Application Description Language



Summary

Spring MVC REST helps us with:

  • The power of <mvc:annotation-driven/> provides us the automatic marshalling/unmarshalling of content in REST
  • The configuration flexibility of ContentNegotiatingViewResolver for our browser based clients

About Gordon

Technology enthusiast primarily focused on Java and Open Source projects. Spring Certified Professional and Trainer. http://twitter.com/gdickens http://linkedin.com/in/gordondickens http://github.com/gordonad
This entry was posted in REST, Spring, Spring MVC, Web Services and tagged , , , . Bookmark the permalink.

One Response to RESTful MVC Features in Spring 3.0 and 3.1

  1. Gabriel says:

    Hi Gordon,

    is there a sample app on github where we could explore in more detail these features ?

    Tx,
    Gabriel.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>