Web services using JAXB

Hi Guys here is my brief post on how to develop web services using jaxb notation.

The Java Architecture for XML Binding API (JAXB) makes it easy to access XML documents from applications written in the Java programming language. JAXB is an alternative to using a SAX or DOM parser to access the data in an XML document. When you access an XML document with JAXB, first you bind the schema for the XML document into a set of Java classes that represents the schema. Then you unmarshal the XML document. Unmarshalling a document means creating a tree of content objects that represents the content and organization of the document.

You can also use JAXB to build an XML document. To build an XML document with JAXB, you first bind the schema for the XML document you want to build. Then you create a content tree. Lastly, you marshal the content tree into an XML document.

The following diagram, from Java Architecture for XML Binding API, shows the processes both for accessing and for building XML documents from Java applications.


Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.
No extra jaxb libraries are required if you are using JDK1.6 or above, because JAXB is bundled in JDK 1.6.
Note
For JDK < 1.6, download JAXB from here and put “jaxb-api.jar” and “jaxb-impl.jar” on your project classpath.

now lets see how to code with “jaxb”

/**
 * 
 */
package com.spark.jaxb.model;

import java.io.Serializable;

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

/**
 * @author Pavan Mantha
 * 
 */
@SuppressWarnings("serial")
@XmlRootElement
public class Customer implements Serializable {

	private int id;
	private String firstName;
	private String lastName;
	private String designation;
	private String phoneNumber;

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	@XmlAttribute
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	@XmlElement
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	@XmlElement
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the designation
	 */
	public String getDesignation() {
		return designation;
	}

	/**
	 * @param designation
	 *            the designation to set
	 */
	@XmlElement
	public void setDesignation(String designation) {
		this.designation = designation;
	}

	/**
	 * @return the phoneNumber
	 */
	public String getPhoneNumber() {
		return phoneNumber;
	}

	/**
	 * @param phoneNumber
	 *            the phoneNumber to set
	 */
	@XmlElement
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

}

now its time to code jaxb marshaller,

/**
 * 
 */
package com.spark.jaxb.marshaller;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.spark.jaxb.model.Customer;

/**
 * @author Pavan Mantha
 * 
 */
public class JaxbMarshaller {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Customer customer = new Customer();
		customer.setId(100);
		customer.setFirstName("Pavan");
		customer.setLastName("Mantha");
		customer.setDesignation("SoftwareEngineer");
		customer.setPhoneNumber("123-4567-890");

