Download Lecture 1: Introduction to Servlets

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CPAN423 Enterprise Java Programming
Lecture #1: An Introduction to Servlets
Java is one of the programming languages that are used to build web
applications. Servlets are java applications running on the server, to
process the requests sent by the client and to send responses back.
Any servlet must implement Servlet interface. The servlet package defines
two abstract classes that implement Servlet interfaces, which are
GenericServlet (from the javax.servlet package) and HTTPServlet (from
the javax.servlet.http package). The HttpServlet extends the
javax.servlet.GenericServlet and is used to handle HTTP requests.
Following are methods of interface Servlet
 void init()
This method is automatically called once during a servlet's execution cycle
to initialize the servlet.
 servletConfig getServletConfig()
Returns a reference to an object that implements interface servletConfig.
This object provides access to the servlet configuration information.
 void service(HttpServletRequest req, HttpServletResponse res)
Which is the first method get called on every servlet to respond to the
client request. Both HttpServletRequest object ( req)
and
HttpServletRespond object ( res) provides an access to input and
output stream that allows the servlet to read data from the client and send
data to the client.
Service method determines the request type and then call either doPost
or doGet method of class HttpServlet in response to post or get request
respectively.
 String getServerInfo()
Defines the servlet information, like author and version
 void destroy()
Called when the server terminates a servlet.
When the server runs the servlet, it creates an HttpServletRequest and
HttpServletResponse object and passes them to service method, which
in turn passes them to doPost, or doGet methods.
1
Class HTTPServlet define the following methods:
 void doPost(HttpServletRequest req, HttpServletResponse res)
Process HTTP Post request.
 void doGet(HttpServletRequest req, HttpServletResponse res)
Process HTTP get request.
 void doDelete(HttpServletRequest req, HttpServletResponse res)
Process Delete request. Called in response to an HTTP delete request
to delete a file from the server.

void doOption(HttpServletRequest req, HttpServletResponse res)
Process Option request. Called in response to an HTTP options
request to send information to the client regarding the HTTP options
supported by the server.

void doPut(HttpServletRequest req, HttpServletResponse res)
Process Put request. Called in response to HTTP request to store a file
on the server.

void doTrace(HttpServletRequest req, HttpServletResponse res)
Used for debugging. It returns an HTML page containing the header
information sent by the client.
Following are some of the methods of interface HTTPServletResponse
 void addCookie(Cookie cookie)
Sends a new cookie to the client.
 void addHeader(java.lang.String name, java.lang.String value)
Adds a header.
 void setStatus(int sc)
Sets the HTTP status.
 void setHeader(java.lang.String name, java.lang.String value)
Sets a header.
 void sendRedirect(java.lang.String location)
Redirects the client to another page.
 PrintWriter getWriter()
Returns a PrintWriter with the proper character encoding for writing
data to the client.
 void setContentType(java.lang.String type)
Sets the response content type.
Some of the methods of interface HTTPServletRequest are listed below:
 String getAuthType()
2
Gets the authentication type.
 Cookie [] getCookies()
Returns an array of all cookies sent by the client.
 String getHeader(java.lang.String name)
Returns the first value for the requested header.
 Enumeration getHeaderNames()
Returns an enumeration of all the headers sent by the client.
 Enumeration getHeader(java.lang.String name)
Returns all the values of the requested header.
 String getMethod()
Returns the HTTP method used by the client.
 String getQueryString()
Returns the request query string.
 String getRequestedSessionId()
Returns the session id.
 HttpSession getSession()
Returns the current session. Create one if necessary.
 HttpSession getSession(boolean create)
Returns a session.
 String getParameter(java.lang.String name)
Returns a form’s parameter.
 Enumeration getParameterNames()
Returns an enumeration of all the form parameter names.
 String [] getParameterValues()
Returns all the values of the form parameters.
 void SetAttribute(java.lang.String name, java.lang.Object o)
Sets an attribute value.
 void removeAttribute(java.lang.String uri)
Removes an attribute.
 RequestDispatcher getRequestDispatcher(java.lang.String uri)
