Nothing Special   »   [go: up one dir, main page]

Advance Java Module 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

Module -1 Servlet

Introduction to J2EE
 J2EE stands for Java 2 Enterprise Edition.
 J2EE is a platform-independent, Java-centric environment from Sun for developing, building and
deploying Web-based enterprise applications online. The J2EE platform consists of a set of services, APIs,
and protocols that provide the functionality for developing multitier, Web-based applications.
 The J2EE platform uses a multitiered distributed application model. This means application logic is
divided into components according to function, and the various application components.
 A J2EE application system is divided into the tiers as shown below:
 Client Tier
 Web Tier
 EJB (Enterprise JavaBeans) Tier
 EIS Tier (Enterprise Information
Systems)
 J2EE application can consist of the three
or four tiers shown in figure 1.1

 J2EE multitiered applications are


generally considered to be three-tiered
applications because they are distributed
over three different locations that are
client machines, J2EE server machine,
and the database machine.
Figure1.1: J2EE Architecture
J2EE Application Components
J2EE applications are made up of the following components.
 Application clients and applets are client components.
 Java Servlet and Java Server Pages (JSP) technology are web components.
 Enterprise JavaBeans (EJB) is business components.
J2EE components are written in the Java
programming language and compiled in the same
way as any Java programming language program.
The difference when you work with the J2EE
platform, is J2EE components are assembled into a
J2EE application, verified that they are well-formed
and in compliance with the J2EE specification, and
deployed to production where they are run and Figure 1.2: Client Tier Architecture
managed by the J2EE server.
Module -1 Servlet
Client Tier
Client tier consists of programs that interact with the user. It prompts the user for input and then converts the
user’s response into requests that are forwarded to program that processes the request and returns results to the
client program.

Web Tier
Web tier accepts requests from other
software that was sent using POST, GET,
and PUT operations, which are part of
HTTP transmissions. The two major
components of web tier are Servlets and
Java Server Pages. A servlet is a java class
that resides on the web tier and is called
by a request from a browser client that
operates on the client tier. Figure 1.3: Web Tier Architecture

Business Tier and Enterprise Information Systems Tier


Enterprise java bean is a class that
contains business logic and callable from
a servlet or JSP. EJB tier contains the
enterprise java beans server that stores
and manages enterprise java beans. This
tier automatically handles concurrency
issues that assure multiple clients have
simultaneous access to the same object
and also manages instances of
components. Figure 1.4:Business & EIS Tier Architecture
EIS tier provides flexibility to developers of J2EE applications since it include variety of resources and support
connectivity to resources. It defines all the elements that are needed to communicate between J2EE application
and non-J2EE software.

J2EE Server and Container


A container is a runtime support of a system level entity. Before it can be executed, a web, enterprise bean, or
application client component must be assembled in to a J2EE module and deploy into its container. The four types
of container that the J2EE specification defines are applet container, application-client container, web container
and EJB container.

Applet Container
An applet is a java program that can be embedded into a web page. Most of the web pages are authored in HTML.
To use an applet in HTML document, the tags <APPLET> and </APPLET> are used. They are used to indicate to
Module -1 Servlet
the browser that a java applet should be loaded. “These tags act as a container for the java applet definition.”
Applet container manages the execution of applet, and contains the web browser.

Application-Client Container
The Application Client Container (ACC) is a combination of Java classes, libraries, and other files. They are used
to distribute along with Java client programs that execute on their own JVM. The execution of the application
client components is managed by the application-client container. The ACC can take the responsibility to collect
user name and password which is treated as authentication data.

Figure 1.5: Containers Architecture


Java EE Server
The runtime portion of a java EE product. A java EE server provides EJB and web containers.

Web Container:
A web container is a part of web server. It provides the run time environment to execute a web application such as
a servlet, JSP. A servlet container translates the URL requests into servlet requests. The JSP implicit objects such
as request, response, out, page, pageContext etc., are exposed by JSP container.

EJB Container:

The EJB container manages the execution of enterprise beans for Java EE applications. Enterprise beans and their
container run on the java EE server. An EJB Container manages transactions, state management details, multi
threading, connection pooling. The applications are provided with security using EJB container. All database
access required by the entity bean will be handled by the EJB container.
Module -1 Servlet
Chapter – 1

Servlets
 Servlet is a java program that runs on the server side and it acts as a middle layer between a request
coming from the web browser or other HTTP client. The figure 1.6 shows the interaction between client
and Servlet.
 Servlet is an API that provides many
interfaces and classes including
documentations.
 Servlet is a class that extends the capabilities
of the servers and responds to the incoming
request. It can respond to any type of
requests. Servlet is a web component that is
deployed on the server to create dynamic
web page.
 Servlets are Java technology’s answer to
Figure 1.6: Client and Servlet Interaction
CGI programming.

Then Servlet’s jobs are:


i. Read any data sent by the user
This data is usually entered in a form on a Web page.

ii. Look up any other information about the request that is embedded in the HTTP request.
This information includes details about browser capabilities, cookies, the host name of the requesting
client, and so forth.

iii. Generate the results.


This process may require talking to a database, executing an RMI or CORBA call, invoking a legacy
application, or computing the response directly.

iv. Format the results inside a document.


In most cases, this involves embedding the information inside an HTML page.

v. Set the appropriate HTTP response parameters.


This means telling the browser what type of document is being returned (e.g., HTML), setting cookies
and caching parameters, and other such tasks.

vi. Send the document back to the client.


This document may be sent in text format (HTML), binary format (GIF images), or compressed format
like gzip that is layered on top of some other underlying format.
Module -1 Servlet
Advantages of Servlets over Traditional “CGI”:
Java servlets are more
 Easier to use  More portable  Safer
 More powerful  Efficient  Cheaper
than traditional CGI
i. Convenient:
Servlets have an extensive infrastructure for automatically parsing and decoding
 HTML form data,
 reading and setting HTTP header
 handling cookies, tracking sessions
 many other such high-level utilities
ii. Powerful:
 Servlets can talk directly to the Web server, whereas regular CGI programs cannot[but can do
using APIs]
 Communicating with the Web server makes it easier to translate relative: “URLs into concrete path
names, for instance”.
iii. Portable:
Servlets are written in the Java programming language and follow a standard API. Consequently, servlets
written for,
 I-Planet Enterprise Server
 Apache Tomcat
 Microsoft Internet Information Server
 Sun’s JavaServer Web Development Kit (JSWDK)
 IBM WebSphere
iv. Secure:
 The CGI programmer has to be very careful to filter out characters such as backquotes and semicolons