		try {

			File file = new File("C:\\customer.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

			// output pretty printed
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			jaxbMarshaller.marshal(customer, file);
			jaxbMarshaller.marshal(customer, System.out);

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

and unmarshaller as below.

/**
 * 
 */
package com.spark.jaxb.unmarshaller;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.spark.jaxb.model.Customer;

/**
 * @author Pavan Mantha
 * 
 */
public class JaxbUnmarshaller {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {

			File file = new File("C:\\customer.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
			System.out.println(customer);

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

Happy Coding 🙂

Advertisements

10 thoughts on “Web services using JAXB

  1. I need an example regarding unmarshalling xml file using jaxb for java web service in netbeans ide…plz help me out

    1. Hi Aswin,
      its Netbeans or Eclipse the logic remains the same only some project structure differs so i give you logic here,suppose if u have a xsd as below “in my case its item.xsd”

      <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <xsd:element name="item" type="Item"/>
          <xsd:complexType name="Item">
              <xsd:sequence>
                  <xsd:element name="code" type="xsd:string"/>
                  <xsd:element name="name" type="xsd:string"/>
                  <xsd:element name="price" type="xsd:double"/>
              </xsd:sequence>
          </xsd:complexType>
      </xsd:schema>
      

      open command prompt and run ‘xjc item.xsd’, it create the pojo and ObjectFactory class required for unmarshalling in a “generated” package

      <?xml version="1.0"?>
      <item>
                <code>I001</code>
                <name>First item</name>
                <price>100000</price>
      </item>
      

      Now its time to write the unmarshaller class as below

      import generated.Item;
      import java.io.File;
      import javax.xml.bind.JAXBContext;
      import javax.xml.bind.JAXBElement;
      import javax.xml.bind.JAXBException;
      import javax.xml.bind.Unmarshaller;
      
      public class UnmarshallingDemo {
      
          public static void main (String [] args) {
              try {
                  JAXBContext jc = JAXBContext.newInstance ("generated");
      
                  Unmarshaller u = jc.createUnmarshaller ();
      
                 File f = new File ("item.xml");
                 JAXBElement element = (JAXBElement) u.unmarshal (f);
      
                 Item item = (Item) element.getValue ();
                 System.out.println (item.getCode ());
                 System.out.println (item.getName ());
                 System.out.println (item.getPrice ());
             } catch (JAXBException e) {
                 e.printStackTrace ();
             }
         }
      }
      
      1. Thank you sir i understood the process but i need the unmarshalling for a java web service for web application

  2. when i run the web service the success message is coming as”unmarshalled” but i need the java content objects to be displayed in the output console

    1. Hi Aswin,

      When you want to display the content get the unmarshalled object and call the properties of the unmarshalled object as shown below

      Customer customer = (Customer) jaxbUnmarshaller.unmarshal(<!-- your stream to unmarshall -->);
      System.out.println(customer); //display the object serial
      System.out.println(customer.getFirstName); //display the property of the object that is unmarshalled.
      
  3. /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    package student;
    import java.math.BigInteger;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.bind.JAXBException;
    import org.netbeans.xml.schema.studentschema.Student;
    /**
    *
    * @author Vijayalekshmy
    */
    @WebService()
    public class GetDetails {

    /**
    * Web service operation
    */
    @WebMethod(operationName = “GetMarks”)
    public String GetMarks(@WebParam(name = “Rollno”)
    String Rollno) {
    //TODO write your implementation code here:
    Student student;
    java.io.File stuxml = new
    java.io.File(“C:\\Users\\Vijayalekshmy\\Documents\\NetBeansProjects\\jaxb1\\src\\java\\Students.xml”);
    try{
    student = jaxbUnmarshalFromFile(stuxml);
    double Mark1 = student.getMark1();
    double Mark2 = student.getMark2();
    System.out.println(“Mark1: “+Mark1+” Mark2: “+Mark2);
    }
    catch(java.io.FileNotFoundException fe)
    {
    System.out.println(fe);
    }
    catch(JAXBException je)
    {
    System.out.println(je);
    }
    return “Unmarshalled”;
    }
    private org.netbeans.xml.schema.studentschema.Student jaxbUnmarshalFromFile(java.io.File file) throws java.io.FileNotFoundException, javax.xml.bind.JAXBException {
    org.netbeans.xml.schema.studentschema.Student ret = null;
    java.io.InputStream is = null;
    try {
    javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(org.netbeans.xml.schema.studentschema.Student.class.getPackage().getName());
    javax.xml.bind.Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
    is = new java.io.FileInputStream(file);
    ret = (org.netbeans.xml.schema.studentschema.Student) unmarshaller.unmarshal(is);
    } finally {
    try {
    is.close();
    } catch (Exception ex) {
    java.util.logging.Logger.getLogger(“global”).log(java.util.logging.Level.SEVERE, null, ex);
    }
    }
    return ret;
    }

    }

    I have provided my web service code for unmarshalling for getting the content java objects….i need to unmarshal the details of the xml file….plz help me out….This is an example for a student details where using the id no the rest of the details are displayed as a part of unmarshalling…plz help me out

  4. /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    package student;

    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.bind.JAXBException;
    import org.netbeans.xml.schema.studentschema.Student;
    /**
    *
    * @author Vijayalekshmy
    */
    @WebService()
    public class GetStudentDetails {

    /**
    * Web service operation
    */
    @WebMethod(operationName = “getMarks”)
    public String getMarks(@WebParam(name = “RollNo”)
    String RollNo) {
    //TODO write your implementation code here:
    Student student;
    java.io.File stuxml = new
    java.io.File(“C:\\Users\\Vijayalekshmy\\Documents\\NetBeansProjects\\jaxbash3\\src\\javaStudents.xml”);
    try{
    student = jaxbUnmarshalFromFile(stuxml);
    double Mark1 = student.getMark1();
    double Mark2 = student.getMark2();
    System.out.println(“Mark1: “+Mark1+” Mark2: “+Mark2);
    }
    catch(java.io.FileNotFoundException fe)
    {
    System.out.println(fe);
    }
    catch(JAXBException je)
    {
    System.out.println(je);
    }
    return “Unmarshalled”;
    }

    private org.netbeans.xml.schema.studentschema.Student jaxbUnmarshalFromFile(java.io.File file) throws java.io.FileNotFoundException, javax.xml.bind.JAXBException {
    org.netbeans.xml.schema.studentschema.Student ret = null;
    java.io.InputStream is = null;
    try {
    javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(org.netbeans.xml.schema.studentschema.Student.class.getPackage().getName());
    javax.xml.bind.Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
    is = new java.io.FileInputStream(file);
    ret = (org.netbeans.xml.schema.studentschema.Student) unmarshaller.unmarshal(is);
    } finally {
    try {
    is.close();
    } catch (Exception ex) {
    java.util.logging.Logger.getLogger(“global”).log(java.util.logging.Level.SEVERE, null, ex);
    }
    }
    return ret;
    }

    }
    This the correct code….plz respond how to unmarshal the xml file into java objects for the student detais

  5. Ca you please let me know an example where i can work wothout annotations (because in jdk 1.4 annotations are not supported ). I am getting javax.xml.bind.UnmarshalException: unexpected element (uri:””, local:”response”). Expected elements are (none)

    1. Hi
      let me use a domain mode customer.java and PhoneNumber.java as below

      package blog.defaults;
       
      import java.util.List;
       
      public class Customer {
       
          private String firstName;
          private String lastName;
          private List<PhoneNumber> phoneNumbers;
       
          public String getFirstName() {
              return firstName;
          }
       
          public void setFirstName(String firstName) {
              this.firstName = firstName;
          }
       
          public String getLastName() {
              return lastName;
          }
       
          public void setLastName(String lastName) {
              this.lastName = lastName;
          }
       
          public List<PhoneNumber> getPhoneNumbers() {
              return phoneNumbers;
          }
       
          public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
              this.phoneNumbers = phoneNumbers;
          }
       
      }
      
      package blog.defaults;
       
      public class PhoneNumber {
       
          private String foo;
          private String bar;
       
          public String getType() {
              return foo;
          }
       
          public void setType(String type) {
              this.foo = type;
          }
       
          public String getNumber() {
              return bar;
          }
       
          public void setNumber(String number) {
              this.bar = number;
          }
       
      }
      

      and your demo would look something like this.

      package blog.defaults;
      
      import javax.xml.bind.*;
      import javax.xml.namespace.QName;
      import javax.xml.transform.stream.StreamSource;
      
      public class Demo {
      
          public static void main(String[] args) throws Exception {
              JAXBContext jc = JAXBContext.newInstance(Customer.class);
      
              StreamSource xml = new StreamSource("src/blog/defaults/input.xml");
              Unmarshaller unmarshaller = jc.createUnmarshaller();
              JAXBElement<Customer> je1 = unmarshaller.unmarshal(xml, Customer.class);
              Customer customer = je1.getValue();
       
              JAXBElement<Customer> je2 = new JAXBElement<Customer>(new QName("customer"), Customer.class, customer);
              Marshaller marshaller = jc.createMarshaller();
              marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
              marshaller.marshal(je2, System.out);
           }
      
      }
      

      check it out and give me ur feedback.
      Happy coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s