XML and Java Tutorial, Part II-Servlets
Posted February 11th, 1999 by Nazmul
We believe in the power of ONE, at ScreamingToaster.
We believe in innovation - ONE experience can change a person's life.
We believe in partnerships - ONE endeavor can establish lasting trust & mutual success.
We believe in education - ONE training course can empower a developer for life.
We believe in giving back - ONE open-source project can inspire future entrepreneur.
ONE person can become the leader that starts a revolution.
ONE company can change the world and make it a better place - join us.
Table of contents
Step 1: Converting an XML document to a Java object model
Creating the Java object model
Step 2: Working with the Java object model
Adding new information to the AddressBook
Deleteing information from the AddressBook
Step 3: Generating an XML document from a Java object model
Downloading the source code and running the program
About the tutorial
In this tutorial, we will read an XML document and map the content of the XML document to a Java object model; this model can then be view and modified using a Servlet. Also, we will generate an XML document from this Java object model.
You should use the JDOM parser to run the code.
Overview
There are three main steps we have to go through when working with XML and Java. They are: converting an XML document to an Java object model, working with the Java object model, and generating (saving) an XML document from the Java object model.
These steps are shown below:
Step 2: Working with the Java object model. The contents of the address book are stored in the object model and this model is used to add, edit, or delete information (about persons).
Step 3: Generating an XML document from the Java object model. The Java object model for the address book is saved as an XML document.
Step 1: Converting an XML document to a Java object model
Please refer to Tutorial I for a detailed explanation on how to read XML documents using the Sun and IBM XML parser using the DOM API.
The DOM API is used to read in information from an XML document. DOM can also be used to change this information, but using DOM is very tedious. DOM can also be used to generate an XML document. There is an easier way of getting around using DOM for modifiying and saving the XML data; by creating a Java object model for the information in the document, you can create this object model by giving it a DOM object that holds all the XML document information. That is, the XML document should be mapped to a Jave object model.
Here is how to map the AddressBook XML document (used in tutorial one) to a set of related Java classes (or a Java object model):
Here is a partial code listing from AddressBook.java:
public class AddressBook {
//data members
…
protected java.util.List data = new ArrayList();
//METHODS
…
/**
Add a person to the address book
@param p a Person object
*/
public void add(Person p){
data.add(p);
…
}//end method
The Person class maps the PERSON element to a class and is a container for the LASTNAME, FIRSTNAME, COMPANY, AND EMAIL elements. The LASTNAME, FIRSTNAME, COMPANY, AND EMAIL elements are mapped to simple Strings.
Here is a partial code listing of Person.java:
public class Person {
//
// Data Members
//
protected String lastName, firstName, company, email;
….
}
Creating the Java object model
Converting AddressBook XML document to a an AddressBook object is done by the IoUtils class. The getAddressBook() method returns an AddressBook object when it is called with an XML filename and path.
Here is a partial code listing from IoUtils.java:
import com.sun.xml.tree.*;
import org.w3c.dom.*;
import java.io.*;
public class IoUtils {
//
// Data Members
//
//xml file location - from user’s input
public static String fileLocation;
//TABLE META DATA
public static final String ROOT_ELEMENT_TAG = “PERSON”;
//
// Methods
//
/**
Return AddressBook object
@return a AddressBook Object
*/
public static AddressBook getAddressBook(String file){
fileLocation = file;
//instantiate AddressBook object
AddressBook addressBook = new AddressBook();
Person person;
try {
//convert comming file location into input stream
InputStream is = new FileInputStream(file);
//create xml document
Document doc =
XmlDocumentBuilder.createXmlDocument(is);
//get the number of person
int size = XmlUtils.getSize(doc , ROOT_ELEMENT_TAG );
for ( int i = 0; i < size; i++ ) {
//instanticate a Person object
person = new Person();
//get information about a person
//and set information
Element row =
XmlUtils.getElement(doc , ROOT_ELEMENT_TAG , i);
person.setLastName(
XmlUtils.getValue( row , “LASTNAME” ) );
person.setFirstName(
XmlUtils.getValue( row , “FIRSTNAME” ) );
person.setEmail(
XmlUtils.getValue( row , “EMAIL” ) );
person.setCompany(
XmlUtils.getValue( row , “COMPANY” ) );
//add a person to an address book
addressBook.add(person);
}//end for
}
catch ( Exception e ) {
System.out.println( e );
return addressBook;
}
return addressBook;
}//end method
….
}//end of IoUtils class
Step 2: Working with the Java object model
Now that we can change the information in the AddressBook XML document into an AddressBook object, we dont need to use DOM anymore. It is very simple to modify the AddressBook object; it is also trivial to create and modify Person objects. The AddressBook contains an ArrayList object (which holds all the Person objects).
Adding new information to the AddressBook
The following code snippet adds a Person object to an AddressBook:
AddressBook addressBook = new AddressBook();
Person person = new Person();
person.setLastName(“John”);
person.setFirstName(“Doe”);
person.setCompany(“Doe Enterprise, Inc.”);
person.setEmail(“john@doeenterprise.com”);
addressBook.add(person);
Editing the AddressBook
To edit the 2nd Person object in the AddressBook, we need to get a Person object in index 2 of the AddressBook object (which is a container of Person objects).
1: Person person = addressBook.get( 2 );
Then with the person object reference, you can change the contents of this person object. Once you have finished your modifications, you can put the person object back in the AddressBook object by using:
1: addressBook.set( 2 , person );
Deleting a person from the AddressBook
To delete the 2nd Person object from the AddressBook object, we simple tell the addressbook to remove the 2nd object it contains:
1: addressBook.remove( 2 );
Step 3: Generating an XML document from a Java object model
Generating an XML document is exactly the same as writing a text file. The object model has to be manually covered to text using all the appropriate tags. DOM can generate XML text based on the intformation contained in it, but since we didn’t use DOM to allow modifications on the AddressBook, we have to manually genereate the XML ourselves. It is actually easier to do it this way, becuase DOM is very messy to manipulate.
We first need to create a new text file using FileOutputStream, we can write Strings to this file using a PrintWriter. Since we know how the Java object model is structured, we can simply add a tag before and after every element. The AddressBook object contains multiple Person objects, so we need to use loop to extract each Person object.
As you might already know, a DTD does not need to be included in XML file. In this example however the DTD is included in the XML file.
Here is an XML-generating code example:
import com.sun.xml.tree.*;
import org.w3c.dom.*;
import java.io.*;
public class IoUtils {
//
// Data Members
//
//xml file location - from user’s input
public static String fileLocation;
…
//
// Methods
//
….
/**
Generating an xml file given a Java object
@param data the collection of Person object
*/
public static void saveAddressBook(java.util.List data){
Person person;
try {
FileOutputStream fo =
new FileOutputStream(fileLocation);
PrintWriter pw = new PrintWriter(fo);
//start writing XML file
pw.println(“<?xml version= ‘1.0′?>”);
pw.println(“<!DOCTYPE ADDRESSBOOK [”);
pw.println(“<!ELEMENT ADDRESSBOOK (PERSON)*>”);
pw.println(“<!ELEMENT PERSON”+
“(LASTNAME, FIRSTNAME, COMPANY, EMAIL)>”);
pw.println(“<!ELEMENT LASTNAME (#PCDATA)>”);
pw.println(“<!ELEMENT FIRSTNAME (#PCDATA)>”);
pw.println(“<!ELEMENT COMPANY (#PCDATA)>”);
pw.println(“<!ELEMENT EMAIL (#PCDATA)>”);
pw.println(“]>”);
pw.println(“<ADDRESSBOOK>”);
pw.println(“”);
int size = data.size();
for ( int i = 0; i < size; i++ ) {
//get a person object and
//write it to a file
person = (Person)data.get(i);
pw.println(” <PERSON>”);
pw.println(” <LASTNAME>”+
person.getLastName()+“</LASTNAME>”);
pw.println(” <FIRSTNAME>”+
person.getFirstName()+“</FIRSTNAME>”);
pw.println(” <COMPANY>”+
person.getCompany()+“</COMPANY>”);
pw.println(” <EMAIL>”+
person.getEmail()+“</EMAIL>”);
pw.println(” </PERSON>”);
pw.println(“”);
}//end for
pw.println(“</ADDRESSBOOK>”);
pw.flush();
pw.close();
}
catch ( Exception e ) {
System.out.println(e);
}
}//end method
}//end of IoUtils class
Working with Servlets
OpenServlet class
This servlet displays a text input field and button. When the button is pressed, a GET request is sent to AddressBookServlet with the String entered in text field.
Here is the HTML that generates the input field and button:
“<form method=GET action=/servlet/AddressBookServlet>“+
“XML file location: <input type=text name=file>“+
“<input type=submit value=Open>“
AddressBookServlet class
This servlet does all the work displaying AddressBook and manipulating it.
The doGet() method is used to display the contents of the AddressBook.
The doPost() method does all the work for adding, editing, or deleting person objects from the AddressBook object. The POST requests made to the AddrssBookServlet must be given an action command. In the doPost() method of the AddressBookServlet calls the appropriate method based on the action’s name.
Here is the doPost() method code:
/**
When this method receives a POST request from
a browser, it executes appropriate action.
@param req http servlet request
@param res http servlet response
@exception ServletException
@exception IOException
*/
protected void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType(“text/html”);
PrintWriter out = new PrintWriter(res.getOutputStream());
out.print(“<html>”);
out.print(“<body>”);
out.print( “<center>” );
//check and see which request is posted
if ( req.getParameter(“action”).equals(“New”) ) {
newRow(out);
}
if ( req.getParameter(“action”).equals(“Edit”) ) {
editRow(out, req);
}
if ( req.getParameter(“action”).equals(“Delete”) ) {
deleteRow(out, req);
}
if ( req.getParameter(“action”).equals(“Add”) ) {
add(out, req);
}
if ( req.getParameter(“action”).equals(“Set”) ) {
set(out, req);
}
out.print( “<hr>Copyright The Bean Factory, LLC.”);
out.print( “1999. All Rights Reserved.”);
out.print( “</center>” );
out.println(“</body>”);
out.println(“</html>”);
out.flush();
out.close();
}//end method
Refreshing the page
In your browser, when you are looking at the AddressBookServlet HTML page, and you try to edit or delete and invalid row number, a message appears (in a new HMTL page) saying that you need to enter the correct row number for a short amount of time. This page then dissapears and the AddressBookServlet page is shown again. If you are wondering how this trick is done here is the code to do it:
“<head><title>XML and Java2 Tutorial Part 2: Sun Parser</title>“+
“<meta http-equiv=\“refresh\” content=\“2; url=” +
“http://” + req.getHeader(“Host”) +
“/servlet/AddressBookServlet;\”>” +
“</head>“
Basically, a temporary page is generated which redirects the browser to the AddressBookServlet after 2 seconds.
Downloading the source code and running the programs
Here is a description of these source code files:
| Name | Description |
| AddressBook.java | Is a container for Person objects, and implements the TableModel |
| Person.java | Stores information about a person |
| XmlUtils.java | Needed by AddressBook.java |
| IoUtils.java | Read from and Write to an XML document (file) |
| OpenServlet | Get XML file location |
| AddressBookServlet | Modify and display AddressBook |
To run the Servlet, place all the class files in your servlet folder (including the XML Parser class files), and start your servlet engine. Start OpenServlet from web browser, e.g.: by loading the following URL: http://127.0.0.1/servlet/OpenServlet
After starting OpenServlet, a text box appears asking a XML file location. Simply type in the folder and file name. For example. I have a AddressBook.xml file in c:/temp. I would type in: c:/temp/AddressBook.xml
If the file name is not provided, the the program will throw an exception when it tries to generate an XML file.
Here is the source code for the Sun Parser: sunServlet.zip
I hope you enjoy this tutorial and find it to be useful. I will have more useful and interesting applications of XML and Java in Part III of the tutorial, so stay tuned and keep coming back
. Click here to send me any feedback/comments.
We do not just build mobile “apps”, we build mobile experiences
Let us build you mobile experiences for Android, BlackBerry, and iPhone. We can also build you cloud-connected experiences that span Mobile (Android, BlackBerry, iPhone), Web (Safari, Firefox, Internet Explorer) and Desktop (PC, Mac, Linux) for a truly connected real-time experience. See our work in action: download RainOrShine for BlackBerry and CityRyde for Android.
- We provide full service, full lifecycle consulting services (planning, graphic design, architecture, marketing, support, and implementation).
- We provide Architecture guidance before implementation; marketing strategy after implementation. Click here to learn more.
Zen Application Framework
All our applications are built using our Zen Application Framework, which helps you avoid the common pitfalls around mobile development. Zen drastically reduces development time & cost for mobile, web, and desktop experiences. Click here to learn more.
Our training services make You self-sufficient & sustainable
Want to learn from the best? We offer Android and BlackBerry developer training programs. Whether you are just starting out, or want advanced training, we have courses for different skill levels & technology requirements. Contact us to learn more, and sign up.
Our values: Open-source. Democratization of knowledge. To lead, never follow
We are leaders in mobile technology. We have done and seen it all. We do not follow trends set by others & we do not make the mistakes made by others. We set the trends for mobile because we are mobile visionaries.