Tuesday, 29 May 2012

Spring Web Services

In designing a REST interface the spring framework seemingly does it all - or does it?

In order to handle the various forms of request I have set up the following configuration in the MDR-servlet.xml file:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="defaultContentType" value="text/html" />
        <property name="ignoreAcceptHeader" value="true" />
        <property name="favorPathExtension" value="true" />
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
                <entry key="xml" value="application/xml" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <property name="marshaller" ref="jaxbMarshaller" />
                </bean>
            </list>
        </property>
    </bean>


  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
  </bean>


I think this is saying that if a request comes in with a MIME-type of a) "application/json" then my MappingJacksonJsonView will handle it, and that if a request comes in with a MIME-type of b) "application/xml" type then my MarshallingView will handle it.  If a normal text/html request (c) comes in then the ContentNegotiatingViewResolver will simply leave it to the "default" view resolver.  This is good, I can define a view key, and forward the request to the relevant .jsp file for rendering.

The only problem is that if I change the request type from a) to b), nothing happens - they are both handled by c)....however if I tag the request with ".json" I do get it handled by a) and if I tag it with ".xml"  then it is handled by b) ---this wasn't very clear from the documentation.....or maybe I'm just not reading it correctly....no matter I still get 3 view handlers from the same Controller...so I suppose I'm winning....

Now I have 3 URLS for 1 (get) operation : 



JSON:   /dataelement/{id}/de.json

REST :   /dataelement/{id}/de.xml 

HTML:  /dataelement/{id}/de     (.jsp)


instead of being able to use the same URL and simply change the MIME type in the request header.
It works but it isn't as elegant as I expected....unless I've missed something?



No comments:

Post a Comment