View RSS Feed

Spring Framework

Resource Representation in Spring

Rate this Entry
by , 11-28-2011 at 02:05 AM (1464 Views)
In my previous tips, I looked out how to make the key RESTful method calls. In all of them the controllerís handler method finishes, and a logical view name is usually returned. In the case that the method doesnít return a logical view name (a method returning void) then the logical view name is derived from the requestís URL. The DispatcherServlet passes the view name to a view resolver in order to facilitate the determination of which view should render the results of the request.

In a human-facing web application, the view chosen is almost inevitably rendered as HTML. View resolution is a one-dimensional activity. If the view name matches a view, then thatís the view weíll go with the results.

Resolving view names into views that can produce resource representations is not as straightforward as it appears with RESTful services. There is another aspect to consider. The view need to match the view name, but as well the view needs to be chosen to suit the client. That means you need to match the clients needs (i.e. XML) with the rendering (i.e. XML). If they donít align it will not produce any rendering of value to the user.

Spring has a ContentNegotiatingViewResolver that is specially created for this situation. It takes the content type that the client wants into consideration in itís rout. Just like any other view resolver, itís configured as a <bean> in the Spring application context, as shown next.

Java Code:
<bean class="org.springframework.web.servlet.view.
    <property name="mediaTypes"> 
	   <entry key="json" value="application/json" /> 
	   <entry key="xml" value="text/xml" /> 
	   <entry key="htm" value="text/html" />
    </property> <property name="defaultContentType" value="text/html" />
In the next tip, we will look at the strategy used by the ContentNegotiatiingViewResolvers to determine the requested media type.

Submit "Resource Representation in Spring" to Facebook Submit "Resource Representation in Spring" to Digg Submit "Resource Representation in Spring" to Submit "Resource Representation in Spring" to StumbleUpon Submit "Resource Representation in Spring" to Google

Updated 11-30-2011 at 02:42 PM by Spring Framework

Configuration , View , XML , REST , Resource