that are treated specially by the shell. This is weaknesses stemming from this problem are constantly
being uncovered in widely used CGI libraries.
 Some CGI programs are processed by languages that do not automatically check array or string
bounds.
Servlets is more secure from these problems because array bounds checking and other memory protection
features are a central part of the Java Programming Language.

v. Cheaper:
There are a number of free or very inexpensive Web servers available that are good for “personal” use or low-
volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web
servers are relatively expensive. Nevertheless, once you have a Web server, adding a Servlets.
Module -1 Servlet
vi. Efficient than CGI:

 If N requests to the same CGI program, the  If N requests(threads) but only a single copy of
code for the CGI program is loaded into the servlet class.
memory N times.  When a servlet finishes handling a request,
 When a CGI program finishes handling a remain in memory. So it is straightforward to
request, the program terminates store arbitrarily complex data between
requests.

1.1 Basic Structure of Servlets:


To be a servlet, a class should extend HttpServlet and override doGet or doPost, depending on whether the data is
being sent by GET or by POST. Both of these methods take two arguments: an HttpServletRequest and an
HttpServletResponse.
 The HttpServletRequest has methods by which you can find out about incoming information such as
form data, HTTP request headers, and the client’s hostname.
 The HttpServletResponse lets you specify outgoing information such as HTTP status codes (200, 404,
etc.), response headers (Content-Type, Set-Cookie, etc.), and lets you obtain a PrintWriter used to send
the document content back to the client.
Syntax: import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletTemplate extends HttpServlet {


public void doGet(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
// Use "request" to read incoming HTTP headers(eg. cookies)and HTML
form data(eg. data the user entered and submitted).

// Use "response" to specify the HTTP response status code and


headers (eg. the content type, cookies).
PrintWriter out = response.getWriter();

// Use "out" to send content to browser


}
}
Module -1 Servlet
Example1.1: Simple Servlet Generating [HelloWorld.java]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {


protected void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException{

PrintWriter out = response.getWriter();


out.println("Hello World");
}
}

Example1.2: A Servlet that Generates HTML[index.html and HelloServlet.java]

index.html
<html>
<head><title>User Name</title></head>
<body>
<center><h1>Welcome</h1></center>
<form action="HelloServlet" method="Post">
Enter your Name: <input type="text" name="name"/><br/><br/>
<input type="submit" value="submit"/>
</form></body></html>
HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
PrintWriter out = response.getWriter();
String username=request.getParameter("name");
out.println("<html><body>");
out.println("<h1>Username is: " + username + "</h1>");
out.println("</body></html>");
}
}
Module -1 Servlet
1.2 Servlet Packaging:
In a production environment, multiple programmers may be developing servlets for the same server. So, placing
all the servlets in the top-level Servlet directory results in a massive hard-to manage directory and risks name
conflicts when two developers accidentally choose the same Servlet name. Packages are the natural solution to
this problem.
Creating Servlets in Packages:
Two steps are needed to place servlets in packages:

 Move the files to a subdirectory that matches the intended package name.
Example: I’ll use the coreservlets package for the servlets case. So, the class files need to go in a
subdirectory called coreservlets.
 Insert a package statement in the class file.
Example: place a class file in a package called coreservlets Package, the first line of the file should read.
package coreservlets;

1.3 Simple HTML building utilities:


An HTML-Building Utilities as follows:
<!DOCTYPE . . .>
<HTML>
<HEAD>
<TITLE>. . . . . . . . . . . </TITLE>
</HEAD>
<BODY . . . >
- - - - - - - - - -
- - - - - - - - - -
</BODY>
</HTML>

The advantage of the <! DOCTYPE> line:


