Rest project with JAXB


JAXB


Java Architecture for XML Binding (JAXB) is an XML-to-Java binding technology which helps to transfer
the java object to XML and vice versa.

In other words, JAXB is used to marshal the Java object to XML and unmarshal the XML file to java object.

We can use JAXB with JAX-RS to return Java object in XML format from the rest service.

Create a new Maven Web project in eclipse (Refer Rest service Hello World project for the same)

Step 1

Update pom.xml with below dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2.               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.               xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4.              http://maven.apache.org/maven-v4_0_0.xsd">
  5.   <modelVersion>4.0.0</modelVersion>
  6.   <groupId>RestServiceWithJerseyAndJAXB</groupId>
  7.   <artifactId>RestServiceWithJerseyAndJAXB</artifactId>
  8.   <packaging>war</packaging>
  9.   <version>0.0.1-SNAPSHOT</version>
  10.   <name>RestServiceWithJerseyAndJAXB Maven Webapp</name>
  11.   <url>http://maven.apache.org</url>
  12.    <dependencies>
  13.        
  14.          <dependency>
  15.                <groupId>junit</groupId>
  16.                <artifactId>junit</artifactId>
  17.                <version>3.8.1</version>
  18.                <scope>test</scope>
  19.          </dependency>
  20.    
  21.          <dependency>
  22.                <groupId>org.glassfish.jersey.containers</groupId>
  23.                <artifactId>jersey-container-servlet</artifactId>
  24.                <version>2.24</version>
  25.          </dependency>
  26.  
  27.          <dependency>
  28.                <groupId>javax.xml</groupId>
  29.                <artifactId>jaxb-api</artifactId>
  30.                <version>2.1</version>
  31.          </dependency>
  32.  
  33.          <dependency>
  34.                <groupId>javax.servlet</groupId>
  35.                <artifactId>servlet-api</artifactId>
  36.                <version>2.5</version>
  37.          </dependency>
  38.  
  39.    </dependencies>
  40.  
  41.   <build>
  42.     <finalName>RestServiceWithJerseyAndJAXB</finalName>
  43.   </build>
  44. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
              http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>RestServiceWithJerseyAndJAXB</groupId>
  <artifactId>RestServiceWithJerseyAndJAXB</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>RestServiceWithJerseyAndJAXB Maven Webapp</name>
  <url>http://maven.apache.org</url>
   <dependencies>
        
         <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <version>3.8.1</version>
               <scope>test</scope>
         </dependency>
   
         <dependency>
               <groupId>org.glassfish.jersey.containers</groupId>
               <artifactId>jersey-container-servlet</artifactId>
               <version>2.24</version>
         </dependency>

         <dependency>
               <groupId>javax.xml</groupId>
               <artifactId>jaxb-api</artifactId>
               <version>2.1</version>
         </dependency>

         <dependency>
               <groupId>javax.servlet</groupId>
               <artifactId>servlet-api</artifactId>
               <version>2.5</version>
         </dependency>
 
   </dependencies>
  
  <build>
    <finalName>RestServiceWithJerseyAndJAXB</finalName>
  </build>
</project>

We have added dependencies for Jersey servlet,Jaxb,servelt api and Junit in the above pom file.

Step 2

Update web.xml file with Jersey servlet container

