Spring 3 MVC and XML example

In Spring 3, one of the feature of “mvc:annotation-driven“, is support for convert object to/from XML file, if JAXB is in project classpath.

In this tutorial, we show you how to convert a return object into XML format and return it back to user via Spring @MVC framework.

Technologies used :

  1. Spring 3.0.5.RELEASE
  2. JDK 1.6
  3. Eclipse 3.6
  4. Maven 3
JAXB in JDK6
JAXB is included in JDK6, so, you do not need to include JAXB library manually, as long as object is annotated with JAXB annotation, Spring will convert it into XML format automatically.

1. Project Dependencies

No extra dependencies, you need to include Spring MVC in your Maven pom.xml only.


	<properties>
		<spring.version>3.0.5.RELEASE</spring.version>
	</properties>

	<dependencies>

		<!-- Spring 3 dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

	</dependencies>

2. Model + JAXB

A simple POJO model and annotated with JAXB annotation, later convert this object into XML output.


package com.mkyong.common.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "coffee")
public class Coffee {

	String name;
	int quanlity;

	public String getName() {
		return name;
	}

	@XmlElement
	public void setName(String name) {
		this.name = name;
	}

	public int getQuanlity() {
		return quanlity;
	}

	@XmlElement
	public void setQuanlity(int quanlity) {
		this.quanlity = quanlity;
	}

	public Coffee(String name, int quanlity) {
		this.name = name;
		this.quanlity = quanlity;
	}

	public Coffee() {
	}
	
}

3. Controller

Add “@ResponseBody” in the method return value, no much detail in the Spring documentation.

As i know, when Spring see

  1. Object annotated with JAXB
  2. JAXB library existed in classpath
  3. “mvc:annotation-driven” is enabled
  4. Return method annotated with @ResponseBody

It will handle the conversion automatically.


package com.mkyong.common.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mkyong.common.model.Coffee;

@Controller
@RequestMapping("/coffee")
public class XMLController {

	@RequestMapping(value="{name}", method = RequestMethod.GET)
	public @ResponseBody Coffee getCoffeeInXML(@PathVariable String name) {

		Coffee coffee = new Coffee(name, 100);
		
		return coffee;

	}
	
}

4. mvc:annotation-driven

In one of your Spring configuration XML file, enable “mvc:annotation-driven“.


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<context:component-scan base-package="com.mkyong.common.controller" />

	<mvc:annotation-driven />

</beans>
Note
Alternatively, you can declares “spring-oxm.jar” dependency and include following MarshallingView, to handle the conversion. With this method, you don’t need annotate @ResponseBody in your method.


<beans ...>
	<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
	
	<bean id="xmlViewer" 
		class="org.springframework.web.servlet.view.xml.MarshallingView">
		<constructor-arg>
		  <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
			<property name="classesToBeBound">
				<list>
					<value>com.mkyong.common.model.Coffee</value>
				</list>
			</property>
		  </bean>
		</constructor-arg>
	</bean>
</beans>

5. Demo

URL : http://localhost:8080/SpringMVC/rest/coffee/arabica

spring mvc and xml example demo

Download Source Code

Download it – SpringMVC-XML-Example.zip (7 KB)

References

  1. Spring MVC and Rss example
  2. mvc-annotation-driven JavaDoc
  3. Jaxb2Marshaller JavaDoc
  4. ResponseBody.html JavaDoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
hack2003
Guest
hack2003

You have a problem writing this way? How do'<'output number?

Gyanendra
Guest
Gyanendra

Hi All, I follow the same code and project executed successfully, but I’m unable to get XML format output, its output on browser is “arabika 100”

svale
Guest
svale

In the other browsers example works perfect in any case: with “.xml” and without “.xml”

svale
Guest
svale

Thank you so much! You example help me a lot!!
Could i make a little notice : if you want the example works in IE browser – use in the end “.xml”. I mean value of RequestMapping

trackback
Spring MVC Tutorial

[…] Spring 3 MVC and XML example Using JAXB to generate XML output from Spring MVC. […]

trackback
Spring 3 MVC hello world example – Annotation

[…] Spring 3 MVC and XML example […]

trackback
Spring 3 MVC hello world example

[…] Spring 3 MVC and XML example […]

Dipanjan
Guest
Dipanjan

I want to add one information to the xml header. I used

It did not help

Dipanjan
Guest
Dipanjan

Want to add

Dipanjan
Guest
Dipanjan

