A Jersey Web Service that returns XML

Now we are going to create a web service, which doesn't return String. It returns Objects or may be we can say XMLs(after this post, you will say that there is actually no difference in them)
Let's say, There is a Web service which accepts the user name in url (not as a parameter) & returns the details of the users with the same name in XML.
It is easily understandable that, we need to use a list as the number of users with the same name is not known.


So, we need to write the web service as following one in order to return multiple user's details.
@GET
@Path("/{name}")
public List<User> getUserDetailsFromURL(@PathParam("name") String name) {
User returnUser = new User();
List<User> returnList = new ArrayList<User>();
if (name != null && !"".equals(name)) {
   setUserDetails();
   for (int count = 0; count < userList.size(); count++) {
    if (name.equalsIgnoreCase(userList.get(count).getName())) {
     returnUser = userList.get(count);
     returnList.add(returnUser);
    }
   }
  } 
return returnList;
}

But, to return these objects in the form of XML, we need to modify bean class(e.g. User.j as follows:


import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 @XmlRootElement(name = "user")

public class User {
 private String name;
 private String surname;
 private String address;
 public User() 
 {
 }
 public User(String name, String surname, String address) {
  this.name = name;
  this.surname = surname;
  this.address = address;
 }
 @XmlElement(name = "surname")
 public String getSurname() {
  return surname;
 }
 public void setSurname(String surname) {
  this.surname = surname;
 }
 @XmlElement(name = "name")
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @XmlElement(name = "address")
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
}
Now what does it mean by  @XmlRootElement(name = "user") & @XmlElement(name = "name") ?

@XmlRootElement(name = "user") means, that if a XML represents User object, then the root element for this User object is "user".


@XmlElement(name = "name") means that inside the user node, we will find the name property of the object from "name" node.


And, if, multiple users are returned, then the root element will be "users"

If we run the url in our browser: http://localhost:8080/Test/resources/test/Tom the result will be a XML tree as follows:




Well, that is how we create a web service which returns objects or list of objects in  form of XML.




Feel free to share & please post some response.


No comments :

Post a Comment