Spring MVC speaking Json or XML

In Spring MVC we can find a nice way of resolving view by type of request. This class is called ContentNegotiatingViewResolver.

It uses the requested media type to find correct View for a request. Task to pick most appropriate view is done by ViewResolvers that are either set expilicty or are taken from application context.

Here is an example of ContentNegotiatingViewResolver with JSON an Xml views provided:

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

    <property name="defaultViews">
       <list>
          <!-- JSON-->
          <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>

          <!-- XML-->
          <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
              <constructor-arg>
                  <bean class="org.springframework.oxm.xstream.XStreamMarshaller">
                      <property name="autodetectAnnotations" value="true"/>
                  </bean>
              </constructor-arg>
          </bean>
        </list>
    </property>
</bean>

JSON
MappingJacksonJsonView is a View that renders JSON content by serializing the model for the current request using Jackson’s ObjectMapper.

XML
For Xml view we can use Jaxb or XStream. Not much difference beetween them: http://blog.bdoughan.com/2010/10/how-does-jaxb-compare-to-xstream.html

Now different types of call to application will cause different return types:
http://localhost/ingredient/list.xml , XML file.
http://localhost/ingredient/list.json , JSON file.
http://localhost/ingredient/list, default view resolver.

There are also other View resolvers like for RSS, velocity or freemarker available.You can find them in: org/springframework/web/servlet/view package.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s