| By Chad Darby | Article Rating: |
|
| February 1, 1998 12:00 AM EST | Reads: |
22,271 |
The drive to create a successful Web site has resulted in Web applications that are interactive and informative. A wealth of information is stored in corporate databases and there is a rush to publish this information on the Web. Corporations' traditional client/server applications are being edged out by Web-based applications. This occurrence is possible thanks to the universal client, the Web browser.
This article is the second in a three-part series on Java servlets. Last month (JDJ, Vol. 3, Iss. 1), I gave you an overview of the Java servlet technology and how to migrate your existing CGI scripts to Java servlets. This article will not reintroduce those concepts. I assume that you are familiar with the basics of the Java Servlet API and the Java Database Connection API.
In this article, you will learn how to build a 3-tier database application that uses Java servlets and the Java Database Connection (JDBC). You will witness the construction of each tier and understand the techniques used to create Java Servlets with database connectivity.
The Challenge
A prominent public speaker keeps track of students who attend her Internet seminars. After each seminar, she exchanges business cards with the interested students. She then enters the student data into her database program.
Instead of entering the data from each business card, she envisions a Web application that would do the work for her. At each seminar, the Web application is set up on several Web terminals. Each student registers at a Web terminal and provides their name, company, e-mail address, course title and expectations. The Web application also has the option to display an updated list of all students.
3-Tier Solution
The Web application is made up of three tiers: Web browser, servlet middleware and database server. The three tiers are illustrated in Figure 1.
The first tier uses a Web browser to take advantage of the installed user base of this universal client. An HTML form is used for user-input and the results of the database query are returned as an HTML page. Using HTML for user-input and displaying the data lowers the requirement of the client's browser version. This Web application does not impose the requirement of a Java-enabled browser with the latest JDK patch.
The second tier is implemented with a Web server running Java servlets. The Java servlet is able to access the database and return an HTML page listing the data. Please note that Java servlets are not restricted to Sun Microsystem's Java Web Server. You can also use Java servlets with the following servers: Microsoft IIS, Netscape FastTrack and Enterprise Server and O'Reilly WebSite Professional. Servlet functionality is possible with Live Software's JRun product, http://www.livesoftware.com. Sun's Java Server page, http://jserv.javasoft.com, also has a list of servlet-enabled Web servers.
The third tier is the back-end database server. The Java servlet can access information in the database provided that a JDBC driver exists. In our situation, the public speaker's database is MS-Access so we can use the JDBC-ODBC driver that is bundled with the Java Development Kit versions 1.1 and higher.
Application Interaction
As you can see, the application is partitioned into three different tiers. Figure 2 illustrates the interaction between the different tiers of the application.
Each step of the interaction is described below.
Step 1:
The user enters information into an HTML form. The form data is passed to the Java servlet running on the Web server.
Step 2:
The Java servlet parses the form data and constructs an SQL statement. The SQL statement is passed to the database server using the Java Database Connection (JDBC).
Step 3:
The database server executes the SQL statement and returns a result set to the Java servlet.
Step 4:
The Java servlet processes the result set and constructs an HTML page with the data. The HTML page is then returned to the user's Web browser.
Analyzing the
Database Schema
Our public speaker is currently storing the student information in a MS Access database. The database contains one data table called Students. The data fields are defined in Table 1.
Designing the Web Browser Interface
The browser interface is composed of a main menu page. This page presents the user with the option of student registration or displaying the students in the database. HTML code for the main menu is provided in Listing 1.
Student Registration Form
The students register using an HTML form. The form collects name, e-mail address, company name and other course information. A snapshot of the student registration form is given in figure 3.
Once the user enters their information then the "Register" button sends the data to the Java servlet.Developing the Servlet Middleware
The servlet middleware encapsulates the business logic of the application. The servlet parses the form data and constructs an SQL statement. The SQL statement is then passed to the database server. After executing the SQL statement, the database server returns a result set back to the servlet. At this time, the servlet processes the result set and constructs an HTML page for the user.
The servlet being created is called StudentDBServlet. The StudentDBServlet has methods to perform the following functions: initialization, servicing requests, displaying students and registering a student. Let's look at each of these functions in detail.
Initializing the Servlet
In the life cycle of a servlet, the init() method is called the first time the servlet is invoked. Listing 3 is the code listing for the init() method.
For the StudentDBServlet, a database connection is opened and prepared statements are created for displaying a student list and registering a student. The database connection is left open for the lifetime of the servlet. Depending on your design, you can open and close a connection for each SQL query. However, in this application the database connection is opened only once.
Servicing User Requests
Whenever a servlet is invoked the service() method is called. The service() method is the main entry point for servlets. However, if this is the first time the servlet is being invoked, then the init() method is called followed by the service() method.
The service() method in this application is used to branch the request to the appropriate method. The student registration form has a hidden field called Register. The service method checks the value of the Register field. If the value is non-null then the registerStudent() method is called. If the field does not exist on the HTML page then a null value is returned. A null value results in the execution of the displayStudents() method.
Displaying the Student List
The displayStudents() method encapsulates the business logic to access the database and display the student list. This is accomplished by using a supporting Student class. The code for the Student class is given in Listing 4.
The Student class has data members to hold information for one student. The Student class also has constructors that can create an object based on form data or a database result set. The code below demonstrates how a student's last name is accessed from the form data.
lastName = request.getParameter("LastName");
The request object is an instance of HttpServletRequest. The request object contains the form data. The form data is accessed by calling the getParameter() method and providing the name of the form field. The student registration form has a LastName field. Refer to my earlier article in JDJ for a detailed discussion of accessing form data with servlets.
The Student class has methods for accessing its data members and for providing a string representation of its data. Listing 4 contains the code listing for the methods of the Student class. The toString() method returns a normal string version of the data members. The toWebString() method returns the data as an HTML-formatted unordered list. The toTableString() method returns the data as an HTML-formatted table row. These methods are used to build the student list.
Constructing an HTML page creates the student list. In the displayStudents() method of Listing 3, the heading of the HTML page is created. Next the table heading is created to display the information as shown below.
The servlet sends a request to the database server to get a list of students. The following SQL statement was prepared in the init() method.
select * from Students order by LastName;
The SQL statement will return a list of students in alphabetical order based on the last name. The result set is used to create the body of the HTML table. A while-loop is created to iterate through each record of the result set. The code fragment for the while-loop is:
int rowNumber = 1;
while (dataResultSet.next())
{
aStudent = new Student(dataResultSet);
tableBody += aStudent.toTableString(rowNumber);
rowNumber++;
}
Each record is used to create a new Student object. The toTableString() method is called to get a string representation of the student data. Recall that the toTableString() method returns the data as an HTML-formatted table row.
After the body of the table is constructed the result set is closed. At the bottom of the Web page, navigation links are provided to the main menu page.A large amount of server-side processing has taken place. However, we are not finished yet. The HTML page must be returned to the Web browser. This is accomplished by opening an output stream on the response object. The response object is an instance of HttpServletResponse. The response object is used to respond to the client. The code for returning the HTML page to the user is:
PrintWriter outputToBrowser = new
PrintWriter(response.getOutputStream());
response.setContentType("text/html");
outputToBrowser.println(htmlPage);
outputToBrowser.close();
The content-type is set for HTML and the htmlPage string is returned to the browser using the println() method. Figure 4 is a sample student list that is returned by the StudentDBServlet.
Registering A Student
The registerStudent() method creates a new Student object based on the HTML form data. The Student object is used to set the parameters on the SQL statement prepared in the init() method. The code fragment below shows how a parameter is set.
registerStatement.setString
(LAST_NAME_POSITION, aStudent.getLastName());
Once all of the parameters are set then the SQL statement is executed. After the statement is executed the new student data is successfully inserted into the database.
A confirmation page is constructed for the user. The confirmation page contains a list of the data that was successfully entered into the database. The Student.toWebString() method is called to provide an HTML string for an unordered list.
Pulling It All Together
At this point, all three tiers of the application are constructed. Collections of HTML pages represent the user interface component for the browser. The only requirement on the browser is the ability to display HTML tables. The two leading browsers available from Microsoft and Netscape easily satisfy this requirement, thus making the Web application browser-friendly.
The back-end database was developed with Microsoft Access. However, any database could have been used provided that a JDBC driver was available for the database. In our scenario, the public speaker was already tracking student data with MS Access. The Web application gave her the ability to access her legacy data and build on it.
The middleware was the critical piece of the application. The servlet middleware encapsulated the business logic and provided the "glue" between the Web browser interface and the backend database information. The database access was made possible by using a nice blend of Java-based technologies: Java Servlet API and JDBC.
Each of the components in the 3-tier application can reside on different computers. The application can easily be distributed across the network. With the worldwide reach of the Web browser, a user can enter information from a networked computer. The Java servlet middleware can reside on any servlet-enabled Web server. The servlet can, in turn, interact with any networked database server in a different location.
Future Enhancements
This 3-tier Web application allowed students to register their student information. The application also gave the option of displaying an updated student list. However, the application is by no means complete. There are a number of enhancements that can be made to it.
The application can be enhanced to display students from a specific city, company or course. A user could create a custom query to generate the student listing. Also, the application can be enhanced to allow remote database administration features such as updating and deleting student entries. Currently, the application does not perform error checking on the form data entered. Client-side JavaScript can be used to verify user data. The application does not consider the case where a student will attend multiple seminars. The application can be enhanced to hold multiple course titles for a student.
Conclusion
This article presented the basic components and techniques to build a 3-tier database application. You can use this information to quickly and easily build a Web interface to your existing corporate database. The Java servlet technology coupled with the Java Database Connection are the key components in creating a Web application that is informative and interactive.
Resources
Article Source Code Listings:
http://www.j-nine.com/pubs/dbservlets
Sun Microsystem's Java Server Page:
http://jserv.javasoft.com
Live Software, JRun 2.0
http://www.livesoftware.com
Published February 1, 1998 Reads 22,271
Copyright © 1998 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Chad Darby
Ch‡d (shod) Darby is a Java consultant for J9 Consulting, www.j-nine.com. He specializes in developing server-side Java applications and database applications. He also provides Java training for Learning Tree International.
- Kindle 2 vs Nook
- Why IBM’s Server Chief Got Busted
- Is Cloud Computing Like Teenage Sex?
- Industry Experts Discuss the State of Cloud Computing
- Performance Tuning Essentials for Java
- Confessions of a Ulitzer Addict
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- It's the Java vs. C++ Shootout Revisited!
- Cloud Computing Can Revitalize Your Career as Software Developer
- IBM Could "Reinvent" Java: Mills
- Oracle & Cloud Computing: Exclusive Q&A with SVP Richard Sarwal
- A Brief History of Cloud Computing
- Kindle 2 vs Nook
- Cloud CEOs, CTOs & SVPs to Speak at 4th International Cloud Computing Expo
- Why IBM’s Server Chief Got Busted
- Is Cloud Computing Like Teenage Sex?
- Industry Experts Discuss the State of Cloud Computing
- Performance Tuning Essentials for Java
- The Difference Between Web Hosting and Cloud Computing
- Cloud Computing Expo: Exclusive Q&A with Yahoo! SVP Cloud Computing
- Ajax in RichFaces 3.3, JSF 2 and RichFaces 4
- Confessions of a Ulitzer Addict
- My Thoughts on Ulitzer
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- A Cup of AJAX? Nay, Just Regular Java Please
- Java Developer's Journal Exclusive: 2006 "JDJ Editors' Choice" Awards
- The i-Technology Right Stuff
- JavaServer Faces (JSF) vs Struts
- Rich Internet Applications with Adobe Flex 2 and Java
- Java vs C++ "Shootout" Revisited
- Bean-Managed Persistence Using a Proxy List
- Reporting Made Easy with JasperReports and Hibernate
- Creating a Pet Store Application with JavaServer Faces, Spring, and Hibernate
- What's New in Eclipse?
- Why Do 'Cool Kids' Choose Ruby or PHP to Build Websites Instead of Java?
- i-Technology Predictions for 2007: Where's It All Headed?









