It tells HTML validators which version of HTML you are using, so they know which specification to check your
document against. These validators are very valuable debugging services, helping you catch HTML syntax errors.
The two most popular on-line validators are:
 The World Wide Web Consortium (http://validator.w3.org/)

 The Web Design Group (http://www.htmlhelp.com/tools/validator/)

They let you submit a URL, then they retrieve the page, check the syntax against the formal HTML specification,
and report any errors to you. Since a servlet that generates HTML looks like a regular Web Page to visitors.
 it can be validated in the normal manner unless it requires POST data to return its result.
 Remember that GET data is attached to the URL, so you can submit a URL that includes GET data to the
validators.
Module -1 Servlet
To generate HTML with println statements, especially long tedious lines like the DOCTYPE declaration. Some
people address this problem by writing detailed HTML generation utilities in Java, then use them throughout their
servlets. Still, have the problems listed below:

 Its inconvenience of generating HTML programmatically


 HTML generation routines can be cumbersome and tend not to support the full range of HTML attributes
(CLASS and ID for style sheets, JavaScript event handlers, table cell background colors, and so forth).
For this JSP is a better solution.

1.4 Servlet Lifecycle:


Now be more specific about how servlets are created and destroyed, and how and when the various methods are
invoked. The web container maintains the life cycle of a servlet instance.
Let's see the life cycle of the servlet:
 Loading the servlet class.
 Servlet instance is created.
 Initialize the servlet
instance (init)
 service method is invoked.

 destroy method is invoked.

1. Loading Servlet Class: Figure 1.7: Servlet Life Cycle


A Servlet class is loaded when first request for the servlet is received by the Web Container.

2. Servlet instance is created:


After the Servlet class is loaded, Web Container creates the instance of it. Servlet instance is created only
once in the life cycle.
3. Initialize the servlet instance:
The web container calls the init method only once after creating the servlet instance. The init method is
used to initialize the servlet.
There are two versions of init():
i. one that takes no argument
ii. one that takes a ServletConfig object as an argument
The first version is used when the servlet does not need to read any settings that vary from server to server.
Syntax: public void init() throws ServletException
{
// Initialization code...
}
Module -1 Servlet
Example 1.3: Initialize Servlet instance using ServletConfig object read greet message from web.xml and
display.
NoArgServlet.java

import java.io.*
import javax.servlet.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class NoArgServlet extends HttpServlet {
String str;
public void init()throws ServletException{
ServletConfig info= getServletConfig();
str=info.getInitParameter("greet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("<h1>"+str+"<h1>");
}
}

Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>NoArgServlet</servlet-name>
<servlet-class>NoArgServlet</servlet-class>
<init-param>
<param-name>greet</param-name>
<param-value>Hello J2EE World !!!! </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>NoArgServlet</servlet-name>
<url-pattern>/NoArgServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
Module -1 Servlet
The second version of init() is used when the servlet needs to read server-specific settings before it can complete
the initialization. For example: about database settings, password files, serialized cookies
public void init(ServletConfig config) throws ServletException {
super.init(config); // Initialization code...
}
Notice two things about this code.
 First, the init method takes a ServletConfig as an argument. ServletConfig has a getInitParameter
method with which you can look up initialization parameters associated with the servlet.
 Second thing is that the first line of the method body is a call to super.init(config). This method is
have a parameter ServletConfig object and always call the init method of the superclass registers it where the
servlet can find it later.
Example1.4: Using Initialize parameters[init()]: Shows a servlet that reads the message and repeats initialization
parameters when initialized.
ShowMessage.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShowMessage extends HttpServlet {


private String message;
private String defaultMessage = "No message.";
private int repeats = 1;
@Override
public void init(ServletConfig config)throws ServletException {
super.init(config);
message = config.getInitParameter("message");
if (message == null) {
message = defaultMessage;
}try {
String repeatString = config.getInitParameter("repeats");
repeats = Integer.parseInt(repeatString);
} catch(NumberFormatException nfe) { }
}
@Override
public void doGet(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
PrintWriter out = response.getWriter();
for(int i=0; i<repeats; i++) {
out.println(message + "<BR>");
}
}
}
Module -1 Servlet

Web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

<servlet>
<servlet-name>ShowMessage</servlet-name>
<servlet-class>ShowMessage</servlet-class>

<init-param>
<param-name>message</param-name>
<param-value>Advance JAVA</param-value>
</init-param>
<init-param>
<param-name>repeats</param-name>
<param-value>5</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ShowMessage</servlet-name>
<url-pattern>/ShowMessage</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Output of Servlet instance Initialized Output of Servlet instance not Initialized


a message and repeat
4. Service() method is invoked:
The containers call the service() method each time the request for servlet is received.
 If servlet is not initialized, it follows the first three steps
 If servlet is initialized, it calls the service method

The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost,
doPut, doDelete, etc., as appropriate.
Module -1 Servlet
Syntax:

public void service(HttpServletRequest request, HttpServletResponse


response)throws ServletException, IOException {
// Servlet Code
}

doGet method Syntax:

public void doGet(HttpServletRequest request, HttpServletResponse


response)throws ServletException, IOException {
// Servlet Code
}
doPost method Syntax:

public void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
// Servlet Code
}

Table1.1: Description on different types of HTTP Request


HTTP Request Description
GET Asks to get the resource at the requested URL.
Asks the server to accept the body info attached. It is like GET request with extra
POST
info sent with the request.
Asks for only the header part of whatever a GET would return. Just like GET but
HEAD
with no body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.


Asks for a list of the HTTP methods to which the thing at the request URL can
OPTIONS
respond

5. destroy() method is invoked:


 The Web Container call the destroy() method before removing servlet instance from the services.
 It gives the servlet an opportunity to clean up any resource
Example: memory, thread etc.
Syntax: public void destroy()
{
//Code
}
Module -1 Servlet
1.5 SingleThreadModel interface:

The system makes a single instance of your


servlet and then creates a new thread for each
user request, with multiple simultaneous threads
running if a new request comes in while a
previous request is still executing. This means
that your doGet and doPost methods must be
careful to synchronize access to fields and other
shared data, since multiple threads may be trying
to access the data simultaneously.
If you want to prevent this multithreaded access,
you can have your servlet implement the
SingleThreadModel interface, as below: Figure 1.8: Multi-Threading Model

public class YourServlet extends HttpServlet


implements SingleThreadModel {
//Code
}

If you implement this interface,

 The system guarantees that there is never more


than one request thread accessing a single
instance of your servlet.

 It does so either by queuing up all the requests


and passing them one at a time to a single servlet
instance, or by creating a pool of multiple
instances, each of which handles one request at a
time as shown in figure 1.9.

Figure 1.9: SingleThread Model

Example 1.5:

 The class SingleThreadServlet which is a servlet prevents handling Single requests at a single time.
 Thread. Sleep( 2000 ) will stop the execution of the thread for 2000 millisecond.
 When another user access the same servlet, the new instance is created instead of using the same instance
for multiple threads.
Module -1 Servlet

SingleThreadServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SingleThreadServlet extends HttpServlet
implements SingleThreadModel{
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();

out.print("Welcome");
try{
Thread.sleep(2000);
out.print(" to Servlet ! ! !");
}
catch(Exception e){
e.printStackTrace(out);
}
}
}

Differentiate between the doGet() and doPost() method:

doGet() doPost()
In case of post request, large amount of
In case of Get request, only limited amount of
Parameters data can be sent because data is sent in
data can be sent because data is sent in header.
body.
Parameters are not saved in browser
History Parameters remain in browser history
history
Get request is not secured because data is Post request is secured because data is
Security
exposed in URL bar. not exposed in URL bar.
Restrictions on Yes, since form data is in the URL and URL
form data length is restricted ie., 2048 characters No
length
Bookmarked Get request can be bookmarked Post request cannot be bookmarked
Data are re-executed but may not be re-
BACK button submitted to server if the HTML is stored in the Data will be re-submitted
browser cache.
Module -1 Servlet
Chapter 2
Handling the Client Request: Form Data
2.1 Form Data
We’ve seen URL: http://host/path?user=Marty+Hall&origin=bwi&dest=lax. The part after the
question mark (i.e., user=Marty+Hall&origin=bwi&dest=lax) is known as form data (or query
data) and is the most common way to get information from a Web page to a server-side program.

Form data can be attached to the end of the URL after a question mark (as above), for GET requests, or
sent to the server on a separate line, for POST requests.
2.2 Reading Form Data from Servlets
The request object of HttpServletRequest class contains the incoming request data sent by client program.
Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request. The
parameters are stored as a set of name-value pairs. Multiple parameter values can be given as parameter name.
By using following methods we can read parameter values which exist in the parameter name.
i. getParameter()
ii. getParameterValues()
iii. getParameterNames()

 getParameter(): You call request.getParameter() method to get the value from HTML Page.
Null is returned if data is not sent.
Syntax: public String getParameter(String name)
Example: String username = request.getParameter(“UNAME”);
Example 2.1: To implement a simple servlet called Three Params that reads form data parameters named
param1, param2, and param3 and display their values. Shows an HTML form that collects user input and sends
it to Servlet.
index.html
<html>
<body bgcolor="#FDF565">
<h1>Collecting Three Parameters</h1>
<form action="ParmeterServlet" method="Get">
First Parameter:<input type="text" name="param1"/><br>
Second Parameter:<input type="text"name="param2"/><br>
Third Parameter: <input type="text" name="param3"/><br>
<input type="submit" value="Click Here">
</form></body></html>
Module -1 Servlet

ParmeterServlet.java
import java.io.*
import javax.servlet.*
import javax.servlet.http.*;

public class ParmeterServlet extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
PrintWriter out=response.getWriter();
String title = "Reading Three Request Parameters";
out.println("<BODY BGCOLOR=\"#FDF5E6\">");
out.println("<H1 ALIGN=CENTER>" + title + "</H1>");
out.println("<UL>"+
"<LI><B>param1</B>:" + request.getParameter("param1")
+ "<LI><B>param2</B>:" + request.getParameter("param2")
+"<LI><B>param3</B>:"+ request.getParameter("param3")+"</UL>");
out.println("</BODY></HTML>");
}
}

 getParameterValues(): Call this method if the parameter have more than one value, which returns an