Returns a request dispatcher for forwarding.
The servlet context is the environment where the servlet runs. It is created
by the servlet container to access information about the servlet
environment. We can bind objects into the Servlet context, which make
them accessible by all servlets in the same web application. There is one
servlet context object per a web application. It enables us to set and get
application level data among all parts of the application.
To get the servlet Context, call the method getServletContext(). Once we
have a ServletContext object, we can call any method in the
ServletContext interface. The most important methods are:
getAttribute and setAttribute, and removeAttribute.
3
Reading Data in Servlet Sent by HTML form :
In Java Servlet all the form element that send a request to the servlet is handled
automatically, We can use getParameter method of HttpServletRequest class
to get the data that a certain HTML field has by passing field name-case
sensitive as parameter to this function.
For example assume we have two HTML text fields named UserName and
UserPassword. To get the data contained In these field in the servlet we use:
String name;
String password;
name=request.getParameter(“UserName”);
password=request.getParameter(“UserPassword”);
Assuming that the HttpServletRequest object named request in my Servlet.
We can get all the parameter names by using getParameterNames method of
HttpServletRequest, this method return an enumeration that contain the
parameter names in an unspecified order. We have to import java.util.* and
since nextElement returns an Object we have to cast it back to String type.
Reading HttpRequest headers from a Servlets:
getHeader method of HttpServletRequest returns a String if the specific header
was presented and null if not.
Also there are some other method that read some common headers like:
getCookies, getMethod, getProtocol, getRequestURI, and some others (refer
to java documentation for full details ).
Generating the server response:
The server response consist of status line, some response headers , a blank line
and the document for example:
HTTP/1.1 200 OK
Content-Type: text/html
<html>
<head>
<title> example of HTML
</title>
</head>
<body>
4
</body>
This is my page
</html>
In most cases all the headers are optional except for Contet-Type. Servlets can
perform many tasks like forward the user to another site, indicate the type of the
document and so on by manipulating the status line.
To set the status code we use setStatus method of HttpServletResponse.
We can use another method named setHeader to set the location of the new
redirected page.
The status code falls into the following categories:
100-199 informational- user should respond with some action
200-299 request was successful
300-399 indicate that file has moved and requires Location header
indicating the new address
400-499 error by client
500-599 error by the server
Invoking Other Web Resource
Web components can invoke other web resources while they execute. This
can be done using two techniques. The first is by including the content of
another resource. The second is by forwarding a request to another
resource. Both techniques require obtaining a RequestDispacher object.
For example assume that we want to invoke another servlet called
myServlet. Then we need to call getRequestDispatcher method of the
ServletContent as shown below:
String adr="/myServlet";
RequestDispatcher dispatcher
=getServletContext().getRequestDispatcher(adr);
After that we can either include the content of myServlet servlet :
dispatcher.include(req,res);
Or we can forward the request to myServlet servler :
dispatcher.forward(req,res);
Installing Java-based web server:
5
To run a servlet you need a Java based web server. Many web servers are
available for free to download including Resin and Tomcat:
 Resin Web server:
You can get Resin- Enterprise Edition from http://www.caucho.com .The
file name of this server is in the format resin-ee-x.x.x.zip. This server
supports many technologies including JSP ,Servlets , Javabeans, Enterprise
Javabeans , and XML.
After you download and unzip this web server, you can run it by executing the
file:
resin-x.x.x\bin\httpd
One thing to mention here is that each server has its own configuration. To
change the configuration of Resin, you need to edit the file conf/resin.conf .If
you choose another web server for your development; you need to consult the
documentation of this server.
HTML and JSP files should be stored in the folder resin-x.x.x\doc . To invoke
an HTML file called file.html, type the following in the browser URL:
http://localhost:8080/file.html
If you want to call a JSP file called file.jsp stored in the doc folder, you have to
type the following in the browser URL:
http://localhost:8080/file.jsp
Where localhost is server’s hostname and 8080 is the port that this server is
listening to.
To develop servlets on Resin, the .java files can be saved in the folder resinx.x.x\doc\WEB-INF\classes.
Then the action attribute of the form should be:
http://localhost:8080/servlet/servletfile
Where servletfile is the java class name (no extension is required).
 Tomcat Web Server:
Another Java based web server is called Tomcat. You can download it from
http://www.apache.org. Chapter 9 of the textbook explains in detail how to use
this server to develop servlets.
6

Deploying you web application:
Instead of putting all you classes and files in doc folder and its subfolders, we
can deploy them as separate web applications under the webapps folder. The
path of this folder under Resin is resin-x.x.x\webapps. To deploy an application,
a certain procedure must be followed. This procedure applies to both Resin and
tomcat web servers:

Create a folder called cpan423 under webapps folder.
Any HTML or JSP file should be stored in cpan423 folder.
 Under cpan423 folder create a folder called WEB-INF. WEB-INF contain
