Spring MVC 3: Returning XML through @ResponseBody Spring MVC 3: Returning XML through @ResponseBody xml xml

Spring MVC 3: Returning XML through @ResponseBody


This can be done by adding the following bit of magic to the Spring context (see docs):

<mvc:annotation-driven/>

which amongst other things, provides:

Support for reading and writing XML, if JAXB is present on the classpath.

If JAXB is detected (i.e. if you're on Java6, or otherwise have some JAXB implementation on your classpath), this will register a Jaxb2RootElementHttpMessageConverter with the context, and will provide the ability to spit out XML from the return value of the @ResponseBody-annotated method.

Note: Your question sort-of suggested using a ViewResolver for rendering the XML, but this isn't necessary. The @ResponseBody annotation is designed to bypass the view layer altogether.


I solved this problem with Spring 3 mvc without MarshallingView

@RequestMapping(value = "actionName.xml", method = RequestMethod.GET)public HttpEntity<byte[]> getXml(ModelMap map, HttpServletResponse response) {    String xml = generateSomeXml();    byte[] documentBody = xml.getBytes();    HttpHeaders header = new HttpHeaders();    header.setContentType(new MediaType("application", "xml"));    header.setContentLength(documentBody.length);    return new HttpEntity<byte[]>(documentBody, header);}

that's all. greetings


What I do when I want to return an XML representation of objects using spring is that I define a MarshallingView, e.g.,

<!-- XML view using a JAXB marshaller --><bean id="jaxbView" class="org.springframework.web.servlet.view.xml.MarshallingView">    <constructor-arg>        <bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">            <property name="classesToBeBound">                <list>                    <value>com.company.AClass</value>                </list>            </property>        </bean>    </constructor-arg></bean><!-- Resolve views based on string names --><bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>

Note that there is a whole world of alternatives to jaxb. The next step is

@RequestMapping("/request")public ModelAndView sample() {    return new ModelAndView("jaxbView", "data", "data_to_be_turned_into_xml");}

Or if you want to use the ResponseBody annotation, it would look like:

@RequestMapping("/request")@ResponseBodypublic void sample() {    return "data_to_be_turned_into_xml"}

Note that this requires defining a HttpMessageConverter. See the spring documentation for a perfect sample on how to do this.