array of strings, Null is returned if data is not sent.
Syntax: public String [] getParameterValues(String name)
Example: String[] v = request.getParameterValues("Checkboxname");
Example 2.2: To implement a Servlet called checkbox that describes the different types of programming
languages, and then choose knowing languages and display as a list.

index.html
<html>
<body>
<form action="ParamValues" method="Post">
Languages:<br>
<input type="checkbox" name="language" value="C" checked>C<br>
<input type="checkbox" name="language" value="Java"/>
Java/J2EE<br>
<input type="checkbox" name="language" value="Dot Net">C#<br>
<input type="checkbox" name="language" value="Python">Python<br>
<input type="submit" value="submit">
</form>
</body>
</html>
Module -1 Servlet

ParamValues.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ParamValues extends HttpServlet {


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
PrintWriter out=response.getWriter();

String[] paramvalues=request.getParameterValues("language");
out.println("<h4>Selected Languges are:</h4>");
if(paramvalues==null){
out.println("<h5>NONE</h5>");
}
else{
for(String str:paramvalues){
out.println("<li>" + str + "</li>");
}
}
}

 getParameterNames():Call this method if you want a complete list of all parameters in the current request
in the form of Enumeration. Each name is given in the form as String object.
Syntax: java.util.Enumeration getParameterNames()
Example: Enumeration paramNames=request.getParameterNames();

Example 2.3: Here isan example that looks up all the parameter names that are sent and display their values

index.html
<html>
<head><title>Reading the input</title></head>
<body bgcolor="#FDF565">
<form action="ParamNamesServlet" method="Post">
User Information:<hr>
First Parameter: <input type="text" name="param1"/><br>
Second Parameter: <input type="text" name="param2"/><br>
Third Parameter: <input type="text" name="param3"/><br>
Module -1 Servlet

index.html (Continued)
<hr>
Languages:<br>
<input type="checkbox" name="language" value="C" checked>C/C++<br>
<input type="checkbox" name="language" value="Java"/>Java/J2EE<br>
<input type="checkbox" name="language" value="Dot Net">C#<br>
<input type="checkbox" name="language" value="Python">Python<br>
<hr>
<input type="submit" value="Click Here">
</form>
</body></html>
ParamNamesServlet.java
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

public class ParamNamesServlet extends HttpServlet {


@Override
protected void doPost(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
PrintWriter out=response.getWriter();

Enumeration userinfo= request.getParameterNames();

while(userinfo.hasMoreElements()){
String info=(String)userinfo.nextElement();
String[] value=request.getParameterValues(info);
for(int i=0;i<value.length;i++){
out.println("Parameter Name is '"+info+"' and
Parameter Value is '"+value[i]+"'");
}
}
}
}
Module -1 Servlet
Chapter 3

Handling the Client Request: HTTP Request Headers


3.1 Reading Request Headers from Servlets
Reading headers is straightforward; just call the getHeader method of HttpServletRequest, which returns a
String if the specified header was supplied on this request, null otherwise. Header names are not case sensitive.

Following are the important header information which comes from browser side and you would use very
frequently in web programming:
Table 3.1: Methods for reading request header
Methods Meaning
getCookies() returns the contents of the Cookie header, parsed and stored in an array of Cookie objects
getAuthType()
break the Authorization header into its component pieces.
getRemoteUser()
getContentLength() returns int value of the Content-Length header
getContentType() Returns string value of the Content-Type header
getDateHeader()
read the specified header and then convert them to Date and int values
getIntHeader()
to get an Enumeration of the values of all occurrences of the header names received on
getHeaderNames()
this particular request.
If a header name is repeated in the request,
 version 2.1 servlets cannot access: returns the value of the first occurrence of the
getHeaders()
header only
 version 2.2 returns an Enumeration of the values of all occurrences of the header.
getMethod() returns the main request method(Get, Post . . . . )
getRequestURI() returns the part of the URL that comes after the host and port but before the form data
getProtocol() returns the third part of the request line, [HTTP/1.0 or HTTP/1.1]

Example 3.1: Printing All Headers

ShowRequestHeaderServlet.java

import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShowRequestHeaderServlet extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
Module -1 Servlet

ShowRequestHeaderServlet.java(continued)

PrintWriter out = response.getWriter();


String title="Servlet Example: Showing Request Headers";
out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<B>Request Method:</B>" + request.getMethod() + "<BR>\n" +
"<B>Request URI:</B>" + request.getRequestURI() + "<BR>\n" +
"<B>Request Protocol:</B>" + request.getProtocol() +
"<BR><BR>\n");
out.println("<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Header Name<TH>Header Value");

Enumeration headerNames = request.getHeaderNames();


while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println("<TD>"+request.getHeader(headerName)+“</TR>”);
}
out.println("</TABLE>\n</BODY></HTML>");
}
}
Module -1 Servlet
3.2 HTTP 1.1 Request Headers:
The possible HTTP 1.1 request headers along with a brief summary of how servlets can make use of them.

Table 3.2: List of Request Headers


Header Names Description
Accept specifies the MIME types that the browser or other client can handle. Returns more than one
format

Accept-Charset indicates the character sets (e.g., ISO-8859-1) the browser can use.

Accept-Encoding designates the types of encodings that the client knows how to handle. If it receives this header,
the server is free to encode the page by using the format, sending the Content-Encoding response
header to indicate that it has done so.

Accept-Language specifies the client’s preferred languages, in case the servlet can produce results in more than one
language. The value of the header should be one of the standard language codes such as en, en-us,
da, etc.

Authorization is used by clients to identify themselves when accessing password-protected Web pages.

Cache-Control used by the client to specify a number of options for how pages should be cached by
proxy servers.
Connection tells whether or not the client can handle persistent HTTP Connections.

