ZeePedia

JAVA: AddressBook Case Study Using Sevlets

<< JAVA: Session Tracking 2
Java Server Pages 1 >>
img
Web Design & Development ­ CS506
VU
Lesson 33
AddressBook Case Study
Using Sevlets
Design Process
In this handout, we will discuss the design process of a simple address book. A step by step procedure of
creating a simple address book is given below.
Layers & Web Application
As discussed previously, normally web applications are partitioned into logical layers. Each layer performs
a specific functionality which should not be mixed with other layers. For example data access layer is used
to interact with database and we do not make any direct calls to database from the presentation layer.
Layers are isolated from each other to reduce coupling between them but they provide interfaces to
communicate with each other.
Simplified view of a web application and its layers
-Presentation Layer
Provides a user interface for client to interact with application. This is the only part of application
visible to client.
-Business Layer
The business or service layer implements the actual business logic or functionality of the application.
For example in case of online shopping systems this layer handles transaction management.
-  Data Layer
This layer consists of objects that represent real-world business objects such as an Order,
OrderLineItem, Product, and so on. It also encapsulates classes which are used to interact with the
data providing services such as databases, other web services etc.
In our case study of address book, we will also try to make use of the layered architecture. We will create a
separate layer for working with data, and our presentation and business logic will be merged into servlets. It
means that we will not have separate layers for presentation and business rather one layer (formed by
servlets) will do the job of both presentation and business logic. The extent to which you divide your
application into layers depends upon the size of the application and some other factors such as scalability,
portability etc.
Step 1
Create a database (AddressBook)
Make a table named Person according to the figure shown below. It has columns name, address,
phomeNum
245
img
Web Design & Development ­ CS506
VU
Step 2
The next step is to create a class that can hold the information of a single person. Remember we have stored
the information in the database, now when we extract this information from the database as a result of some
search, we will require some object to store the data for that particular person. The PersonInfo class will be
used at that point to store the retrieved data and transport it to presentation layer. Also we extend this
application and add the functionality of "AddingNewContacts" in the database. The PersonInfo class can be
used to transport data from front end to the database.
Make a PersonInfo class with the following consideration
It has three three attributes: name, address, ph. No.
It has a parameterized constructor which takes in the above mentioned parameters
Override the toString() method
//File: PersnInfo.java
public class PersonInfo {
String name;
String address;
String phoneNum;
public PersonInfo(String n, String a, String pn) {
name = n;
address = a;
phoneNum = pn;
}
public String toString( ){
return "Name: " + name + " Address: " + address + " Phone No: " + phoneNum;
}
}// end class PersonInfo
Note: To keep the code simple, attributes (name, address & phoneNum) are not declared as private,
which is indeed not a good programming approach.
Step 3
Now we will create a class that will be used to interact with the database for the search, insert, update and
delete operations. We will call it PersonDAO where DAO stands for the "data access object". The
PersonDAO along with the PersonInfo class forms the data layer of our application. As you can see that
these two classes do not contain any code related to presentation or business logic (There is not much of
business logic in this application anyway). So PersonDAO along with PersonInfo is used to retrieve and
store data in this application. If at some stage we choose to use some other way of storing data (e.g. files)
only the PersonDAO class will change and nothing else, which is a sign of better design as compared to a
design in which we put every thing in a single class.
246
img
Web Design & Development ­ CS506
VU
So, Make a PersonDAOclass which contains:
a searchPerson(String name) method that first establishes a connection to the database and returns
PersonInfo object after searching the information of the specified person from the database.
//File: PersonDAO.java
import java.sql.*;
public class PersonDAO {
// method searchPerson
public PersonInfo searchPerson(String sName){
PersonInfo person = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:AddressBookDSN";
Connection con = DriverManager.getConnection(url);
String sql = "SELECT * FROM Person WHERE name = ?";
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setString(1, sName);
ResultSet rs = pStmt.executeQuery();
if (rs.next( ) ) {
String name = rs.getString("name");
String add = rs.getString("address");
String pNum = rs.getString("phoneNum");
person = new PersonInfo(name, add, pNum);
}
con.close();
}catch(Exception ex){
System.out.println(ex);
}
return person;
}// end method
}
Step 4
To find what user wants to search, we need to give user an interface through which he/she can enter the
input. The SearchPesonServlet.java will do this job for us, It will collect the data from the user and submit
that data to another class. The SearchPersonServlet forms the part of our presentation layer. As you can see
that it is being used to present a form to the user and collect input.
Write SearchPersonServlet.java
Will take input for name to search in address book
Submits the request to ShowPersonServlet
//File: SearchPersonServlet.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SearchPersonServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,HttpServletResponse
esponse)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>" + "<body>" +"<h1> Address Book </h1>" +"<form action=showperson >"
+ // showperson is alias or
247
img
Web Design & Development ­ CS506
VU
// url pattern of
// ShowPersonServlet"<h2> Enter name to
search </h2> <br/>" +"<input type=text name=pName /> <br/>" +"<input type=submit
value=Search Person />" +"</form>" +"</body>" +"</html>"
);
out.close();
}
// Handles the HTTP GET method.protected void
doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);}
// Handles the HTTP POST method protected void doPost(HttpServletRequest
request,HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
Step 5
The data submitted by the SearchPersonServlet will be submitted to another servlet i.e. ShowPersonServlet,
which will interact with the DataLayer(Business logic processing) collects the output and show it to the
user. The ShowPersonServlet forms the part of our presentation layer and business layer. As you can see
that it is being used to do processing on the incoming data and giving it to data layer (business layer) and
present data/output to the user (presentation layer)
. Write ShowPersonServlet.java
. Receives request from SearchPersonServlet
. Instantiate objects of PersonInfo and PersonDAO class
. Call searchPerson() method of PersonDAOclass
. Show results
//File : ShowPersonServlet.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowPersonServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("pName");
// creating PersonDAO object, and calling searchPerson() method
PersonDAO personDAO = new PersonDAO();
PersonInfo person = personDAO.searchPerson(name);
out.println("<html>");
out.println("<body>");
out.println("<h1>Search Results</h1>");
248
img
Web Design & Development ­ CS506
VU
if (person != null){
out.println("<h3>"+ person.toString() +"</h3>" );
}
else{
out.println("<h3>Sorry! No records found</h3>" );
}
out.println("</body>");
out.println("</html>");
out.close();
}
// Handles the HTTP GET method.protected void
doGet(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException
{processRequest(request, response);}
// Handles the HTTP POST method.protected void
doPost(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException
{processRequest(request, response); }
} // end ShowPersonServlet
Sequence Diagram: Address Book (search use case)
249
img
Web Design & Development ­ CS506
VU
Package
Many times when we get a chance to work on a small project, one thing we intend to do is to put all java
files into one single directory (folder). It is quick, easy and harmless. However if our small project gets
bigger, and the number of files is increasing, putting all these files into the same directory would be a
nightmare for us. In java we can avoid this sort of problem by using Packages.
What is a package?
In simple terms, a set of Java classes organized for convenience in the same directory to avoid the name
collisions. Packages are nothing more than the way we organize files into different directories according to
their functionality, usability as well as category they should belong to. An obvious example of packaging is
250
img
Web Design & Development ­ CS506
VU
the JDK package from SUN (java.xxx.yyy) as shown below:
Figure. Basic structure of JDK package
Basically, files in one directory (or package) would have different functionality from those of another
directory. For example, files in java.io package do something related to I/O, but files in java.net package
give us the way to deal with the Network.
Packaging also helps us to avoid class name collision when we use the same class name as that of others.
For example, if we have a class name called "ArrayList", its name would crash with the ArrayList class
from JDK. However, this never happens because JDK use java.util as a package name for the ArrayList
class (java.util.ArrayList). So our ArrayList class can be named as "ArrayList" or we can put it into another
package like com.mycompany.ArrayList without fighting with anyone. The benefits of using package
reflect the ease of maintenance, organization, and increase collaboration among developers. Understanding
the concept of package will also help us manage and use files stored in jar files in more efficient ways.
How to create a package
Suppose we have a file called HelloWorld.java, and we want to put this file in a package world. First thing
we have to do is to specify the keyword package with the name of the package we want to use (world in
our case) on top of our source file, before the code that defines the real classes in the package, as shown in
our HelloWorld class below:
// only comment can be here
package world;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");}
}
One thing you must do after creating a package for the class is to create nested subdirectories to represent
package hierarchy of the class. In our case, we have the world package, which requires only one directory.
So, we create a directory (folder) world and put our HelloWorld.java into it.
251
img
Web Design & Development ­ CS506
VU
Figure: HelloWorld in world package (C:\world\HelloWorld.java)
How to use package
By using "import" keyword, all class files reside only in that package can be imported. For example,
// we can use any public classes inside world package
import world.*;
// import all public classes from java.util package
import java.util.*;
// import only ArrayList class (not all classes in
// java.util package)
import java.util.ArrayList;
Note: While working with IDEs, You don't have to create folders (packages) and to place classes at right
locations. Many IDEs (like netBeans® 4.1) performs this job on your behalf.
JavaServer Pages (JSP)
Like Servlets, JSP is also a specification. JSP technology enables Web developers and designers to rapidly
develop and easily maintain, information-rich, dynamic Web pages that leverage existing business systems.
As part of the Java technology family, JSP technology enables rapid development of Web-based
applications that are platform independent. JSP technology separates the user interface from content
generation, enabling designers to change the overall page layout without altering the underlying dynamic
content.
The Need for JSP
With servlets, it is easy to
--
Read form data
--
Read HTTP request headers
--
Set HTTP status codes and response headers
--
Use cookies and session tracking
--
Share data among servlets
--
Remember data between requests
--
Get fun, high-paying jobs
But, it sure is a pain to
--
Use those println()statements to generate HTML
--
Maintain that HTML
The JSP Framework
--
Use regular HTML for most of the pages
--
Mark servlet code with special tags
252
img
Web Design & Development ­ CS506
VU
--
Entire JSP page gets translated into a servlet (once), and servlet is what actually gets
invoked (for each request)
--
The Java Server Pages technology combine with Java code and HTML tags in the same
document to produce a JSP file.
Advantages of JSP over Competing Technologies
Versus ASP or ColdFusion
--
JSPs offer better language for dynamic part i.e. java
--
JSPs are portable to multiple servers and operating systems
Versus PHP
--
JSPs offer better language for dynamic part
--
JSPs offer better tool support
Versus pure servlets
--
JSPs provide more convenient way to create HTML
--
JSPs can use standard front end tools (e.g., UltraDev)
--
JSPs divide and conquer the problem of presentation and business logic.
Setting Up Your Environment
In order to create a web-application that entirely consists of JSP pages and Html based pages, the setup
is fairly simple as compared to a servlet based webapplication.
Set your CLASSPATH.
No.
Compile your code.
No.
Use packages to avoid name conflicts.  No.
Put JSP page in special directory, like WEB-INF for servlets No.
o
tomcat_install_dir/webapps/ROOT
o
jrun_install_dir/servers/default/default-app
Use special URL to invoke JSP page. No
However
o  If you want to use java based classes in an application along with JSPs, previous rules
about CLASSPATH, install dirs, etc, still apply to regular classes used by JSP
References:
Java A Lab Course by Umair Javed
Java Package Tutorial by Patrick Bouklee
http://jarticles.com/package/package_eng.html
JavaServer Pages Overview
http://java.sun.com/products/jsp/overview.html
253