views:

56

answers:

1

How can I influence the process of choosing a message converter in AnnotationMethodHandlerAdapter for resulting POJO by url extension? I would like to have more representations of one data object, while data representation should be chosen by the requested url extension e.g. /users/2.xml or /users/2.json.

Current configuration of message handlers, which should be chosen based on url extension:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
            <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"
                p:marshaller-ref="xmlMarshaller" p:unmarshaller-ref="xmlMarshaller" />
        </list>
    </property>
</bean>

There is one way, which I'm nearly comfortable with and that is using ContentNegotiatingViewResolver, however I would like to bypass the process of view resolution and directly use message converters. Also when creating actions, using ResponseEntity in public ResponseEntity<User> showUser() provides fine grained control of resulting http status codes definitions (OK, NOT_FOUND, NO_CONTENT, ..). I couldn't find a way of using ResponseEntity with ContentNegotiatingViewResolver, which would also satisfy my needs.

Another way could be by modifying the request accept header to application/xml or application/json based on the url extension. This way, all the processing should go directly to the configured message converter. However I don't know a reasonable way to tamper the request headers.

Thanks.

+1  A: 

Since the choose of HttpMessageConverters uses the Accept request header, perhaps the simpliest way to implement a content negotiation is to replace this header with the desired media type specified by the URL extension.

This can be implemented either as a Filter (using HttpServletRequestWrapper to replace header value) or by overriding AnnotationMethodHanlderAdapter.createHttpInputMessage() as suggested in SPR-7517 (requires Spring 3.0.2).

See also SPR-6993.

axtavt
Thanks, you saved my day :) went the `SPR-7517` way
Juraj Blahunka