Server Side Development:
Servlets
1 of 84
Server Side Development
Outline
Container Architecture
Web Components
Servlets and Servlet Applications
Servlet API
Javax.servlet
Javax.servlet.http
Deploying an Application
2 of 84
Server Side Development
Web Server
A web server is a program running on the server that listens
for incoming requests and services those requests as they
come in.
Once the web server receives a request, depending on the
type of request the web server might look for a web page, or
it might execute a program on the server.
It will always return some kind of results to the web browser,
even if its simply an error message saying that it couldnt
process the request.
By default the role of a web server is to serve static pages
using the http protocol
Web servers can be made dynamic by adding additional
processing capability to the server
3 of 84
Server Side Development
Server Extensions
Several different tools are available for extending the
server capabilities
Java enterprise architecture
VB .Net architecture
Active Server Pages (ASP)
CGI-Perl scripting
These tools process incoming requests from the user
and generate custom html pages
4 of 84
Server Side Development
Tomcat
Tomcat is a stand alone web server and a servlet container
It is written in Java
It is open source and free for usage
You do not have to be a Java programmer to use it
Its web server is not as fully featured as others like Apache
Installing Tomcat
Make sure that jdk1.4 (or higher) is installed on your machine
Download the latest windows version of Tomcat
Run the installer by double clicking on the download
The installer checks if JRE and JDK are available for Tomcat
Accept the license agreement
Installation directory: c:\Program Files\Apache Tomcat 4.0
On installation you get a message Completed
5 of 84
Tomcat
Tomcat is the Servlet Engine than handles servlet
requests for Apache
Tomcat is a helper application for Apache
Its best to think of Tomcat as a servlet container
Apache can handle many types of web services
Apache can be installed without Tomcat
Tomcat can be installed without Apache
Its easier to install Tomcat standalone than as part
of Apache
By itself, Tomcat can handle web pages, servlets, and JSP
6 of 84
HTTP
7 of 84
HTTP
Application Layer Protocol
User applications implement this protocol
Different applications use different protocols
Other protocols implemented by the OS.
Web Servers/Browsers use HTTP
File Transfer Utilities use FTP
Electronic Mail applications use SMTP
Naming Servers use DNS
Interacts with transport layer to send messages
8 of 84
HTTP
Application Layer Protocol, contd.
Socket
Socket
TCP/UDP
with
Buffers
and
Variables
Process
Controlled by
Application
Developer
Internet
Controlled by
Operating
System
HOST
TCP/UDP
with
Buffers
and
Variables
Process
Controlled by
Operating
System
Controlled by
Application
Developer
HOST
Two parameter required for identifying the receiving process
Host machine identifier - IP Address
Host machine process identifier - Port
(localhost or ip-address)
(80 or 8080 for web server)
9 of 84
HTTP
HyperText Transfer Protocol
Lightweight protocol for the web involving a single request
& response for communication
Provides 8 methods
Get: Used to request data from server
(By convention get will not change data on server)
Post: Used to post data to the server
Head: returns just the HTTP headers for a resource.
Put: allows you to "put" (upload) a resource (file) on to a webserver
so that it be found under a specified URI.
Delete: allows you to delete a resource (file).
Connect:
Options: To determine the type of requests server will handle
Trace: Debugging
10 of 84
HTTP
GET and POST
GET and POST allow information to be sent back to the web server
from a browser
Choosing GET as the "method" will append all of the data to the URL
and it will show up in the URL bar of your browser.
e.g. when you click on the submit button of a form the data in the form
is send back to the server, as "name=value" pairs.
The amount of information you can send back using a GET is restricted
as URLs can only be 1024 characters.
A POST sends the information through a socket back to the webserver
and it won't show up in the URL bar.
This allows a lot more information to be sent to the server
The data sent back is not restricted to textual data and it is possible to
send files and binary data such as serialized Java objects.
11 of 84
HTTP
HTTP Headers
Contains information about client and the request
Four categories of header information
General Information: Date, caching information, warnings etc.
Entity Information: Body of the request or response e.g. MIME type,
length etc.
Request Information: Information about client e.g. cookies, types of
acceptable responses etc.
Response Information: Information about server e.g. cookies,
authentication information etc.
General & Entity information used for both client & server
Request information included by client
Response information included by server
12 of 84
HTTP
Protocol
HTTP is a stateless protocol
Request/Response occurs across a single network connection
At the end of the exchange the connection is closed
This is required to make the server more scalable
Web Sites maintain persistent authentication so user does not have
to authenticate repeatedly
While using HTTP persistent authentication is maintained using a
token exchange mechanism
HTTP 1.1 has a special feature (keep-alive) which allows clients to
use same connection over multiple requests
Not many servers support this
Requests have to be in quick succession
13 of 84
HTTP
Tracking State
Three types of tracking methods are used:
Cookies: Line of text with ID on the users cookie file
URL Session Tracking: An id is appended to all the links in
the website web pages.
Hidden Form Elements: An ID is hidden in form elements
which are not visible to user
Custom html page allows the state to be tracked
14 of 84
HTTP
HTTP Status Codes
When a server responds to a request it provides a status code
Web Container automatically handles setting of status codes
Five categories of status codes
Informational
Success
Redirection
Client error
Server error
Common Status Codes
200 Request was processed normally
401 Unauthorized access
403 Forbidden
404 Requested resource not found on server
405 Method Not allowed
500 Internal server error
15 of 84
Servlets
16 of 84
Servlets
Introduction
Classes that dynamically process requests and construct responses
In an application processing of each request will normally be done
by a different servlet.
Dynamically generate html pages in response to requests
May also send data in other forms like XML or serialized Java objects
Run in a servlet container and have access to services that the
container provides
e.g. search catalog, check out, confirm order etc.
Client of the servlet can be any of the following
Browser
Applet
Java Application
17 of 84
J2EE Architecture
J2EE Container Architecture
Application is considered as a collection of related yet
independent components
Container acts as an execution environment for the
components
Container Provides services to the components
J2EE Container
J2EE
Component
J2EE
J2EE
J2EE
Component
Component
Component
Component 2
J2EE Component
Component Code
& Resources
18 of 84
Servlets
Servlet Lifecycle
Calling the
init method
Initialization
and Loading
Servlet Class
Servicing requests by
calling the
service method
Destroying the servlet
by calling the
destroy method
Garbage
Collection
19 of 84
Servlet Life Cycle
The servlet class is loaded by the container during start-up.
The container calls the init( ) method.
initializes the servlet and must be called before the servlet
can service any requests.
called only once.
Servlet processes each request in its own separate thread.
The container calls the service( ) method of the servlet for
every request.
determines the kind of request being made and dispatches
it to an appropriate method to handle the request.
Finally, the container calls the destroy( ) method that takes
the servlet out of service.
The destroy( ) method like init( ) is called only once in the
lifecycle of a servlet.
20 of 84
Servlets
Servlet Communication
Servlets can work with any protocol.
Servlet can communicate with four different entities
Client during request/response cycle
With servlet container to get context/config information
With other resources on server e.g. servlets, EJBs
With external resources like databases, legacy systems.
Client communication can be in many forms
In Http communication
Request Information parameters (as name value pairs)
Response
HTML (Browsers)
WML (Mobile Devices)
21 of 84
Advantages of Servlet over CGI
Efficient single servlet multiple thread
Convenient Familiar, HTTP specific
Powerful talks directly to web server, share data
with other servlets, database connection, session
tracking
Portable supported directly or via a plugin on
almost every major Web server
Inexpensive - free or very inexpensive Web servers
available
Cross Platform
22 of 84
What can Servlets Do?
Dynamically build and return an HTML file based on the nature of the
client request.
Process user input passed by an HTML form and return an appropriate
response.
Provide user authentication and other security mechanism.
Interact with server resources such as databases, other applications and
network files to return useful information to the client
Process input from many clients for interaction among peers for
applications such as Multiplayer Games.
Allow the server to communicate with a client applet via a custom protocol
and keep the connection open throughout the conversation.
Forward requests from one server to another for load balancing purposes.
Partition a single logical service across servers or between servlets in order
to most efficiently process the task.
Virtually any other way you can imagine to enhance or extend a server.
23 of 84
Servlets API
24 of 84
Servlets
Servlet API
Contained in two packages
javax.servlet
javax.servlet.Http
Contains 20 interfaces and 16 classes
Prevalence of interfaces allows servlet implementation to be
customized to container
25 of 84
Servlets
JAVA Servlets
Javax.servlet package can be extended for use with any
application layer protocol
http is the most popularly used protocol
Javax.servlet.http package is extension of the javax.servlet
package for http protocol
The Servlet spec allows you to implement separate Java methods
implementing each HTTP method in your subclass of HttpServlet.
Override the doGet() and/or doPost() method to provide normal servlet
functionality.
Override doPut() or doDelete() if you want to implement these methods.
There's no need to override doOptions() or doTrace().
The superclass handles the HEAD method all on its own.
26 of 84
Servlets
Generic Servlet Class
GenericServlet is abstract class that implements servlet interface
Requires implementing the service() method
Servlets normally extend from this class
Methods
LifeCycle Methods
init()
service()
destroy()
Environment Methods
getServletContext()
getInitParameter()
getInitParameterNames()
Utility Methods
log()
27 of 84
Servlets
javax.servlet.http
Javax.servlet package provides interfaces and classes to service
client requests in protocol independent manner.
Javax.servlet.http package supports http-specific functions.
Several of the classes are derived from the javax.servlet packaage
Some methods from the javax.servlet package are also used
Contains
8 interfaces
7 classes
28 of 84
Servlet Package
javax.servlet
The Servlet interface defines methods that
manage servlets and their communication
with clients
Client Interaction: when it accepts call,
receives two objects that implements
ServletRequest
ServletResponse
29 of 84
Architecture
Servlet
Generic Servlet
HttpServlet
YourOwnServlet
30 of 84
Servlets
Classes and Interfaces
Interfaces
Classes
HttpSession
HttpServletRequest
HttpServletResponse
HttpSessionAttributeListener
HttpSessionActivationListener
HttpSessionBindingListener
HttpSessionContext
HttpSessionListener
Cookie
HttpServlet
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionBindingEvent
HttpSessionEvent
HttpUtils
31 of 84
Servlets
HttpServlet Class
Extends the Generic Servlet
Service() method
Inherits the init() and destroy methods()
Overrides the service() method
Signature: Protected void service(HttpServletRequest req,
HttpServletResponse res)
Forwards the request to the appropriate method
Developer should not normally override this method
The developer needs to implement the methods
corresponding to the request
doGet(), doPost(), doHead(), doPut()
32 of 84
HTTP Methods
POST:
Data sent in two steps
Designed for Posting information
Browser contacts server
Sends data
GET:
Contacts server and sends data in single step
Appends data to action URL separated by question mark
Designed to get information
33 of 84
doGet(HttpServletRequest, HttpServletResponse)
information entered by the user is appended
to the URL and displayed in plain text by the
browser.
this method will accepts only 255 characters.
34 of 84
doPost(HttpServletRequest,HttpServletResponse)
pass the body of the request.
not visible in the URL.
No Limit of amount of information.
generated by the browser in response to the
user clicking the submit button on an HTML
form.
35 of 84
Other Methods
HEAD: Client sees only header of response to
determine size, etc
PUT: Place documents directly on server
DELETE: Opposite of PUT
TRACE: Debugging aid returns to client
contents of its request
OPTIONS: what options available on server
36 of 84
HTTP requests
When a request is submitted from a Web page, it is
almost always a GET or a POST request
The HTTP <form> tag has an attribute action,
whose value can be "get" or "post"
The "get" action results in the form information
being put after a ? in the URL
Example:
http://www.google.com/search?hl=en&ie=UTF8&oe=UTF-8&q=servlets
The & separates the various parameters
Only a limited amount of information can be sent this
way
"put" can send large amounts of information
37 of 84
Important servlet methods
The service method dispatches the following kinds
of requests: DELETE, GET, HEAD, OPTIONS,
POST, PUT, and TRACE
A GET request is dispatched to the
doGet(HttpServletRequest request,
HttpServletResponse response) method
A POST request is dispatched to the
doPost(HttpServletRequest request,
HttpServletResponse response) method
These are the two methods you will usually override
doGet and doPost typically do the same thing, so usually
you do the real work in one, and have the other just call it
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
doPost(request, response);
}
38 of 84
Using the HttpServletResponse
The second parameter to doGet (or doPost) is
HttpServletResponse response
Everything sent via the Web has a MIME type
The first thing we must do with response is set the
MIME type of our reply:
response.setContentType("text/html");
This tells the client to interpret the page as HTML
Because we will be outputting character data, we
need a PrintWriter, handily provided for us by the
getWriter method of response:
PrintWriter out = response.getWriter();
Now were ready to create the actual page to be
returned
39 of 84
Using the PrintWriter
From here on, its just a matter of using our
PrintWriter, named out, to produce the Web
page.
Then use the println method of out one or
more times
out.println(docType +
"<HTML>\n" +
"<HEAD> ...
</BODY></HTML>");
And were done!
40 of 84
Input to a servlet
A GET request supplies parameters in the form
URL ? name=value & name=value & name=value
(Illegal spaces added to make it more legible)
Actual spaces in the parameter values are encoded by +
signs
Other special characters are encoded in hex; for example,
an ampersand is represented by %26
Parameter names can occur more than once, with
different values
A POST request supplies parameters in the same
syntax, only it is in the body section of the request
and is therefore harder for the user to see
41 of 84
Getting the parameters
Input parameters are retrieved via messages to the
HttpServletRequest object request
Most of the interesting methods are inherited from the
superinterface ServletRequest
public Enumeration getParameterNames()
Returns an Enumeration of the parameter names
If no parameters, returns an empty Enumeration
public String getParameter(String name)
Returns the value of the parameter name as a String
If the parameter doesnt exist, returns null
If name has multiple values, only the first is returned
public String[] getParameterValues(name)
Returns an array of values of the parameter name
If the parameter doesnt exist, returns null
42 of 84
Servlets
HttpServletRequest Interface
Extends ServletRequest
Inherited methods from ServletRequest
getParameterNames()
getParameter(String name)
getParameterValues(String name)
getServerName()
getServerPort()
getRequestDispatcher
New methods defined
getCookies()
getHeader()
getPathInfo()
getContextPath()
getQueryString()
43 of 84
Servlets
HttpServletRequest Interface, contd.
Extends ServletResponse
Inherited methods from ServletResponse
New methods
getoutputStream()
getWriter(String name)
flushBuffer()
setContentType()
encodeURL(String url)
encodeRedirectURL(String url)
setDateHeader()
setStatus()
44 of 84
Servlets
Writing a Servlet
Create a servletclass
extend HttpServlet
Implement the doGet() or doPost() method
Both methods accept two parameters
Obtain parameters from HttpServletRequest Interface using
HttpServletRequest
HttpServletResponse
getParameter(String name)
Obtain the writer from the response object
Process input data and generate output (in html form) and
write to the writer
Close the writer
45 of 84
Compiling
javac classpath
$LIB/servlet-api.jar
Hellox.java
46 of 84
Directory Structure
Create your
web applications
here
Create a directory
D for your
web application
Create WEB-INF
under D
Create classes
under WEB-INF
47 of 84
Directory Structure (cont.)
Static content in D
Dynamic content
in WEB-INF
web.xml in WEB-INF
Servlets in classes
48 of 84
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<description>Examples</description>
<display-name>Examples</display-name>
<servlet> Declares servlet
<servlet-name>Hellox</servlet-name> abbreviation
<servlet-class>Hellox</servlet-class>
fully qualified (e.g., java.lang.String)
</servlet>
Maps servlet to URL (rooted at
<servlet-mapping>
<servlet-name>Hellox</servlet-name>
<url-pattern>/Hellox</url-pattern>
</servlet-mapping> </web-app>
49 of 84
D)
Example 1
50 of 84
Example 1
Login Servlet
package edu.albany.mis.goel.servlets;
import javax.servlet.http.*;
import java.io.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// Get the parameter from the request
String username = request.getParameter("username");
// Send the response back to the user
try {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><body>");
writer.println("Thank you, " + username + ". You are now logged into the system.");
writer.println("</body></html>");
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
51 of 84
Example 1
Login.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
Please enter your username and password
<form action="servlet/edu.albany.mis.goel.servlets.Login" method="POST">
<p><input type="text" name="username" length="40">
<p><input type="password" name="password" length="40">
<p><input type="submit" value="Submit">
</form>
</body>
</html>
52 of 84
Example 1
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Login Servlet</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>edu.albany.mis.goel.servlets.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
</web-app>
53 of 84
Example 1
Login Deployment
Compiling
Commands
Makefile contains all the scripts for compiling and deployment of the
servlet
Needs to be modified for any give application
make shutdown: shuts down the tomcat server
make clean: cleans up the current setup for the application
make all: compiles code, creates war file and deploys war file on server
make startup: starts the server again
Running the servlet
http://localhost:8080/login/login.html
54 of 84
Example 2
55 of 84
Tracking State
56 of 84
Tracking State
Cookies
A Cookie is data (String) that the server passes to the
browser and the browser stores on the server
Set of name value pairs
Web servers place cookies on user machines with id to
track the users
Two types of cookies
Persistent cookies: Stored on hard drive in text format
Non-persistent cookies: Stored in memory and goes away
after you reboot or turn off the machine
57 of 84
Tracking State
Cookie Attributes
Attributes of a cookie
Name: Name of a cookie
Value: Value of the cookie
Comment: Text explaining purpose of cookie
Max-Age: Time in seconds after which the client should not send cookie
back to server
Domain: Domain to which the cookie should be sent
Path: The path to which the cookie should be sent
Secure: Specifies if cookie should be sent via https
Version: Cookie version
(0 original Netscape version of Cookie
1 cookies standardized via RFC 2109)
58 of 84
Tracking State
Cookie Servlet
package edu.albany.mis.goel.servlets;
Cookie[] cookies = request.getCookies();
import java.io.IOException;
Cookie token = null;
import java.io.PrintWriter;
if(cookies != null) {
import java.util.Random;
for(int i = 0; i < cookies.length; i++)
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
if(cookies[i].getName().equals("token"))
{
import javax.servlet.http.HttpServletResponse;
// Found a token cookie
import javax.servlet.http.Cookie;
token = cookies[i];
import javax.servlet.ServletException;
break;
public class CookieServlet extends HttpServlet
}
{
protected void doGet(HttpServletRequest
request,HttpServletResponse response)
throws ServletException, IOException
}
}
{
59 of 84
Tracking State
Cookies (Token)
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><head><title>Tokens</title></head><body ");
writer.println("style=\"font-family:verdana;font-size:10pt\">");
String reset = request.getParameter("reset");
System.out.println("token = " + token);
if (token == null || (reset != null && reset.equals("yes"))) {
Random rand = new Random();
long id = rand.nextLong();
writer.println("<p>Welcome. A new token " + id + " is now established</p>");
// Set the cookie
token = new Cookie("token", Long.toString(id));
token.setComment("Token to identify user");
token.setMaxAge(-1);
token.setPath("/cookie/track");
60 of 84
Tracking State
Cookies, contd.
response.addCookie(token);
} else {
writer.println("Welcome back. Your token is " + token.getValue() +
".</p>"); }
String requestURLSame = request.getRequestURL().toString();
String requestURLNew = request.getRequestURL() + "?reset=yes";
writer.println("<p>Click <a href=" + requestURLSame +
">here</a> again to continue browsing with the same identity.</p>");
writer.println("<p>Otherwise, click <a href=" + requestURLNew +
">here</a> again to start browsing with a new identity.</p>");
writer.println("</body></html>");
writer.close();
}
}
61 of 84
Tracking State
Cookies
package edu.albany.mis.goel.servlets;
response.setContentType("text/html");
import java.io.IOException;
PrintWriter writer = response.getWriter();
import java.io.PrintWriter;
writer.println("<html><head><title>Tokens</title></head><body ");
import java.util.Random;
writer.println("style=\"font-family:verdana;font-size:10pt\">");
import javax.servlet.http.HttpServlet;
String reset = request.getParameter("reset");
import javax.servlet.http.HttpServletRequest;
System.out.println("token = " + token);
import javax.servlet.http.HttpServletResponse;
if (token == null || (reset != null && reset.equals("yes"))) {
import javax.servlet.http.Cookie;
Random rand = new Random();
import javax.servlet.ServletException;
long id = rand.nextLong();
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest
request,HttpServletResponse response)
writer.println("<p>Welcome. A new token " + id + " is now
established</p>");
throws ServletException, IOException {
// Set the cookie
Cookie[] cookies = request.getCookies();
token = new Cookie("token", Long.toString(id));
Cookie token = null;
token.setComment("Token to identify user");
if(cookies != null) {
token.setMaxAge(-1);
for(int i = 0; i < cookies.length; i++) {
token.setPath("/cookie/track");
if(cookies[i].getName().equals("token")) {
}
}
response.addCookie(token);
// Found a token cookie
token = cookies[i];
else {
break;
writer.println("Welcome back. Your token is " + token.getValue() +
".</p>");
}
62 of 84
Tracking State
URL Encoding
http:// www.address.edu:1234/path/subdir/file.ext?query_string
Http allows name value pairs to be passed to the resource
http:// www.test.edu/index.jsp?firstname=sanjay+lastname=goel
The server can place the id of a customer along with the URL
Service http
Host www. Address. edu
Port 1234
/path/subdur/file.ext resource path on the server
query_string additional information that can be passed to resource
http://www.fake.com/ordering/id=928932888329938.823948
This number can be obtained by guessing or looking over some
ones shoulder
Timeout for the sessions may be a few hours
User can masquerade as the owner of the id and transact on the web
63 of 84
Tracking State
URL Rewriting
package edu.albany.mis.goel.servlets;
if (tokenID == null) {
import java.io.IOException;
// Client did not sent any token
import java.io.PrintWriter;
Random rand = new Random();
import java.util.Random;
tokenID = Long.toString(rand.nextLong());
import javax.servlet.http.HttpServlet;
writer.println("<p>Welcome. A new token " + tokenID + " is now
established</p>");
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
else {
import javax.servlet.ServletException;
// Client sent the token back
writer.println("<p>Welcome back. Your token is " + tokenID + ".</p>");
public class TokenServlet extends HttpServlet {
// Prepare links for sending requests back
protected void doGet(HttpServletRequest request,HttpServletResponse
response)
String requestURLSame = request.getRequestURL().toString() +
"?tokenID=" + tokenID;
throws ServletException, IOException {
String requestURLNew = request.getRequestURL().toString();
// Get the token from the request
// Write the response and close
String tokenID = request.getParameter("tokenID");
writer.println("<p>Click <a href=" + requestURLSame +
// Prepare for response
">here</a> again to continue browsing with the same
identity.</p>");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<p>Otherwise, click <a href=" + requestURLNew +
">here</a> again to start browsing with a new
identity.</p>");
writer.println("<html><head><title>Tokens</title></head><body ");
writer.println("style=\"font-family:verdana;font-size:10pt\">");
writer.println("</body></html>");
writer.close();
}
}
64 of 84
Tracking State
Hidden Form Fields
HTML allows creation of hidden fields in the forms
Developers use hidden fields to store information for
their reference
ID can be stored as a hidden form field
<Input Type=Hidden Name=Search Value=key>
<Input Type=Hidden Name=id Value=123429823>
65 of 84
Tracking State
Hidden Form Field
package edu.albany.mis.goel.servlets;
else {
import java.io.IOException;
// Client sent the token back
import java.io.PrintWriter;
writer.println("<p>Welcome back. Your token is " + token + ".</p>");
import java.util.Random;
// Prepare a URL for sending requests back
import javax.servlet.http.HttpServlet;
String requestURL = request.getRequestURL().toString();
import javax.servlet.http.HttpServletRequest;
// Write a form with a hidden field
import javax.servlet.http.HttpServletResponse;
writer.println("<p>");
import javax.servlet.ServletException;
writer.println("<form method='GET' action='" + requestURL + "'>");
public class HiddenFieldServlet extends HttpServlet {
writer.println("<input type='hidden' name='token' value='" + token + "'/>");
protected void doGet(HttpServletRequest
request,HttpServletResponse response)
writer.println("<input type='submit' value='Click Here'/>");
throws ServletException, IOException {
writer.println("</form>");
// Get the token from the request
writer.println(" to continue browsing with the same identity.</p>");
String token = request.getParameter("token");
// Write another form without the hidden field
// Prepare for response
writer.println("<p>");
response.setContentType("text/html");
writer.println("<form method='GET' action='" + requestURL + "'>");
PrintWriter writer = response.getWriter();
writer.println("<input type='submit' value='Click Here'/>");
writer.println("<html><head><title>Tokens</title></head><body ");
writer.println("</form>");
writer.println("style=\"font-family:verdana;font-size:10pt\">");
writer.println(" to start browsing with a new identity.</p>");
if(token == null) {
// Client did not sent any token
writer.println("</body></html>");
Random rand = new Random();
writer.close();
token = Long.toString(rand.nextLong());
writer.println("<p>Welcome. A new token " + token + " is now
established</p>");
66 of 84
Tracking State
HttpSession Interface
Provides methods to establish session between client and server
Session lasts for a specified time
Allows binding of objects over multiple requests
Important Methods
getID()
getAttribute(String name)
getAttriubuteNames()
setAttribute(String name, Object value)
removeAttribute(String name)
inValidate()
67 of 84
Store
MainServlet
/** This is the main servlet of the application which reads the
* products from the product list and presents it to the user for
public class MainServlet extends HttpServlet {
public void init() throws ServletException {
* selecting and addition to the shopping card. The data is read from
// Load the products from XML file provided by init parameter
* an XML file and is added to a hashmap which is added to the
ServletContext context = getServletContext();
* ServletContext for future access.
InputStream productsFile = context.getResourceAsStream((String)
context.getInitParameter("productsFile"));
* Steps:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
* init()
DocumentBuilder db = null;
* 1. Gets the servletcontext
try { db = dbf.newDocumentBuilder();
* 2. Obtains the name of the product file from the context (init param)
} catch (ParserConfigurationException pce) {
throw new ServletException (pce.getMessage());
* 3. Creates a DOM parser
* 4. Parses the product file and creates a document (xml data)
* 5. Adds the product information to a Hashmap called product
Document doc = null;
* 6. Adds the Hashmap to the context.
try { doc = db.parse(productsFile);
} catch (IOException ioe) {
* doGetPost()
throw new ServletException(ioe.getMessage());
* 1. Reads the products from the Hashmap
} catch (SAXException se) {
* 2. Creates web page which contains standard header footer (dispatcher)
throw new ServletException(se.getMessage()); }
* 3. Adds products to the web page and links them to the cartServlet
NodeList productsList = doc.getElementsByTagName("product");
*/
HashMap products = new HashMap();
package edu.albany.mis.goel.store;
Node product;
import java.io.*;
for (int ctr = 0; ctr < productsList.getLength(); ctr ++ ) {
import java.util.*;
product = productsList.item(ctr);
import javax.servlet.*;
NamedNodeMap attribs = product.getAttributes();
import javax.servlet.http.*;
Node attrib = attribs.getNamedItem("name");
String name = attrib.getNodeValue();
// JAXP packages
attrib = attribs.getNamedItem("price");
import javax.xml.parsers.*;
String price = attrib.getNodeValue();
import org.xml.sax.*;
Product p = new Product(ctr,name,price);
products.put(new Integer(ctr),p);
import org.xml.sax.helpers.*;
}
import org.w3c.dom.*;
// Store products in the ServletContext
context.setAttribute("products",products);
}
68 of 84
Store
MainServlet
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetOrPost(req,res);
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetOrPost(req,res);
}
private void doGetOrPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();
// Include standard header
RequestDispatcher dispatcher = req.getRequestDispatcher("/header.html");
dispatcher.include(req,res);
HashMap products = (HashMap) getServletContext().getAttribute("products");
// List the products, clickable to add to cart
Iterator it = products.values().iterator();
out.println("<table>");
while (it.hasNext()) {
out.println("<tr>");
Product product = (Product) it.next();
out.print("<td><a href='Cart?add=true&id=" + product.getId() +"'>");
out.print(product.getName() + "</a></td><td>" + product.getPrice());
out.println("</td>);
out.println("</tr>");
}
out.println("</table>");
// Include standard footer
dispatcher = req.getRequestDispatcher("/footer.html");
dispatcher.include(req,res);
}
}
69 of 84
Store
Cart and Product
package edu.albany.mis.goel.store;
package edu.albany.mis.goel.store;
import java.util.*;
public class Product {
private String name;
public class Cart {
private HashMap items = new HashMap();
private String price;
// Default Cart Constructor
private int id;
public Cart() {
public Product(int id, String name, String price) {
}
// Function to get items from the cart
this.price = price;
public Iterator getItems() {
this.name = name;
this.id=id;
return items.values().iterator();
}
}
public void addItem(Product product) throws ItemAlreadyAddedException {
public String getPrice() {
Integer id = new Integer(product.getId());
return this.price;
if (this.items.containsKey(id)) {
}
throw new ItemAlreadyAddedException();
}
public String getName() {
this.items.put(id, product);
return this.name;
}
public int getId() {
package edu.albany.mis.goel.store;
return this.id;
import javax.servlet.*;
public class ItemAlreadyAddedException extends ServletException {
}
70 of 84
Store
CartServlet
package edu.albany.mis.goel.store;
private void addToCart(HttpServletRequest req, Cart cart, PrintWriter out)
import java.io.*;
throws ItemAlreadyAddedException {
import java.util.*;
// Get the item to add from the request
import javax.servlet.*;
// Get the products from the servletcontext
import javax.servlet.http.*;
HashMap products = (HashMap) getServletContext().getAttribute("products");
public class CartServlet extends HttpServlet {
// Find the one represented by the ID that we passed in
public void doPost(HttpServletRequest req, HttpServletResponse res)
try {
throws ServletException, IOException {
Integer id = new Integer(Integer.parseInt(req.getParameter("id")));
Product p = (Product) products.get(id);
public void doGet(HttpServletRequest req, HttpServletResponse res)
// Add it to the cart
throws ServletException, IOException {
cart.addItem(p);
doGetOrPost(req,res);
// add the cart to the session
req.getSession().setAttribute("cart",cart);
private void doGetOrPost(HttpServletRequest req, HttpServletResponse res)
out.println("<b>Succesfully added product to cart!</b><br>");
throws ServletException, IOException {
} catch (NumberFormatException nfe) {
// Get the cart if it exists
out.println("<b>Can't add product</b><br>");
HttpSession session = req.getSession();
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
private void displayCart(Cart cart, PrintWriter out) {
cart = new Cart();
Iterator items = cart.getItems();
out.println("<h1>Current Cart Contents:</h1>");
// Check to see if we are adding to the cart or we want to dispay the cart
out.println("<table>");
String adding = req.getParameter("add");
while (items.hasNext()) {
PrintWriter out = res.getWriter();
out.println("<tr>");
// Add to it
Product p = (Product)items.next();
if (adding.equalsIgnoreCase("true")) {
out.println("<td>"+p.getName()+"</td>"+"<td>"+p.getPrice() +"</td>");
addToCart(req, cart, out);
out.println("<tr>");
// Display its contents
out.println("</table>");
displayCart(cart, out);
}
}
}
71 of 84
Tracking State
CheckoutServlet
/** Checkout for the customer. This is also the place where the
private void doGetOrPost(HttpServletRequest req, HttpServletResponse res)
* security check should be done to make sure that the customer is a
throws ServletException, IOException {
* registered customer. There are two ways of doing that. Currently
// Get the writer
* security is not implemented
PrintWriter out = res.getWriter();
// include the cart display, and ask to confirm check out.
* 1. Declarative - Relies on the deployment
System.out.println("Dispatching the request");
* 2. Programmatic - Internally codes the security
RequestDispatcher dispatcher = req.getRequestDispatcher("/Cart?add=false");
dispatcher.include(req,res);
* Steps
out.println("<br>Please Click Confirm to check out");
* 1. Prints the contents of the shopping cart
out.println("<form action='confirmed.html'>" +
* 2. Asks the user to confirm his/her selection
"<input type='submit' value='Confirm'></form>");
* 3. Sends the paget to the confirm page.
*/
}
}
package edu.albany.mis.goel.store;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.Principal;
public class CheckOutServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetOrPost(req,res);
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetOrPost(req,res);
}
72 of 84
Application
Deployment
73 of 84
Application Deployment
Structure of Web Application
AppDir/
index.html
main.jsp
images/
Public Resources that are
downloaded directly to the client
without processing
company.jpg
divider.jpg
admin/
admin.jsp
WEB-INF/
Lib files are standard libraries that
the code may need
JSP files are an exception since they
are converted to servlets and not
downloaded directly
web.xml
classes/edu/albany/mis/goel/servlets/
ShoppingCart.class
Catalog.class
Files which the web container
processes but not client
lib/
Lib files are standard libraries that
the code may need
xereces.jar
xalan.jar
ShoppingCart.java
Source Files which are developed
by the user
Catalog.java
edu/albany/mis/goel/servlets/
Package directory reduces chances of
name conflicts
74 of 84
Application Deployment
Deployment of Web Applications
Web applications are deployed in the web applications directory
of the web server
In tomcat this directory is ${Tomcat_Home}/webapps
Two separate ways of deploying web applications
Exploded Directory Format
Development directory is copied to the application directory of the web
server
Used primarily in development mode when changes are frequent
Web Application Archive (WAR) Format
Archived version of development directory is copied to application
directory of web server
Created using jar utility i.e. jar cv0f SimpleWebApp.war .
75 of 84
Application Deployment
Deployment of Web Applications, contd.
If web application is in a location different than the webapps
directory context is defined
Location: ${Tomcat_Home}/conf/server.xml
<context path=/store docBase=/store.war
reloadable=true>
Context declares a context to exist with a base URL path of /store
The application can be accessed at http://localhost:8080/store/.
docBase tells tomcat where to find the web application
Relative path (/store.war) tells Tomcat that store.war is at the top level of
the webapps directory
An absolute path can also be supplied I.e. c:/myapps/store.war
Reloadable set to true indicates that if the class or lib files change the
application detects the change
76 of 84
Session Management
77 of 84
Session Management
Basics
HTTP is a stateless protocol. Each re.quest and
response stand alone
Without session management, each time a client makes
a request to a server, its brand new user with a brand
new request from the servers point of view.
A session refers to the entire interaction between
between a client and a server from the time of the
clients first request, which generally begins the session,
to the time the session is terminated.
78 of 84
Session Management
Creating and Using Sessions
Two methods of the HttpServletRequest object are
used to create a session:
HttpSession getSession( );
HttpSession getSession(boolean);
Other methods for dealing with sessions:
Method
Description
String getRequestedSessionID( )
Gets the ID assigned by the server to
the session
Boolean isRequestSessionIdValid( )
Returns true if the request contains a
valid session ID
Boolean
isRequestSessionIdFromCookie( )
Returns true if the session ID was sent
as part of a cookie
Boolean isRequestSessionIdFromURL( ) Returns true if the session ID was sent
through URL rewriting
79 of 84
Session Management
What do you do with a session?
Sessions are useful for persisting information about a
client and a clients interactions with an application.
To do that, the HttpSession interface defines a number
of mehods:
setAttribute(String, Object)
getAttribute(String)
80 of 84
Forwarding and
Including Requests
81 of 84
Forwarding and Including Requests
Obtaining RequestDispatcher
From ServletRequest
RequestDispatcher getRequestDispatcher(String path)
The path argument can be a relative path or absolute path
If the path is absolute relative to application context it starts with a /
e.g. /Login
If the path if relative it is interpreted relative to the current web
component location, e.g. if web component is /store then case would be
considered /store/case
From ServletContext
ServletContext getServletContext()
RequestDispatcher getNamedDispatcher(String name)
RequestDispatcher getRequestDispatcher(String path)
The path argument should always start with a / and is interpreted relative
to the application context
82 of 84
Forwarding and Including Requests
Using RequestDispatcher
Forwarding Request
void forward(ServletRequest request, ServletResponse
response) throws ServletException, java.io.IOException
Calling servlet should not write any data to the response
stream before calling this method
If response data is sent to the stream before calling forward
an error is thrown
Including Resource
void include(ServletRequest req, ServletResponse res) throws
ServletException, java.io.Exception
You can safely write to the ResponseStream before calling
the include function.
83 of 84
Forwarding and Including Requests
Adding Parameters
Parameters are added for use in the forwarded request
Several methods defined in ServletRequest Interface
Object getAttrubute(String name)
Enumeration getAttributeNames()
void setAttribute(String name, Object o)
void removeAttribute(String name)
The calling servlet can set the attributes
The receiving servlet will use getAttribute(String)
method to retrieve the values
84 of 84