by January 11, 2000 0 comments

This article is in continuation of the piece “Workingwith Java Servlets” that appeared in the October issue of PC Quest (page153). In that article we talked about generating simple dynamic pages usingServlets. This month we will see how to do more advanced things using servlets.

A database servlet

Many websites ask you to register, by giving information likename and e-mail address. Once you hit the submit button, the information youprovide is usually stored in a database. This information is moved from the Webpage to the database in one of many ways, like by using CGI scripts, PHP andJava Servlets. In this article we will see how to do this using Java Servlets.

Let’s take an example of a Web page, which asks for detailsof a person who wants to subscribe to PC Quest, First we’ll run the examplewherein the Servlet (we have named it DatabaseServlet) will take data from thisWeb page and store it in an Access database. We’ll then see how theDatabaseServlet works.

Run the DatabaseServlet

First copy the files subscription.html, DatabaseServlet.javaand subscription. mdb from cdrom\sorc_cod\servlet\data base to any directory inyour hard disk. Compile using javac, the Java compileravailable with JDK (this has been given in the CD with the August 2000 issue ofPC Quest). You may remember from last month’s article that if you don’t haveaccess to a Web server that supports Servlets, you will need to setup theServletrunner to test the Servlet.

Now go to Control Panel and click the ODBC Data Sourcesapplet and then click the Add button. Next, select Microsoft Access Driver (*.mdb)and then click Finish. In the text field Data Source Name, enter”subscription”. Now click the Select button, and from the File Openwindow, select the file subscription.mdb that you have already copied from theCD.

Now, fire up your browser and open the file subscription.html.Fill in the text fields and then click the submit button. If everything workedproperly, you will see an HTML page displaying “Database has been updatedsuccessfully”.

How the DatabaseServlet works

Let us see what happened to the database. Opensubscription.mdb in Access and look in the table subscriber_info. You will seethe name, years of subscription, address, telephone number, e-mail and creditcard number as you had entered in the Web page.

What achieved this magic? To understand that, lets look atthe code that went into the making of our Database Servlet.

Open the file in a text editor. Alsoopen the source of subscription.html (open the page in your browser, right clickon the page and select view source). Let us work backwards. When you press thesubmit button, the doPost( ) method is invoked. Now, if you look at the sourceof subscription.html, you will find that we have given each text field uniquenames like name, years, address, tel_no, email and credit_card.

The method request.getParameter( ) accepts this name andreturns the value in the associated text field as a String, using the codebelow.

String name = request.getParameter("name");

String years_of_subscription = request.getParameter ("years");

String address = request.getParameter ("address");

String tel_no = request.getParameter ("tel_no");

String e_mail = request.getParameter ("email");

String credit_card = request.getParameter ("credit_card");

As you can see, the syntax of getParameter( ) is


Next, the Servlet connects to the database in the methodconnectToData base( ). This method contains the following code:

Class.forName("sun.jdbc.odbc.Jdbc OdbcDriver");

Connection con =DriverManager.get Connection("jdbc:odbc:subscription","","");

stmt = con.createStatement();

Here we use the jdbc-odbc driver to connect to the Accessdatabase named subscription (as setup from the control panel). In the secondline the data source name, login name and the password are passed as parametersto the get Connection( ) method. The second line is in the form:

DriverManager.getConnection("jdbc: odbc:<datasource>","<username>"," <password>");

Since we had not given a login name and a password whilecreating the data source in the ODBC Data Sources applet, the username andpassword are empty strings"".

The next line of code is to create a Statement object, whichis used to query the database. The query which is executed by the Statementobject is:

stmt.executeUpdate("INSERT INTO subscriber_info VALUES(‘"+

name+"’,’"+years_of_ subscription+"’,’"+

address+"’,’" +tel_ no+"’,’"+e_mail+"’,’"+


Here subscriber_info is the name of the table in thedatabase. Finally, if no errors occur while connecting to or querying thedatabase, the Servlet generates an HTML page which says "Database has beenupdated successfully" else it generates an HTML page which shows themessage "ERROR: The database is not updated".

When the doGet( ) method of the Servlet is called, thecontents of the database will be displayed in your browser. In this case, theServlet generates an HTML page in which all the fields of the tablesubscriber_info are displayed in a tabular format using HTML tables. Asexplained in the previous article, you can call this method by directly enteringthe URL to the Servlet as:

http://localhost:8080/servlet/Database Servlet.

Lets take a peek into the doGet( ). The line

ResultSet rs = getInformationFromDatabase();

calls the method getInformationFrom Database( ). In thismethod, the database is queried as

rs=stmt.executeQuery("SELECT * FROM subscriber_info");

and the result is stored in a ResultSet object- rs -which isreturned back to the doGet( ) method.

Now coming back to the doGet( ) method, the value of eachfield of the table subscriber_info is extracted and displayed in a cell of theHTML table as:




for(int i=1;i<=6;i++)




The rs.getString( ) method accepts the column number of thetable (1 for the first column, 2 for the second, and so on) as a parameter andreturns the value as a String. Thus all the six columns for name, years ofsubscription, address, telephone number, e-mail and credit card number aredisplayed. The statement while ( )) returns true as long as there aremore rows of the table to be displayed. In other words, the While Loop iteratesthrough all the rows stored in the ResultSet object — rs.

A session tracking servlet

Session tracking is another important feature required byWebsites, particularly by e-commerce sites. Suppose a user visits a shoppingsite where he goes through a number of pages and selects some products forpurchase. Now, once he finishes his shopping, a page is to be displayed to theuser with all the items that he has selected, along with total price, etc. thepage can also has to allow him to make changes. Let us see how this can be doneusing Servlets (we have named this Servlet SessioTracking Servlet).

Technically, when a user goes to a Website, it is said thathe has started a session. The tracking of this session, to know what the user isdoing or selecting, is called session tracking.

Copy the files SessionTrackingServlet. java andcompconfigure.html from the directory cdrom\sorc_cod\servlet on this month’sCD to your hard disk. Then compile and set up the SessionTracking Servlet. Forour example, we will select components like motherboard, processor, etc, andconfigure a PC.

Open compconfigure.html in a Web browser. Select OK in thefirst page to start configuring the computer you want to buy. In the next page,select one of the motherboard models and click OK. You will be taken throughfive such pages where you will select a processor, memory, hard disk, graphicscard, and sound card. In each page take your pick and click OK. Finally, youwill get a page, which will list all the products you have selected.

Let’s parse through the coding of this Servlet. in any text editor. The names of the items,motherboard, processor, RAM, hard disk, graphics card and sound card are storedin the String array named "items" and the different options availablefor each item are stored in the two-dimensional String array named"options".

When you select an item, for example, an AMD processor fromthe third page, the doPost( ) method of the Servlet is invoked. In this method,you store the selection the user makes on each page in an HttpSession object.The object is created from the HttpServletRequest object as below:

HttpSession session = request.getSession(true);

The parameter true tells the getSession( ) method to create asession if it hasn’t been created already.

Now, you will observe the lines:



String selectedValue = request.getParameter(items[pageNumber]);

session.putValue(items[pageNumber], selectedValue);


The if condition is used to skip the first page as you do notmake any selection in it. In the next two lines the selected value from theselection list is retrieved using the request.getParameter(<name-of-the-selection-list>)method. The value is stored in the String selectedValue. Next the selectedValuemust be stored in a session object so that it can be retrieved later. This isdone using putValue( ) method of the session object. The syntax of this methodis:


Hence in the last line, the name of the item from the itemsarray is used as the unique name and the selectedValue is the value for thatunique name. Proceeding further we reach a switch block where the dynamic pagewith the next set of choices is created by calling the generateHtmlPage( )method.

When all the six pages have been displayed, and you have madeyour choices, the final page which displays the selections made is generated bycalling the method generateResultPage( ).

In this method all the values stored in the session objectare extracted. In the first line of this method,

HttpSession session = request.get Session(true); the sessionobject is tried to be created. Since the session has already been created in thedoPost( ) method, it won’t be created again, as you are still in the samesession. The real work is done by the lines:

for (int i=0;i<items.length; i++)

out.println("<br><b>"+items[i]+" :"+


The corresponding value stored for each unique name in thesession object is extracted using session.getValue( ) method. The syntax of thismethod is:

session.getValue(<the unique name stored in the sessionobject>);

Note that the value returned by this method must be casted orconverted to a String, as done in the last line.

Shekhar Govindarajan

No Comments so far

Jump into a conversation

No Comments Yet!

You can be the one to start a conversation.

Your data will be safe!Your e-mail address will not be published. Also other data will not be shared with third person.