we have defined a special servlet called “jersey-serlvet” in web.xml and mapped it by the URL pattern /rest/*

So just like any other servlet in web application,any request matching with the given pattern i.e /rest/* will be redirected to “Jersey servelt”.

  1. <!DOCTYPE web-app PUBLIC
  2.  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3.  "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4.  
  5. <web-app>
  6.   <display-name>Archetype Created Web Application</display-name>
  7.   <servlet>
  8.         <servlet-name>jersey-serlvet</servlet-name>
  9.          <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  10.         <init-param>
  11.             <param-name>jersey.config.server.provider.packages</param-name>
  12.             <param-value>com.kb.service</param-value>
  13.         </init-param>
  14.         <load-on-startup>1</load-on-startup>
  15.     </servlet>
  16.  
  17.     <servlet-mapping>
  18.         <servlet-name>jersey-serlvet</servlet-name>
  19.         <url-pattern>/rest/*</url-pattern>
  20.     </servlet-mapping>
  21. </web-app>
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
		<servlet-name>jersey-serlvet</servlet-name>
		 <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
		<init-param>
			<param-name>jersey.config.server.provider.packages</param-name>
			<param-value>com.kb.service</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>jersey-serlvet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>

We have also provided the package of java classes(to be qualified as Rest services) under init-param tag.

This package will be considered by Jersey servlet container to identify the actual service when the request comes in.

Step 3

Create a domain class which represents the data with JAXB annotations

  1. package com.kb.model;
  2.  
  3. import java.util.Date;
  4.  
  5. import javax.xml.bind.annotation.XmlElement;
  6. import javax.xml.bind.annotation.XmlRootElement;
  7.  
  8. @XmlRootElement(name="User")
  9. public class User {
  10.     private String id;
  11.     private String name;
  12.     private int age;
  13.     public String getId() {
  14.         return id;
  15.     }
  16.    
  17.     @XmlElement
  18.     public void setId(String id) {
  19.         this.id = id;
  20.     }
  21.     public String getName() {
  22.         return name;
  23.     }
  24.    
  25.     @XmlElement
  26.     public void setName(String name) {
  27.         this.name = name;
  28.     }
  29.     public int getAge() {
  30.         return age;
  31.     }
  32.    
  33.     @XmlElement
  34.     public void setAge(int age) {
  35.         this.age = age;
  36.     }
  37. }
package com.kb.model;

import java.util.Date;

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

@XmlRootElement(name="User")
public class User {
	private String id;
	private String name;
	private int age;
	public String getId() {
		return id;
	}
	
	@XmlElement
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	
	@XmlElement
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	
	@XmlElement
	public void setAge(int age) {
		this.age = age;
	}
}

We have created a User class with id and name to represent the data

@XmlRootElement – specifies the root tag of each user record in xml.

@XmlElement – specifies the child element for each attribute of User record.

Step 4

Create the Rest service class which will return the list of user in xml format

  1. package com.kb.services;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import javax.ws.rs.GET;
  6. import javax.ws.rs.Path;
  7. import javax.ws.rs.Produces;
  8. import javax.ws.rs.core.MediaType;
  9. import com.kb.model.User;
  10.  
  11. @Path("/allUserDetails")
  12.  
  13. public class UserService {
  14.  
  15.     @GET
  16.     @Produces(MediaType.APPLICATION_XML)
  17.     public List<User> getUsers(){
  18.         List<User> userList = new ArrayList();
  19.         User user1 = new User();
  20.         user1.setId("1");
  21.         user1.setAge(20);
  22.         user1.setName("raj");
  23.         User user2 = new User();
  24.         user2.setId("2");
  25.         user2.setAge(21);
  26.         user2.setName("ram");
  27.         userList.add(user1);
  28.         userList.add(user2);
  29.         return userList;
  30.        
  31.     }
  32. }
package com.kb.services;

import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.kb.model.User;

@Path("/allUserDetails")

public class UserService {

	@GET
	@Produces(MediaType.APPLICATION_XML)
	public List<User> getUsers(){
		List<User> userList = new ArrayList();
		User user1 = new User();
		user1.setId("1");
		user1.setAge(20);
		user1.setName("raj");
		User user2 = new User();
		user2.setId("2");
		user2.setAge(21);
		user2.setName("ram");
		userList.add(user1);
		userList.add(user2);
		return userList;
		
	}
}


@Path(“/allUserDetails”)


This annotation helps to map the request URL to appropriate Rest service.

So any request with /allUserDetails (relative to the base URI) will be mapped to UserService.

This annotation should be used either at the class level or at the method level.

@GET


This annotation specifies that only GET requests will be accepted by this method.

This annotation will be used at the method level.

@Produces(MediaType.APPLICATION_XML)


This annotation is used to specify the representation of a data (MIME type) that the service can produce and send it to client.

This annotation can be used either at the class level or at the method level.

If this annotation is applied at the class level,all the methods in the class can produce the same MIME type data by default.

However we can override this at the method level with different MIME type.

We can also specify multiple MIME types as below@Produces({“application/xml”, “application/json”})

Step 5

Build and deploy the project

Step 6

Now access the below url

http://localhost:8080/RestServiceWithJerseyAndJAXB/rest/allUserDetails

we can see that XML output is produced by the Rest service.

rest_jaxb_output

Rest service has returned a list of User object and JAX-B has marshaled those objects into XML and sent to client.

http://localhost:8080 – it is the Server path

/RestServiceWithJerseyAndJAXB – It is the Context root of war file where the rest services are deployed.

/restURL pattern to which the Jersey server responds (configured in web.xml)

/allUserDetailsrelative URL of the rest service specified with @Path annotation.

Download this project RestServiceWithJerseyAndJAXB.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on