Content-Length only applicable to POST requests and gives the size of the POST data in bytes. Simply use
request.getContentLength().
Content-Type usually used in responses from the server.
It can also be part of client requests when the client attaches a document as the POST data
or when making PUT requests. Simply use getContentType.
Cookie used to return cookies to servers that previously sent them to the browser.

Expect client tell the server what kinds of behaviors it expects

From gives the e-mail address of the person responsible for the HTTP request

Header Names Description

Host Browsers are required to specify this header, which indicates the host and port as given in
the original URL.
If-Match used header applies primarily to PUT requests. The client can supply a list of entity tags
as returned by the ETag response header
If-None-Match If-Match, except that the operation should be performed only if no entity tags match.
Module -1 Servlet

Header Names Description

If-Modified- indicates that the client wants the page only if it has been changed after the specified date.
Since
If-Range a client that has a partial copy of a document ask for either the parts it is missing (if
unchanged) or an entire new document (if it has changed since a specified date).
If-Unmodified- is used for PUT requests
Since
Pragma The only standard value for this header is no-cache indicates that a servlet that is acting as
a proxy should forward the request even if it has a local copy.
Header Names Description
Proxy- clients identify themselves to proxies that require it. Servlets typically ignore this header,
Authorization using Authorization instead
Range A client that has a partial copy of a document ask for only the parts it is missing.
Referer indicates the URL of the referring Web page.
Upgrade the browser or other client specify a communication protocol it prefers over HTTP 1.1
User-Agent identifies the browser or other client making the request and can be used to return
different content to different types of browsers
Via is set by gateways and proxies to show the intermediate sites the request passed through.
Warning clients warn about caching or content transformation errors.

3.3 Sending Compressed Web Pages


Several recent browsers know how to handle gzipped content, automatically uncompressing documents
that are marked with the Content-Encoding header and then treating the result as though it were
the original document. Sending such compressed content can be a real timesaver, since the time
required to compress the document on the server and then uncompress it on the client is typically dwarfed
by the savings in download time, especially when dialup connections are used.
Implementing gzip format, remember the following points:
 Import java.util.zip, package contains classes that support reading and writing the GZIP compression
formats
 Then servlet first checks the Accept-Encoding header to see if it contains an entry for gzip.
 If so, it uses a GZIPOutputStream to generate the page, specifying gzip as the value of the Content-
Encoding header.
 We must explicitly call close when using a GZIPOutputStream.
 If gzip is not supported, the servlet uses the normal PrintWriter to send the page.
Module -1 Servlet
Example 3.2: Sending Compressed Page

EncodedPage.java

import java.io.*;
import java.util.zip.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EncodingPage extends HttpServlet {@Override


public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
String encodings = request.getHeader("Accept-Encoding");
String encodeFlag = request.getParameter("encoding");
PrintWriter out; String title;
if ((encodings != null) &&
(encodings.indexOf("gzip"!= -1) && !"none".equals(encodeFlag))
{
title = "Page Encoded with GZip";
OutputStream out1 = response.getOutputStream();
out = new PrintWriter(new GZIPOutputStream(out1), false);
response.setHeader("Content-Encoding", "gzip");
}
else{
title = "Unencoded Page";
out = response.getWriter();
}
out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n");
String line = "Blah, blah, blah, blah, blah."
+ "Yadda, yadda, yadda, yadda.";
for(int i=0; i<10000; i++) {
out.println(line);
}
out.println("</BODY></HTML>");
}
}
Module -1 Servlet
3.4 Restricting Access to Web Pages
Many Web servers support standard mechanisms for limiting access to designated Web pages. These mechanisms
can apply to static pages as well as those generated by servlets, so many authors use their server-specific
mechanisms for restricting access to servlets.
Form-based access control requires more effort on the part of the servlet developer, and HTTP-based
authorization is sufficient for many simple applications.
Two Steps are involved for “basic” authorization.
Step 1:
 Check whether there is an Authorization header.
 If there is no such header, go to Step 2.
 If there is, skip over the word “basic” and reverse the base64 encoding of the remaining part.
 This results in a string of the form username:password.
 Check the username and password against some stored set.
 If it matches, return the page. If not, go to Step 2.

Step 2:
 Return a 401 (Unauthorized) response code and a header of the following form:
WWW-Authenticate: BASIC realm=“some-name”.
This response instructs the browser to pop up a dialog box telling the user to enter a name and password
for some-name, then to reconnect with that username and password embedded in a single base64 string
inside the Authorization header.
Example 3.3: Restricting the web page

RestrictingPage.java
import java.io.*;
import java.util.Properties;
import javax.servlet.*; import
javax.servlet.http.* import
sun.misc.BASE64Decoder;

public class RestrictingPage extends HttpServlet {


private Properties passwords;
private String passwordFile;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String authorization = request.getHeader("Authorization");


Module -1 Servlet

RestrictingPage.java(continued)

if (authorization == null) {
askForPassword(response);
}
else {
String userInfo = authorization.substring(6).trim();
BASE64Decoder decoder = new BASE64Decoder();

String nameAndPassword =newString(decoder.decodeBuffer(userInfo));


int index = nameAndPassword.indexOf(":");
String user = nameAndPassword.substring(0, index);
String password = nameAndPassword.substring(index+1);
String realPassword = "chat";

if ((realPassword != null) && (realPassword.equals(password))) {


String title = "Welcome to the Protected Page";
out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title +"</H1>\n" +"Congratulations.
You have accessed a highly proprietary company document\n"
+"Shred or eat all hardcopies before going to bed tonight.
\n" + "</BODY></HTML>");
}
else {
askForPassword(response);
}
}
}
private void askForPassword(HttpServletResponse response) {
response.setStatus(response.SC_UNAUTHORIZED); // Ie 401
response.setHeader("WWW-Authenticate", "BASIC realm=
\"privileged-few\"");
}
}
Module -1 Servlet
Chapter 4

Generating the Server Response: HTTP Status Codes

4.1 The purpose of HTTP status codes


When a Web server responds to a request from a browser or other Web client, the response typically
consists of a status line, some response headers, a blank line, and the document. Here is a minimal
example:

The status line consists of the HTTP version, a status code, and a very short message corresponding to the
status code. In most cases, all of the headers are optional except for Content-Type, which specifies the
MIME type of the document that follows.

Servlets can perform a variety of important tasks by manipulating the status line and the response headers.

Example: They can forward the user to other sites; indicate that the attached document is an image, Adobe
Acrobat file, or HTML file; tell the user that a password is required to access the document; and so forth.

