Servlets
1 of 84
Container Architecture
Web Components
Servlets and Servlet Applications
Servlet API
Javax.servlet
Javax.servlet.http
Deploying an Application
2 of 84
4 of 84
It is written in Java
Installing Tomcat
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
6 of 84
HTTP
7 of 84
HTTP
Application Layer Protocol
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
(localhost or ip-address)
(80 or 8080 for web server)
9 of 84
HTTP
HyperText Transfer Protocol
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.
11 of 84
HTTP
HTTP Headers
General & Entity information used for both client & server
Request information included by client
Response information included by server
12 of 84
HTTP
Protocol
13 of 84
HTTP
Tracking State
14 of 84
HTTP
HTTP Status Codes
Informational
Success
Redirection
Client error
Server error
Servlets
16 of 84
Servlets
Introduction
Browser
Applet
Java Application
17 of 84
J2EE Architecture
J2EE Container Architecture
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
20 of 84
Servlets
Servlet Communication
HTML (Browsers)
WML (Mobile Devices)
21 of 84
23 of 84
Servlets API
24 of 84
Servlets
Servlet API
javax.servlet
javax.servlet.Http
25 of 84
Servlets
JAVA Servlets
Servlets
Generic Servlet Class
Methods
LifeCycle Methods
init()
service()
destroy()
Environment Methods
getServletContext()
getInitParameter()
getInitParameterNames()
Utility Methods
log()
27 of 84
Servlets
javax.servlet.http
8 interfaces
7 classes
28 of 84
Servlet Package
javax.servlet
The Servlet interface defines methods that
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
Service() method
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)
34 of 84
doPost(HttpServletRequest,HttpServletResponse)
35 of 84
Other Methods
HEAD: Client sees only header of response to
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
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
Servlets
HttpServletRequest Interface
Extends ServletRequest
Inherited methods from ServletRequest
getParameterNames()
getParameter(String name)
getParameterValues(String name)
getServerName()
getServerPort()
getRequestDispatcher
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
HttpServletRequest
HttpServletResponse
getParameter(String name)
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
Static content in D
Dynamic content
in WEB-INF
web.xml in WEB-INF
Servlets in classes
48 of 84
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>
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
http://localhost:8080/login/login.html
54 of 84
Example 2
55 of 84
Tracking State
56 of 84
Tracking State
Cookies
57 of 84
Tracking State
Cookie Attributes
Attributes of a cookie
58 of 84
Tracking State
Cookie Servlet
package edu.albany.mis.goel.servlets;
import java.io.IOException;
import java.io.PrintWriter;
if(cookies != null) {
import java.util.Random;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
if(cookies[i].getName().equals("token"))
{
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
token = cookies[i];
import javax.servlet.ServletException;
break;
{
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;
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.ServletException;
long id = rand.nextLong();
if(cookies != null) {
token.setMaxAge(-1);
token.setPath("/cookie/track");
if(cookies[i].getName().equals("token")) {
}
}
response.addCookie(token);
token = cookies[i];
else {
break;
62 of 84
Tracking State
URL Encoding
http:// www.address.edu:1234/path/subdir/file.ext?query_string
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
Tracking State
URL Rewriting
package edu.albany.mis.goel.servlets;
if (tokenID == null) {
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
tokenID = Long.toString(rand.nextLong());
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
else {
import javax.servlet.ServletException;
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\">");
writer.println("</body></html>");
writer.close();
}
}
64 of 84
Tracking State
Hidden Form Fields
65 of 84
Tracking State
Hidden Form Field
package edu.albany.mis.goel.servlets;
else {
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
writer.println("<p>");
import javax.servlet.ServletException;
writer.println("</form>");
writer.println("<p>");
response.setContentType("text/html");
writer.println("<html><head><title>Tokens</title></head><body ");
writer.println("</form>");
writer.println("style=\"font-family:verdana;font-size:10pt\">");
if(token == null) {
// Client did not sent any token
writer.println("</body></html>");
writer.close();
token = Long.toString(rand.nextLong());
66 of 84
Tracking State
HttpSession Interface
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
* selecting and addition to the shopping card. The data is read from
* Steps:
* init()
DocumentBuilder db = null;
try { db = dbf.newDocumentBuilder();
* 2. Obtains the name of the product file from the context (init param)
* doGetPost()
* 3. Adds products to the web page and links them to the cartServlet
*/
package edu.albany.mis.goel.store;
Node product;
import java.io.*;
import java.util.*;
product = productsList.item(ctr);
import javax.servlet.*;
import javax.servlet.http.*;
// JAXP packages
attrib = attribs.getNamedItem("price");
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
}
import org.w3c.dom.*;
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 Cart() {
public Product(int id, String name, String price) {
}
// Function to get items from the cart
this.price = price;
this.name = name;
this.id=id;
return items.values().iterator();
}
}
public void addItem(Product product) throws ItemAlreadyAddedException {
return this.price;
if (this.items.containsKey(id)) {
}
this.items.put(id, product);
return this.name;
}
public int getId() {
package edu.albany.mis.goel.store;
return this.id;
import javax.servlet.*;
70 of 84
Store
CartServlet
package edu.albany.mis.goel.store;
import java.io.*;
throws ItemAlreadyAddedException {
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
try {
cart.addItem(p);
doGetOrPost(req,res);
req.getSession().setAttribute("cart",cart);
if (cart == null) {
// Check to see if we are adding to the cart or we want to dispay the cart
out.println("<table>");
while (items.hasNext()) {
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>");
out.println("<tr>");
out.println("</table>");
displayCart(cart, out);
}
}
}
71 of 84
Tracking State
CheckoutServlet
/** Checkout for the customer. This is also the place where the
dispatcher.include(req,res);
* Steps
out.println("<form action='confirmed.html'>" +
}
}
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/
company.jpg
divider.jpg
admin/
admin.jsp
WEB-INF/
web.xml
classes/edu/albany/mis/goel/servlets/
ShoppingCart.class
Catalog.class
lib/
xereces.jar
xalan.jar
ShoppingCart.java
Catalog.java
edu/albany/mis/goel/servlets/
Application Deployment
Deployment of Web Applications
Application Deployment
Deployment of Web Applications, contd.
Location: ${Tomcat_Home}/conf/server.xml
Relative path (/store.war) tells Tomcat that store.war is at the top level of
the webapps directory
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
78 of 84
Session Management
Creating and Using Sessions
Description
String getRequestedSessionID( )
Boolean isRequestSessionIdValid( )
Boolean
isRequestSessionIdFromCookie( )
Session Management
What do you do with a session?
80 of 84
Forwarding and
Including Requests
81 of 84
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 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
84 of 84