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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<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>
<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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!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>
<!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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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;
    }
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
        
    }
}
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

Karibasappa G C (KB)
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