My text is not appearing.
I basically want to add a Doctype with a reference to a dtd file in the Doctype element

Munish Kumar
Guest
Munish Kumar

I am using servlet with Spring as given below. This class has a field which has been AutoWired. I want to use xml configuration for this class and remove off annotation completely . Please let me know how to do this

@Controller(“oauth2Servlet”)
final public class Oauth2Servlet extends HttpServlet implements HttpRequestHandler

…… Web.xml configuration

Oauth2Servlet
oauth2Servlet
org.springframework.web.context.support.HttpRequestHandlerServlet
1

oauth2Servlet
/oauth2

raj
Guest
raj

public @ResponseBody Coffee getCoffeeInXML(@RequestBody Coffee coffee){

String name = coffee.getname;
int name = coffee.getQuantity;
}
Is this correct way to use @RequestBody xml to pojo mapping

lee
Guest
lee

In Spring MVC
i use AJAX
want @controller return “Object also convert XML-String”
(response header text/plain not application/xml)
how to set spriong config

sandeep
Guest
sandeep

Hi it is working fine for list also,

Write a wrapper class for coffee its working , great tutorial , thanks for help

swap
Guest
swap

Hi I am getting a 406 error, please help

lee
Guest
lee

in this case.
How to change “coffee Object” the other xml declaration

lee
Guest
lee

how to set xml data use another encoding

vikesh
Guest
vikesh

when i run the application . it breaks on hitting the specified url. Pls help.

Fei
Guest
Fei

Hi Mark change config to follow .will not working why?

com.mkyong.common.model

Fei
Guest
Fei

Hi Mark change config to follow .will not working why?

com.mkyong.common.model

Fei
Guest
Fei

Hi Mark change config to packagesToScan it’s not working anything need pay attention to?

Satya Prakash
Guest
Satya Prakash
<pre lang="language" I am getting below error , while using above example in my system, I have jdk1.6 that is why i did not include any jaxb in my classpath. System.Windows.Markup.XamlParseException: 'Cannot create unknown type 'scenario'.' Line number '1' and line position '57'. ---> System.Xaml.XamlObjectWriterException: 'Cannot create unknown type 'scenario'.' Line number '1' and line position '57'. at System.Xaml.XamlObjectWriter.WriteStartObject(XamlType xamlType) at System.Xaml.XamlWriter.WriteNode(XamlReader reader) at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector) at System.Windows.Markup.XamlReader.LoadAsync(XmlReader reader, ParserContext parserContext) --- End of inner exception stack trace ---
Praveen.S.Kalawad
Guest
Praveen.S.Kalawad

Thanks alot Mr.MKYong

Tung
Guest
Tung

Ah, seem like fine following the case which return is collection:

@ResponseBody
@RequestMapping(value="/name/{name}", produces = "application/xml", method= RequestMethod.GET)
public EmployeeList getEmployeeByName(Model model, @PathVariable String name){
	List<Employee> e = empService.selectEmployeeByName(name);
	EmployeeList abc= new EmployeeList(e); // EmployeeList just is List
	return abc;
}
Tung
Guest
Tung

Additionally, in dispatcher file:

 
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
	<list>
		<value>com.abc.Employee</value>
                <value>com.abc.EmployeeList</value>
	</list>
    </property>
</bean>
ant
Guest
ant

I solved the problem, thank you very much for your answer, thank the authors often articles

Jay
Guest
Jay

I tried for a List and could not make it to work.
Please help with a working code.
You mentioned EmployeeList is just a list…. could you please post that code ?

Many thanks

pavan
Guest
pavan

Thanks for this tutorial..
It really helped me a lot in setting up Spring restful services..

Mauro
Guest
Mauro

Great tutorial… i got problems when i do for a List. i’d made a Coffees wrapper class for the list but i got repeated elements :(

Sudhakar
Guest
Sudhakar

Simple and Effective tutorial!.. Keep up the good work Mr.young

guiltry
Guest
guiltry

What if i want to return collection of coffee ?

Tung
Guest
Tung

I have same question, too.

trackback
Spring 3 MVC ContentNegotiatingViewResolver example

[…] need to do any extra works, Spring MVC will handle the conversion automatically. Read this Spring MVC and XML, and Spring MVC and JSON examples.4. RSS ViewTo output RSS View, you need to extend […]

trackback
Spring 3 MVC and JSON example

[…] (7 KB)Referencesmvc-annotation-driven documentationHigh-performance JSON processorSpring MVC and XML example […]