The general method of setting status codes is simply to call response.setStatus(int);


 takes an int (the status code) as an argument.
 sets an arbitrary status code.
Example: response.setStatus(response.SC_UNAUTHORIZED);
If your response includes a special status code and a document, be sure to call setStatus before actually returning
any of the content with the PrintWriter.

There are other two common cases where a shortcut method in HttpServletResponse is provided. Just be
aware that both of these methods throw IOException .

 public void sendError(int code, String message)


This method sends a status code (usually 404) along with a short message that is automatically
formatted inside an HTML document and sent to the client.
Module -1 Servlet
Example 4.1:
SendErrorServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SendErrorServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
// Set error code and reason.
response.sendError(407, "Need authentication!!!" );
}
}

 public void sendRedirect(String url):


The method generates a 302 response along with a Location header giving the URL of the new
document.
Example 4.2: Request will be redirect to the chosen url
index.html
<html>
<head><title>Send Redirect</title></head>
<body>
<form action="RedirectServlet" method="Get">
Choose Your Favorite:
<select name="rv">
<option value="1">Yahoo</option>
<option value="2">Gmail</option>
<option value="3">AnyOtherSite</option>
</select><br>
<input type="submit">
</form>
</body>
</html>
Module -1 Servlet
4.2 HTTP 1.1 Status Codes and Their Purpose:
The five general categories in HTTP1.1 status code:
Table 4.1: categories in HTTP1.1 status code

Status Code Description


100-199: Informational The request has been received and the process is continuing
200-299: Success The action was successfully received, understood, and accepted
300-399: Redirection further action must be taken in order to complete the request.
400-499: Client Error the request contains incorrect syntax or cannot be fulfilled

500-599: Server Error the server failed to fulfill an apparently valid request.
You should only send the new codes to clients that support HTTP 1.1, as verified by checking
request.getRequestProtocol.
Common HTTP 1.1 Status Code:
However, you should note that servers are allowed to vary the messages slightly, and clients pay attention only to
the numeric value.
Table 4.2: List of Common numeric value in status code
Status Code &
Constant Name Description
Message
100 it means that the client is asking if it can send an attached
SC_CONTINUE document in a follow-up request.
Continue
200 SC_OK The request is OK. This status is the default for servlets
OK
204 SC_NO_CONTENT Browser should keep displaying previous document, no new
No Content document is available
301 (SC_MOVED_ • Requested document permanently moved to url.
Moved PERMANENTLY)
• Browsers go to new location automatically
Permanently
302
SC_FOUND The requested page has moved temporarily to a new url
Found
401
SC_UNAUTHORIZED The requested page needs a username and a password
Unauthorized
404
SC_NOT_FOUND The server cannot find the requested page.
Not Found
500 SC_ status notifies the client that the server doesn’t support the
NotImplemented NOT_IMPLEMENTED functionality to fulfill the request.
Module -1 Servlet
4.3 HTTP Response Headers and Their Meaning

The general method to set the response header is simply to call.

Syntax: public void setHeader(string headername, int headervalue)

You must set the headers before the first use of the PrintWriter or OutputStream that transmits the document
content.
There is another two special methods to set headers that contain dates and integers:
 setDateHeader(String header, long milliseconds)
 setIntHeader(String header, int headerValue)
If you want to add a new header rather than replace any existing header with the same name.
 addHeader(string headername, int headervalue)
 addDateHeader(String header, long milliseconds)
 addIntHeader(String header, int headerValue)
Finally, HttpServletResponse also supplies a number of methods for specifying common headers.
Methods Meaning
 sets the Content-Type header(MIME)
setContentType()
 used by the majority of servlets
 sets the Content-Length header
setContentLength()
 used for persistent (keep-alive) HTTP connections.
addCookie() Adds a value to the Set-Cookie header
sendRedirect() Sets Location header (plus changes status code)

HTTP 1.1 Response Headers and Their Meaning:


The possible HTTP1.1 response headers along with a brief summary of how servlets can make use of them.
Table 4.3: List of response header names
Header Name Meaning
Accept-Ranges tells the client whether or not you accept Range request headers.
Age is used by proxies to indicate how long ago the document was generated by the original
server.
Allow specifies the request methods (GET, POST, etc.)
Cache-Control • the circumstances in which the response document can safely be cached.
& Pragma • It can have values public, private or no-cache.
» Public means document is cacheable,
» Private means document is for a single user and can only be stored in private
caches
» no-cache means document should never be cached.
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
Module -1 Servlet

Header Name Meaning


Connection instructs the browser whether to use persistent in HTTP connections or not.
Connection: keep-alive
Content-Encoding indicates the way in which the page was encoded during transmission.
Content- This header signifies the language in which the document is written.
Language Example: en, en-us, ru, etc.

Content-Length indicates the number of bytes in the response.


Content-Location  supplies an alternative address for the requested document.
 Content-Location is informational;
Content-Range is sent with partial-document responses and specifies how much of the total document
was sent
Content-Type  gives the MIME type of the response document.
 The default MIME type for servlets is text/plain
Example: application/zip:- Zip archive, image/gif:- GIF image,
text/html:- HTML document, video/mpeg:- MPEG video clip
Date specifies the current date in GMT format.
Example: response.setHeader("Date", "...");
ETag gives names to returned documents so that they can be referred to by the client later
Expires  The time at which document should be considered out-of-date and thus should no
longer be cached.
 Use setDateHeader() to set this header
Example:
long currentTime = System.currentTimeMillis(); long
tenMinutes = 10*60*1000; // In milliseconds
response.setDateHeader("Expires",currentTime+tenMinutes);
Last-Modified When time document was last changed.
Location should be included with all responses that have a status code in the 300s. The URL to
which browser should reconnect.
Use sendRedirect instead of setting this directly
Refresh The number of seconds until browser should reload page. Can also include URL to
connect to.
response.setIntHeader("Refresh", 30)
response.setHeader("Refresh","5; URL=http://host/path")
Set-Cookie This header specifies a cookie associated with the page.
Server, Retry –After, Trailer, Transfer- Encoding, WWW-Authenticate
Module -1 Servlet
Chapter 5

Handling Cookies
 Cookies are text files stored on the client computer and they are kept for various information tracking purpose.
 Java Servlets transparently supports HTTP cookies.
 There are three steps involved in identifying returning users:
» Server script sends a set of cookies to the browser.
Example: name, age, or identification number etc.
» Browser stores this information on local machine for future use.
» When next time browser sends any request to web server then it sends those cookies information to
the server and server uses that information to identify the user.
5.1 Benefits of Cookies
i. Identifying a User during an E-commerce Session:
Many on-line stores use a “shopping cart” in which the user selects an item, adds it to his/her shopping cart,
and then continues shopping. Since the HTTP connection is usually closed after each page is sent, when the
user selects a new item to add to the cart, how does the store know that it is the same user that put the
previous item in the cart? Persistent (keep-alive). HTTP connections do not solve this problem because it is
stateless. But, Cookies can solve this problem.
ii. Avoiding Username and Password:
Many large sites require you to register in order to use their services, but it is inconvenient to remember and
enter the username and password each time you visit. Cookies are a good alternative for low-security sites.
When a user registers, a cookie containing a unique user ID is sent to him. When the client reconnects at a
later date, the user ID is returned, the server looks it up, determines it belongs to a registered user and
permits access without an explicit username and password.
iii. Customizing a Site:
Many “portal” let you customize the look of the main page. They might let you pick which weather report
you want to see, what stock and sports results you care about, how search results should be displayed, and so
forth. Since it would be inconvenient for you to have to set up your page each time you visit their site, they
use cookies to remember what you wanted. For simple settings, this customization could be accomplished
by storing the page settings directly in the cookies.
iv. Focusing Advertising:
Most advertiser-funded Web sites charge their advertisers much more for displaying “directed” ads than
“random” ads. Advertisers are generally willing to pay much more to have their ads shown to people that are
known to have some interest in the general product category. For example: if you go to a search engine and
do search on “Java Servlets” the search site can charge an advertiser much more for showing you an ad for a
servlet development environment. Without cookies, the sites have to show a random ad when you first arrive
and haven’t yet performed a search, as well as when you search on something that doesn’t match any ad
categories. Cookies let them remember “that’s the person who was searching for such and such previously”
and display an appropriate ad instead of a random one.
Module -1 Servlet
5.2 Problems with Cookies
Providing convenience to the user and added value to the site owner is the purpose behind cookies. And despite
much misinformation, cookies are not a serious security threat.

Cookies are never interpreted or executed in any way and thus cannot be used to insert viruses or attack your
system. Furthermore, since browsers generally only accept 20 cookies per site and 300 cookies total and since
each cookie can be limited to 4 kilobytes, cookies cannot be used to fill up someone’s disk or launch other denial
of service attacks.
The problem is privacy not security,
 First, some people don’t like the fact that search engines can remember that they’re the user who usually
does searches on certain topics. For example, they might search for job openings or sensitive health data
and don’t want some banner ad tipping off their coworkers next time they do a search.
 A second, privacy problem occurs when sites rely on cookies for overly sensitive data. For example, some
of the big on-line bookstores use cookies to remember users and let you order without reentering much of
your personal information.

5.3 Creating a cookie


 To send cookies to the client, a servlet should create one or more cookies with designated names and
values with new Cookie(name, value).

Syntax: Cookie obj_name = new Cookie(“name”, value);

Example: Cookie ck=new Cookie(“username”, name);

Note: Neither the name nor the should contain white space or any of the following characters:
[ ] ( ) = , “ / ? @ : ;

Cookie Attributes:
Before adding the cookie to the outgoing headers, you can set and get the cookie using following methods:
 setXxx methods: you can set the cookie  getXxx methods: you can retrieve the attribute value

Xxx is the name of the attribute you want to specify. javax.servlet.http.Cookie class provides the functionality
of using cookies. It provides a lot of useful methods for cookies, listed below.

Table5.1: List of methods for cookies


Methods Name Description
These methods look up or specify a comment associated with the
public String getComment()
cookie. The comment is used purely for informational purposes
public void setComment(String comment)
on the server.
public String getDomain()
These methods get or set the domain to which the cookie applies.
public void setDomain(String domain)
Module -1 Servlet

Methods Name Description


public String getName() This pair of methods gets or sets the name of the cookie.
public void setName(String cookieName)
public String getPath()
These methods get or set the path to which the cookie applies.
public void setPath(String path)
 This pair of methods gets or sets the boolean value indicating
public boolean getSecure() whether the cookie should only be sent over encrypted
public void setSecure(boolean secureFlag) connections.
 Default is false; the cookie should apply to all connections.
public String getValue() The getValue method looks up the value associated with the
public void setValue(String cookieValue) cookie; The setValue method specifies it.
public int getVersion() These methods get/set the cookie protocol version the cookie
public void setVersion(int version) complies with.

5.4 Steps for creating and set the cookie in to the response header:
 Cookie userCookie = new Cookie("user", "uid1234"); //creating cookie
 userCookie.setMaxAge(60*60*24*365); //setting lifespan
 response.addCookie(userCookie); // Sending Cookie to the Client [HTTP Response Header]

Read cookie from the browser:


After Placing, to read incoming cookies a servlet should call request.getCookies(), which returns an array of
Cookie objects corresponding to the cookies the browser has associated with your site (this is null if there are no
cookies in the request) as shown below:

 Cookie[] cks=request.getCookies();
for(int i=0;i<cks.length;i++) {
out.print(“<br>” + ck[i].getName() + “ ” + ck[i].getValue() );
}

Deleting a Cookie:
 Cookie ck=new Cookie(“user”, “ ”); //deleting value of cookie
 Ck.setMaxAge(0); //Changing the maximum age to 0 seconds
 response.addCookie(ck); //adding cookie in the response
Module -1 Servlet
Example 5.3: Program using cookie to remember the user preferences

index.html

<html>
<head><title>Demo on Cookie</title></head>
<body>
<form action="CreateCookieServlet" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>

CreateCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.*;

public class CreateCookieServlet extends HttpServlet {


@Override
public void doPost(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
try{
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
out.print("Welcome "+name);

Cookie ck=new Cookie("uname",name);//creating cookie object


ck.setMaxAge(60*60); //setting lifespan to a cookie(1 Hour)
response.addCookie(ck); //adding cookie in the response

//creating submit button


out.print("<form action='ReadCookieServlet' method='post'>");
out.print("<input type='submit' value='getYourCookie'>");
out.print("</form>");
out.close();
} catch(Exception e){System.out.println(e);}
}
}
Module -1 Servlet

ReadCookieServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.*;

public class ReadCookieServlet extends HttpServlet {

@Override
public void doPost(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Cookie Name</TH>" +
"<TH>Cookie Value</TH>");

Cookie[] cks=request.getCookies();
for(int i=0;i<cks.length;i++){
out.print("<TR>" + "<TD>" + ck.getName() + "</TD>" +
"<TD>" + ck.getValue() + "</TD>" );
}
}catch(Exception e){System.out.println(e);}
}
}
Module -1 Servlet
Chapter 6

