views:

27

answers:

2

I have a spring controller (MyController) which servers data as json.

With a few configuration changes, I will be able to reuse the same controller and have it serve the same data, but as xml, not json.

I'd love to be able to create myControllerInstanceA, and configure it to use /json as a base url, then create myControllerInstanceB and have it use /xml as a base url.

The only way I can think of to do this is to subclass MyController, and set the subclass's @requestMapping to /xml. I'd rather be able to do some configuration in my springap-servlet.xml to achieve the same effect.

Is this possible?

I'm guessing some of you spring wizards reading this might be thinking "why the heck would he want to do that". So I'll explain the techniques i'm using: I'm creating a controller, which adds simple java beans to a ModelAndView. The controller also ads a view. The view takes the java beans and serializes them to json, or to xml, depending on how the controller was configured. I think there is probably a more Spring-ish way to do this, but this approach seemed simple and straightforward enough. Also, it allows me to work with a JSON library I'm familiar with, rather than the one that Spring seems set up to use. Points for anyone who tells me the Spring way to do it -- how to easily serve the same data as either json or xml, reusing controller code as much as possible.

+1  A: 

Use ContentNegotiatingViewResolver to resolve the views. This resolve will use different configured views to render the model based on the request's Accepts Header or extension. By default it uses the MappingJacksonJsonView for JSON and you will have to configure an Xml Marshaller for use with the MarshallingView.

With this configuration you can have each annotated method support infinite data formats.

Check out this example.

BrennaSoft
+1  A: 

I'm not sure if you're asking for this, but Spring 3 has ContentNegotiationResolver which can help to return json or xml:

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

And in the controller you can map json and xml to the same controller method.

@Controller
class MyClass(){
    @RequestMapping(value={"/yourURL.json", "/yourURL.xml"})
    public Object yourController(){
        return Object
    }
}
Javi
Thank you! Much appreciated.
morgancodes