the web application deployment descriptor file (web.xml). This file
o Under WEB-INF create the following folders:
 classes: contains the servlets classes and any other
supporting classes. All the examples in this lecture will be
deployed together in this folder.
 lib: Contain any JAR file used in the web application. JARs
can contain servlets and other supporting classes.
The resulting structure should look as follow:
webapps
Cpan423
WEB-INF
classes
lib
The web descriptor file specifies the configuration for the web application.
Following are the descriptor elements that must be included for each new servlet:
Element
Description
Servlet
Defines a servlet alias for later
mapping using <servlet-mapping>. This
element should have servlet-name,
servlet-class, init-param, load-onstartup and run-at as child elements.
servlet-name
The servlet's name (alias)
servlet-class
Specifies The class full name of the
servlet
init-param
Initialize a parameter.
load-on-startup
Initialize the servlet when the server
starts.
run- at
Times
to
execute
the
servlet
7
servlet-mapping
servlet-name
url-pattern
automatically (Resin Extension).
Specify the URLs that invoke a servlet.
This element should have servletname and url-pattern as child
elements.
Name of the servlet.
Matches a set of URLs for servlet
mapping.
IN the following web.xml file, we will configure Hello servlet, from Ex 1:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>HelloEx</servlet-name>
<servlet-class>Hello</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /Hello</url-pattern>
<servlet-name>HelloEx</servlet-name>
</servlet-mapping>
</web-app>
You need to add servlet/ servlet-mapping entry for each servlet you add to your
application.
Based on the above structure, if my servlet is called demo.java, then the action
in the HTML form would be: http://localhost:8080/cpan423/demo
If my HTML page is called demo.html, then I can invoke it from the browser by
typing the following URL:
http://localhost:8080/cpan423/demo.html
Notice that you can deploy each servlet independently by providing separate
subfolder foe each under webapps folder. To do that, repeat the deployment
steps mentioned above for each providing that you have to give each servlet
different subfolder name.
Examples:
Ex1: servlet example
8
In this example we will write Hello World Servlet, we will call it from the
browser URL as we are using doGet method in the servlet.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Hello extends HttpServlet
{
/*
Handle HTTP get request
*/
public void doGet (HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException
{
/*
Identify the content type to the browser
*/
res.setContentType("text/html");
/*
Obtain PrintWriter object to send response to the client
*/
PrintWriter out = res.getWriter();
out.println("<html><title>Servlet Example</title>");
out.println("<body>Hello World</body>");
out.println("</html>");
}
}
The servlet file (Hello.java) should be saved in the folder:
resin-x.x.x\webapps\cpan423\WEB-INF\lasses
Remember that you need to configure the servlet in your web.xml by
adding servlet/servlet-mapping entry as shown below:
<servlet>
<servlet-name>HelloEx</servlet-name>
<servlet-class>Hello</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /Hello</url-pattern>
9
<servlet-name>HelloEx</servlet-name>
</servlet-mapping>
To invoke this servlet from the deployment folder, type the following URL:
http://localhost:8080/cpan423/Hello
Example 2: servlet example
In this example, we will build a servlet to which we will pass username and
password from an HTML form. The form that we will use is called
demo.html and has the following content:
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Servlet call example</title>
</head>
<body>
<form method="post" action="http://localhost:8080/cpan423/demo">
<p>User name:<input type="text" name="uname" size="20" /></p>
<p>password:<input type="password" name="password"
size="20" /></p>
<p><input type="submit" value="Submit" name="B1" /><input
type="reset" value="Reset" name="B2" /></p>
</form>
</body>
</html>
Then the servlet that will respond to the form request is called demo.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
10
public class demo extends HttpServlet
{
/*
This servlet will handle both HTTP requests POST and GET.
The work will be done in a user defined method called doTheWork
*/
public void doGet (HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException
{
/*
Identify the content type to the browser
*/
res.setContentType("text/html");
/*
Obtain PrintWriter object to send response to the client
*/
PrintWriter out = res.getWriter();
doTheWork(req,out,"Get");
}
public void doPost (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
/*
Identify the content type to the browser
*/
res.setContentType("text/html");
/*
Obtain PrintWriter object to send response to the client
*/
PrintWriter out = res.getWriter();
doTheWork(req,out,"Post");
}
11
public void doTheWork(HttpServletRequest req,PrintWriter out,String
method)
{
String username=req.getParameter("uname");
String password=req.getParameter("password");
out.println("<html><title>Servlets </title><body>");
out.println("The respond for <b> "+method +" </b> method
was :<br />");
out.println("Your name was:<b>"+username+ " </b>and
password was: <b>"+password+"</b>");
out.println("</body></html>");
out.close();
}
}
In the servlet we are just prompting the user with the method used to
transfer the data, the username and password.
The servlet class has been developed to handle both kinds of requests
(GET and POST) as both methods doPost and doGet, pass their data to a
user-defined method called doTheWork. So if you change the method
from post to get in demo.html, you should receive a similar result.
The servlet file (demo.java) should be saved in the folder:
resin-x.x.x\webapps\cpan423\WEB-INF\lasses and the demo.html should be
saved in the folder: resin-x.x.x\webapps\Cpan423. The following configuration
should be added to the web.xml file:
<servlet>
<servlet-name>demoEx</servlet-name>
<servlet-class>demo</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /demo</url-pattern>
<servlet-name>demoEx</servlet-name>
</servlet-mapping>
The demo servlet is invoked from demo.html. To open demo.html in the
browser, type the following URL:
http://localhost:8080/cpan423/demo.html
12
Ex3: Reading data in a servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class EnumParameter extends HttpServlet
{
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html><head><title> using Enumeration in
Servlets</title></head><body>");
/*
Get an enumeration of the form parameters' names
*/
Enumeration param=req.getParameterNames();
/*
Loop thruogh the enumeration to print the parameters sent by the form
*/
while(param.hasMoreElements())
{
String paramName=(String)param.nextElement();
String paramValue[]=req.getParameterValues(paramName);
out.println(paramName);
for(int i=0;i<paramValue.length;i++)
{
out.println(paramValue[i]);
}
out.println("<br/>");
}
out.println("</body></html>");
}
}
Then we can use an HTML form called Enumparam.html that has the following
content:
13
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Using Enumeration to get Form data</title>
</head>
<body>
<p>Welcome to Java Servlets, please login to receive the Servlet
response.</p>
<form action="http://localhost:8080/cpan423/EnumParameter"
method="post">
<table border="0" width="32%">
<tr>
<td width="12%">Name:</td>
<td width="88%"><input type="text" name="uname" size="20"></td>
</tr>
<tr>
<td width="12%">Password</td>
<td width="88%"><input type="password" name="password"
size="20"></td>
</tr>
<tr>
<td width="12%">Hobbies</td>
<td width="88%"><input type="checkbox" name="Hobbies"
value="sport">Sport
<p><input type="checkbox" name="Hobbies"
value="music">Music</p>
<p><input type="checkbox" name="Hobbies"
value="Games">Games</p>
<p><input type="checkbox" name="Hobbies"
value="Books">Books</p>
<p>&nbsp;</p>
<p>&nbsp;</td>
</tr>
</table>
<table border="0" width="28%">
<tr>
<td width="16%"><input type="submit" value="Login"
name="login"></td>
<td width="84%"><input type="reset" value="Reset" name="reset"></td>
</tr>
</form>
</table>
</body>
</html>
14
The servlet file (EnumParametere.java) should be saved in the folder:
resin-x.x.x\webapps\cpan423\WEB-INF\lasses and the Enumparam.html
should be saved in the folder: resin-x.x.x\webapps\cpan423. The following
configuration should be added to the web.xml file:
<servlet>
<servlet-name>EnumerationEx</servlet-name>
<servlet-class>EnumParameter</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /EnumParameter</url-pattern>
<servlet-name>EnumerationEx</servlet-name>
</servlet-mapping>
The EnumParameter servlet is invoked from Enumparam.html. To open
Enumparam.html in the browser, type the following URL:
http://localhost:8080/cpan423/Enumparam.html
Ex4: Reading header information
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class readingHeaders extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html><head><title> using Enumeration in
Servlets</title></head><body>");
/*
Get all the headers sent by the client
*/
Enumeration headers=req.getHeaderNames();
15
out.println("<table border=1> <tr bgcolor=00ff00><th>Header
Name</th><th>Header Value</th></tr>");
/*
Loop through the headers ahd print them
*/
while(headers.hasMoreElements())
{
String headerName=(String) headers.nextElement();
out.println("<tr><td>"+headerName+"</td><td><b>"+req.getHeader(h
eaderName)+"</b></td><tr>");
}
out.println("</body></html>");
}
}
The servlet file (readingHeaders.java) should be saved in the folder:
resin-x.x.x\webapps\cpan423\WEB-INF\lasses. The following configuration
should be added to the web.xml file:
<servlet>
<servlet-name>readingHeadersEx</servlet-name>
<servlet-class>readingHeaders</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /readingHeaders</url-pattern>
<servlet-name>readingHeadersEx</servlet-name>
</servlet-mapping>
To invoke this servlet from the deployment folder, type the following URL:
http://localhost:8080/cpan423/readingHeaders
Ex5: Redirecting a Servlet to another page
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
16
import java.io.*;
public class redirectServlet extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
// specify that the document was remove permanently
res.setStatus(res.SC_MOVED_PERMANENTLY);
// redirect the server to anothe page
res.setHeader("Location","http://localhost:8080/cpan423/demo.html");
}
}
The servlet file (redirectServlet.java) should be saved in the folder:
resin-x.x.x\webapps\Cpan423\WEB-INF\lasses. The following configuration
should be added to the web.xml file:
<servlet>
<servlet-name>redirectEx</servlet-name>
<servlet-class>redirectServlet</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /redirectServlet</url-pattern>
<servlet-name>redirectEx</servlet-name>
</servlet-mapping>
To invoke this servlet from the deployment folder, type the following URL:
http://localhost:8080/cpan423/redirectServlet
Ex6: connecting to database using Servlet
This example uses a form named db.html to query Customer table. The
user must fill in Customer ID field .The operator must be included , for
example “> 1” or “=1”.
17
dbForm.html:
<html>
<title>DB Servlet</title>
<h1><u>DB Servlet</u></h1>
<br>
<form method=post name=form1
action="http://localhost:8080/cpan423/dbServlet">
Enter the Customer Id: <input type=text name=CustID size=20><br>
<br>
<input type=submit name=submit value="Get Record">
</form>
</html>
The form will be submitted to dbServlet on the server:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.io.*;
import java.sql.*;
public class dbServlet extends HttpServlet
{
Connection con;
public void init() throws ServletException
{
String driver="oracle.jdbc.OracleDriver";
try
{
// load Oracle thin JDBC driver
Class.forName(driver);
//create connection
String url="jdbc:oracle:thin:@munro.humber.ca:1521:msit";
con = DriverManager.getConnection(url,"user","password");
}
catch (Exception e)
{
}
}
public void doPost (HttpServletRequest req, HttpServletResponse res)
18
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
int cnt = 0;
try
{
Statement stmt = con.createStatement();
String sql = "";
out.println("<html>");
out.println("<title>DB Record Retrieval</title>");
out.println("<body>");
out.println("<center>");
out.println("<table widht=90% border=1>");
String CustId = req.getParameter("CustID");
if (!CustId.equals(""))
{
sql ="select id, firstName, lastName from emp where id "+ CustId;
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd=rs.getMetaData();
int col=rsmd.getColumnCount();
while (rs.next())
{
out.println("<tr>");
if (cnt == 0)
{
for(int j=1;j<=col;j++)
out.println("<th align='center'>"
+rsmd.getColumnName(j)+"</th>");
out.println("</tr>");
}
for(int j=1;j<=col;j++)
out.println("<td align='center'>"
+rs.getString(j)+"</td>");
19
out.println("</tr>");
cnt++;
}
if (cnt == 0)
out.println("<tr><td >No Matching Record Found</td></tr>");
out.println("</table></html>");
}
else
out.println("<p>you have not entered anything </p>");
out.println("<p><a href='http://localhost:8080/cpan423/db.html'>Go
back to table selector form</a></p>");
}
catch (Exception e)
{
out.println("Exception" + e );
}
}
public void destroy()
{
try
{
con.close();
}
catch(SQLException sle)
{}
}
}
Notice that you need to use your oracle ID and password in the statement:
con = DriverManager.getConnection(url,"user","password");
To configure the oracle driver under resin, you can place the oracle driver (
classes12.zip file) in the folder: resin-x.x.x\lib. This will enable all of your
application to use this driver. If you want to enable certain application to use this
driver only, then you need to place this driver under WEB-INF\lib folder of the
specified application. You need also to restart Resin for the changes to take
effect.
The servlet file (dbServlet.java) should be saved in the folder:
20
resin-x.x.x\webapps\cpan423\WEB-INF\lasses and the dbForm.html should
be saved in the folder: resin-x.x.x\webapps\cpan423. The following
configuration should be added to the web.xml file:
<servlet>
<servlet-name>dbServlet</servlet-name>
<servlet-class>dbServlet</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /dbServlet</url-pattern>
<servlet-name>dbServlet</servlet-name>
</servlet-mapping>
The dbServlet servlet is invoked from dbForm.html. To open
dbForm.html in the browser, type the following URL:
http://localhost:8080/cpan423/dbForm.html
Ex7: using JNDI configuration to connect to Database from a Servlet
Instead of using the traditional way of connected to a database as shown in Ex6,
we can use JNDI to do that. JNDI provides an application with a global naming
tree designed for storing factory objects and configuration variables.
First we need to add the following configuration section to web.xml (Just before
</web-app>):
<servlet>
<servlet-name>dbServletJNDI</servlet-name>
<servlet-class>dbServletJNDI</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /dbServletJNDI</url-pattern>
<servlet-name>dbServletJNDI</servlet-name>
</servlet-mapping>
<database jndi-name="jdbc/test">
21
<driver type="oracle.jdbc.driver.OracleDriver">
<url>jdbc:oracle:thin:@munro.humber.ca:1521:msit</url>
<user>user</user>
<password>password</password>
</driver>
</database>
Remember to use your user ID/password under oracle.
Following is the source code for dbServletJNDI.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
public class dbServletJNDI extends HttpServlet
{
DataSource ds;
Connection con;
public void init() throws ServletException
{
try
{
Context ic =
(Context) new InitialContext();
ds = (DataSource) ic.lookup("java:comp/env/jdbc/test");
}
catch (Exception e)
{
}
}
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();
int cnt = 0;
try
{
22
con = ds.getConnection();
Statement stmt = con.createStatement();
String sql = "";
out.println("<html>");
out.println("<title>DB Record Retrieval</title>");
out.println("<body>");
out.println("<center>");
out.println("<table widht=90% border=1>");
String CustId = req.getParameter("CustID");
if (!CustId.equals(""))
{
sql ="select id, firstName, lastName from emp
where id "+ CustId;
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd=rs.getMetaData();
int col=rsmd.getColumnCount();
while (rs.next())
{
out.println("<tr>");
if (cnt == 0)
{
for(int j=1;j<=col;j++)
out.println("<th align='center'>"
+rsmd.getColumnName(j)+"</th>");
out.println("</tr>");
}
for(int j=1;j<=col;j++)
out.println("<td align='center'>"
+rs.getString(j)+"</td>");
out.println("</tr>");
cnt++;
}
if (cnt == 0)
23
out.println("<tr><td >No Matching Record Found</td></tr>");
out.println("</table></html>");
}
else
out.println("<p>you have not entered anything </p>");
out.println("<p><a
href='http://localhost:8080/cpan423/dbJNDI.html'>Go back to table selector
form</a></p>");
}
catch (Exception e)
{
out.println("Exception" + e );
}
}
public void destroy()
{
try
{
con.close();
}
catch(SQLException sle)
{}
}
}
And here is an HTML file called dbJNDI.html to invoke this servlet:
<html>
<title>DB Servlet</title>
<h1><u>DB Servlet</u></h1>
<br>
<form method=post name=form1
action="http://localhost:8080/cpan423/dbServletJNDI">
Enter the Customer Id: <input type=text name=CustID size=20><br>
<br>
<input type=submit name=submit value="Get Record">
</form>
</html>
Ex8: Invoking other Servlet
24
In this example we will see how we can include the content of another servlet
while our servlet execute. Our servlet is called demoWithInclude.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class demoWithInclude extends HttpServlet
{
public void doPost (HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException
{
/*
Identify the content type to the browser
*/
res.setContentType("text/html");
/*
Obtain PrintWriter object to send response to the client
*/
PrintWriter out = res.getWriter();
String username=req.getParameter("uname");
String password=req.getParameter("password");
out.println("<html><title>Servlets </title><body>");
out.println("The respond for <b> Post </b> method was :<br />");
out.println("Your name was:<b>"+username+ " </b>and
password was: <b>"+password+"</b>");
/*
Obtain a RequestDispatcher by calling getRequestDispatcher method of
ServletContext, supplying a URL relative to the
servlet root.
*/
String adr="/Footer";
RequestDispatcher
dispatcher=getServletContext().getRequestDispatcher(adr);
// we use include method to include the content of another servlet
dispatcher.include(req,res);
out.println("</body></html>");
}
}
Footer Servlet has the following content:
import javax.servlet.*;
import javax.servlet.http.*;
25
import java.io.*;
public class Footer extends HttpServlet
{
/*
Since demoWithInclude Handles HTTP post request, Footer has to handle
the same request method
*/
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
/*
Identify the content type to the browser
*/
res.setContentType("text/html");
/*
Obtain PrintWriter object to send response to the client
*/
PrintWriter out = res.getWriter();
out.println("<h6 align='right'> Humber College </h6>");
out.println("<h6 align='right'> School of Information Technology
</h6>");
out.println("<h6 align='right'> Computer Programming
Department</h6>");
}
}
And following is an HTML file called demowithInclude.html used to invoke
demoWithInclude Servlet
<html>
<title>Test Servlet</title>
<h1><u>Test Servlet</u></h1>
<form method=post name=form2
action="http://127.0.0.1:8080/cpan423/demoWithInclude">
Enter your name: <input type=text name=uname size=20><br>
Enter your password: <input type=password name=password size=20><br>
<input type=submit name=submit value="Submit to Servlet">
</form>
</html>
The servlet files should be saved in the folder resinx.x.x\webapps\cpan423\WEB-INF\lasses and the HTML file should be saved
26
in the folder: resin-x.x.x\webapps\cpan423. The following configuration should
be added to the web.xml file:
<servlet>
<servlet-name>footer</servlet-name>
<servlet-class>Footer</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern>/footer</url-pattern>
<servlet-name>footer</servlet-name>
</servlet-mapping>
<servlet>
<servlet-name>demoWithInclude</servlet-name>
<servlet-class>demoWithInclude</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /demoWithInclude</url-pattern>
<servlet-name>demoWithInclude</servlet-name>
</servlet-mapping>
Note:

After you configure all the examples in this lecture, your web.xml should
look as follows:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>demoEx</servlet-name>
<servlet-class>demo</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /demo</url-pattern>
<servlet-name>demoEx</servlet-name>
</servlet-mapping>
27
<servlet>
<servlet-name>HelloEx</servlet-name>
<servlet-class>Hello</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /Hello</url-pattern>
<servlet-name>HelloEx</servlet-name>
</servlet-mapping>
<servlet>
<servlet-name>EnumerationEx</servlet-name>
<servlet-class>EnumParameter</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /EnumParameter</url-pattern>
<servlet-name>EnumerationEx</servlet-name>
</servlet-mapping>
<servlet>
<servlet-name>readingHeadersEx</servlet-name>
<servlet-class>readingHeaders</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /readingHeaders</url-pattern>
<servlet-name>readingHeadersEx</servlet-name>
</servlet-mapping>
<servlet>
<servlet-name>redirectEx</servlet-name>
<servlet-class>redirectServlet</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /redirectServlet</url-pattern>
<servlet-name>redirectEx</servlet-name>
</servlet-mapping>
<servlet>
<servlet-name>dbServlet</servlet-name>
28
<servlet-class>dbServlet</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /dbServlet</url-pattern>
<servlet-name>dbServlet</servlet-name>
</servlet-mapping>
<servlet>
<servlet-name>dbServletJNDI</servlet-name>
<servlet-class>dbServletJNDI</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /dbServletJNDI</url-pattern>
<servlet-name>dbServletJNDI</servlet-name>
</servlet-mapping>
<database jndi-name="jdbc/test">
<driver type="oracle.jdbc.driver.OracleDriver">
<url>jdbc:oracle:thin:@sunserv1.humberc.on.ca:1521:orcl</url>
<user>user</user>
<password>password</password>
</driver>
</database>
</web-app>

If you want to distribute a web application, you can package it into a Web
Application Archive (WAR). Following is a batch file called
createWAR.bat that can be used to create WAR file for our examples in
this lecture. This file must be stored under cpan423 folder:
set path=%path%;C:\j2sdk_nb\j2sdk1.4.2\bin
jar cvf cpan423.war .
Following is a description of each option:
c : create a new archive file (war file).
v: generate verbose output on the standard output
f: specifiy the archive file name. In this case it is cpan423.war
29
The dot (.) at the end of the command instructs the jar command to package
all the files in the current directory.
Once you have the war file, you can copy it to the webapps folder of your
server. Resin will unpack it for you the next time it runs.
30