Session Tracking
What is a Session?
 Session simply means a particular interval of time.
 Session is a conversional state between client and server and it can consists of multiple request and
response between client and server.

Why should a session be maintained?

 Each time user requests to the server, server treats the request as the new request.
 Since HTTP and Web Server both are stateless.
 So we need to maintain the state of a user to recognize to particular user.
There are four techniques used in Session tracking are listed below:

i. Cookies:
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a
maximum age, and a version number.
Advantage of Cookies
 Simplest technique of maintaining the state.
 Cookies are maintained at client side.
Disadvantage of Cookies
 It will not work if cookie is disabled from the browser.
 Only textual information can be set in Cookie object.
Because of these reasons, Cookie is not an effective to maintain the sessions.

Note:
 Non-persistent cookie: It is valid for single session only. It is removed each time when user closes the
browser. (e.g. WebApplication1/SessionTrack)
 Persistent cookie: It is valid for multiple session. It is not removed each time when user closes the
browser. It is removed only if user logout or signout.
Module -1 Servlet
ii. Hidden Form Field:
In this case user information is stored in hidden field value and retrieves from another servlet. A web server
can send a hidden HTML form field along with a unique session ID as follows:

<input type="hidden" name="sessionid" value="12345">


Advantage:
 It will always work whether cookie is disabled or not.
Disadvantage:
 It is maintained at server side.
 Extra form submission is required on each pages.
 Only textual information can be used
Example 6.1: We are storing the name of the user in a hidden textfield and getting that value from another servlet.

index.html
<html>
<head><title>Demo on Hidden</title></head>
<body>
<form action="Servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body></html>

Servlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet1 extends HttpServlet {


@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws IOException, ServletException {
try{
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome");
//creating form that have invisible textfield
out.print("<form action='Servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
}catch(Exception e){System.out.println(e);}
}
}
Module -1 Servlet

Servlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet2 extends HttpServlet {


@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException,IOException{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("Hello "+n);
}
catch(Exception e){System.out.println(e);}
}
}

iii. URL Rewriting:


In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can
send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
Example: out.print("<a href='servlet2?uname="+n+"'>visit</a>");
response.sendRedirect("First?user_id="+uid+"");
Advantage
 It will always work whether cookie is disabled or not
 Extra form submission is not required on each pages.
Disadvantage
 It will work only with links.
 It can send only textual information.

Example 6.2: We are maintaining the state of the user using link. For this purpose, we are appending the name of
the user in the query string and getting the value from the query string in another page.
Module -1 Servlet

index.html
<html>
<body>
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>/body></html>

FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws IOException, ServletException{
try{
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome");

//appending the username in the query string


out.print("<a href='SecondServlet?uname=”+n+”'>visit </a>");
}
catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws IOException, ServletException {
PrintWriter out = response.getWriter();
//getting value from the query string
String n=request.getParameter("uname");
out.print("Hello" +n);
}
}
Module -1 Servlet
iv. HTTPSession:
Apart from the above mentioned three ways,
servlet provides HttpSession Interface which
provides a way to identify a user across more
than one page request or visit to a Web site and
to store information about that user.
The servlet container uses this interface to create
a session between an HTTP client and an HTTP
server. The session persists for a specified time
period, across more than one connection or page Figure6.1: HttpSession handling
request from the user.
1) On client's first request, the Web Container generates a unique session ID and gives it back to the client
with response. This is a temporary session created by web container.
2) The client sends back the session ID with each request. Making it easier for the web container to identify
where the request is coming from.
3) The Web Container uses this ID, finds the matching session with the ID and associates the session with
the request.
What does HTTPSession Object perform?
It perform two tasks:
 bind objects
 view and manipulate information about a session, such as the session identifier, creation time, and last
accessed time.
CREATE a HTTP Session:
The HttpServletRequest interface provides two methods to get the object of HttpSession:
 public HttpSession getSession():Returns the current session associated with this request, or if the request
does not have a session, creates one.
Example: HttpSession session = request.getSession();

 public HttpSession getSession(boolean create): Returns the current HttpSession associated with this
request or, if there is no current session and create is true, returns a new session.
Example: HttpSession session = request.getSession(true);

It provides a lot of useful methods to set and get the session object attributes that listed below:
Table 6.1: list of methods for HTTPSession
S.N. Method & Description
public Object getAttribute(String name)
1 This method returns the object bound with the specified name in this session, or null if no object is bound
under the name.
Module -1 Servlet

public Enumeration getAttributeNames()


2 This method returns an Enumeration of String objects containing the names of all the objects bound to
this session.
public long getCreationTime()
3 This method returns the time when this session was created, measured in milliseconds since midnight
January 1, 1970 GMT.
public String getId()
4
This method returns a string containing the unique identifier assigned to this session.
public long getLastAccessedTime()
5 This method returns the last time the client sent a request associated with this session, as the number of
milliseconds since midnight January 1, 1970 GMT.
public int getMaxInactiveInterval()
6 This method returns the maximum time interval, in seconds, that the servlet container will keep this
session open between client accesses.
public void invalidate()
7
This method invalidates this session and unbinds any objects bound to it.
public boolean isNew()
8 This method returns true if the client does not yet know about the session or if the client chooses not to
join the session.
public void removeAttribute(String name)
9
This method removes the object bound with the specified name from this session.
public void setAttribute(String name, Object value)
10
This method binds an object to this session, using the name specified.
public void setMaxInactiveInterval(int interval)
11 This method specifies the time, in seconds, between client requests before the servlet container will
invalidate this session.

Deleting Session Data:


When you are done with a user's session data, you have several options:
 Remove a particular attribute: You can call public void removeAttribute(String name) method to delete
the value associated with a particular key.
 Delete the whole session: You can call public void invalidate() method to discard an entire session.
 Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the
timeout for a session individually.
 Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web
server and invalidate all sessions belonging to all the users.
Module -1 Servlet
 web.xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you can
configure session time out in web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.
Example 6.3: Session Tracking

SessionTracking.java
import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException{
// Create a session object if it is already not created.
HttpSession session = request.getSession();
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = 0;
String visitCountKey = "visitCount";
// Check if this is new comer on your web page.
if (session.isNew())
title = "Welcome to my website";
else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
}
session.setAttribute(visitCountKey, visitCount);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(“id:”+ session.getID() +”\n”+ “Creation Time”
+ createTime +”\n” + “Time of Last Access: ”+
lastAccessTime + “\n” + “Number of visits: ” +visitCount);
}
}

You might also like