Friday, April 27, 2012

JAX-RS Handling XML using JAXB Annotation

In this tutorial, I will show you how to create an “user” object, convert it into XML file,
and return it back to the client.

Create an object, annotate with JAXB annotation to support XML file conversion.

POJO Class with JAXB annotation :
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public class User {

String username;
String password;
int pin;

@XmlElement
public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

@XmlElement
public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@XmlAttribute
public int getPin() {
return pin;
}

public void setPin(int pin) {
this.pin = pin;
}

}



Restful Service for XML in JAX-RS :
To return a XML file, annotate the service method with @Produces("application/xml").

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/xml/user")
public class XMLService {

@GET
@Path("/get")
@Produces("application/xml")
public User getUserInXML() {

User user = new User();
user.setUsername("anuj");
user.setPassword("password");
user.setPin(123456);

return user;

}

}

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/