0% found this document useful (0 votes)
14 views

UNIT6

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

UNIT6

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Unit 6- Servlet Programming

CO: 22517.f:Develop a program using Servlet

JAVA SERVLETS
In the early days, web servers only deliver static contents (all contents appearing on Web pages is
placed manually by the web developers) in response to a client’s request. Then Java servlets came into
picture which is server-side programs that handle client’s requests and return a dynamic page as a
response for each request. This dynamic response could be based on user's input. The pages are called
“dynamic” because their content is generated “on the fly” each time a page is requested by the web
site visitor.

In order to dynamically generate the web page on the server side ,web server uses Servlet containers.
A Servlet container can have one or more servlets. So it act as a container for servlets. Java servlets
typically run on the HTTP protocol. As we know that HTTP is an asymmetrical request-response
protocol. Its means that client sends a request message to the server, and the server returns a response
message as illustrated in fig .A Java Servlet is a Java object that responds to HTTP requests. It runs
inside a Servlet container.

Servlet inside a java servlet container

A Java web application can contain one or more servlets and other components also like Java Server
Pages (JSP), Java Server Faces (JSF) and Web Services. A Servlet container can run multiple web
applications at the same time.

SERVLET VS. CGI


CGI (Common Gateway Interface) is the very first attempt to provide dynamic contents to users. It
allows users to execute a program that resides in the server to process data and even access databases
in order to produce the relevant content as shown in fig. Since these are programs, they are written in
the native operating system and then stored in a specific directory.

Prepared By:Vaishali c.Sanap Page 1


Unit 6- Servlet Programming

A servlet is an implementation of Java that aims to provide the same service as CGI does, but instead
of programs compiled in the native operating system, it compiles into the Java bytecode which is then
run in the Java virtual machine as shown below.
Java source code Java Compiler Byte code JVM Machine code
(.java file) (.class file)

Following table demonstrate the differences between CGI and Servlet.


CGI Servlet
1 CGI creates a new process for each request Servlet creates a thread for each request and
services the request in that thread.
2 For each process created by CGI the No separate address space is created for
process is assigned separate address space. every thread created by servlet . All threads
operate in the same parent process address
space
3 CGI cannot directly link to Web server. Servlets can link directly to the Web server.
4 CGI does not provide sharing property. Servlets can share data among each other.
5 CGI cannot perform session tracking and Servlets can perform session tracking and
caching of previous computations. caching of previous computations.
6 CGI programs are platform dependent and Servlets are platform independent and
not portable portable
7 In CGI, each request is handled by a In Servlets, the Java Virtual Machine stays
heavyweight operating system process. up, and each request is handled by a
lightweight Java thread.
8 CGI cannot automatically parse and decode Servlets automatically parse and decode the
the HTML form data. HTML form data.
9 CGI cannot read and set HTTP headers, Servlets can read and set HTTP headers,
handle cookies, tracking sessions. handle cookies, tracking sessions.
10 CGI is more expensive than Servlets Servlets is inexpensive than CGI.

SERVLET API
The Servlet API comes in Two Java packages. The packages are as follows.

1.javax.servlet
The javax.servlet package is used for serving protocol-less requests. It contains the interfaces and
classes that every servlet must implements and extends respectively. Every servlet must implement
the Servlet interface in one form or another. The abstract GenericServlet class provides the framework
for developing basic servlets. Following table lists some of the interfaces and classes of javax.servlet
package.

Sr. no. Interfaces Classes


1 Servlet GenericServlet

Prepared By:Vaishali c.Sanap Page 2


Unit 6- Servlet Programming

2 ServletRequest ServletInputStream
3 ServletResponse ServletOutputStream
4 RequestDispatcher ServletRequestWrapper
5 ServletConfig ServletResponseWrapper
6 ServletContext ServletRequestEvent
7 SingleThreadModel ServletContextEvent
8 Filter ServletRequestAttributeEvent
9 FilterConfig ServletContextAttributeEvent
10 ServletRequestListener ServletException

2. javax.servlet.http.
The javax.servlet.http package is used for the development of servlets that use the HTTP protocol.
The abstract HttpServlet class extends javax.servlet.GenericServlet and serves as the base class for
HTTP servlets. HttpServletRequest and HttpServletResponse interfaces allow additional interaction
with the client. This package also includes HttpSession and some related classes to support session
tracking. Following table lists some of the interfaces and classes of javax.servlet.http package.

Sr. no. Interfaces Classes


1 HttpServletRequest HttpServlet
2 HttpServletResponse Cookie
3 HttpSession HttpServletRequestWrapper
4 HttpSessionListener HttpServletResponseWrapper
5 HttpSessionAttributeListener HttpSessionEvent
6 HttpSessionBindingListener HttpSessionBindingEvent
7 HttpSessionActivationListener HttpUtils (deprecated now)

SERVLET LIFE CYCLE


To better understand the behavior of servlets, let’s take a look at the life cycle of servlets. A servlet is
basically a small Java program that runs within a Web server. It can receive requests from clients and
return responses. The whole life cycle of a servlet breaks up into 3 phases:
1. Initialization: when a servlet is requested by the corresponding clients it is first loaded and
initialized. For example opening files or establishing connections to the servers takes place.
2. Service: After initialization, the servlet serves the client’s request i.e. implements the
application logic of the web application.
3. Destruction: When all requests are processed and the servlet is idle for a specific amount of
time, It is destroyed by the server and all the resources are released.

A servlet's life cycle is managed via the init(), service() and destroy() methods.

Prepared By:Vaishali c.Sanap Page 3


Unit 6- Servlet Programming

A web server communicates with a servlet through a simple interface javax.servlet.Servlet which
comprised of following methods:
• init()
• service()
• destroy()

The init() Method


When a servlet is first loaded, its init () method is invoked. This allows the servlet to perform setup
processing such as opening files or establishing connections to their servers.

The init() method is guaranteed to finish before any other calls are made to the servlet--such as a call
to the service() method.

Note that init() will only be called once; it will not be called again unless the servlet has been
unloaded and then reloaded by the server.

The service() Method


Once a servlet is initialized, the servlet container invokes its service() method to handle client
requests. This method is called once for each request. Generally, the servlet container handle
concurrent request to the same servlet by running service() on different threads.

The syntax of this method is


public void service(ServletRequest request,ServletResponse response)
throws ServletException, IOException
{
}
The server creates ServletRequest,ServletResponse interface objects. Where ServletRequest interface
object is used for sending client information to the server and ServletResponse interface object is
used for sending response to the client.

For HttpServlet, service() method dispatches doGet(), doPost() to handle HTTP GET, POST, request
respectively.

The syntax of service() method of an HttpServlet is as follows:


public void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
}

The service () method is called by the container which will invokes doGet, doPost, doPut, doDelete,
etc. methods depending on what type of request. So you have to override either doGet() or doPost()
etc. methods

The doGet() Method:


When user submit some form data and that form is using GET method then this type of request is
handled by doGet() method or when a HTML form has no METHOD specified then also it is handled
by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
// Servlet code
}
The doPost() Method:

Prepared By:Vaishali c.Sanap Page 4


Unit 6- Servlet Programming

When user submit some form data and that form is using POST method then this type of request is
handled by doPost() method .
public void doPost(HttpServletRequestrequest,HttpServletResponse response)
throwsServletException, IOException {
// Servlet code
}

The destroy() Method


The destroy() method is called to allow your servlet to clean up any resources (such as open files or
database connections) before the servlet is unloaded. If you do not require any clean-up operations,
this can be an empty method.

WRITING AND RUNNING SIMPLE SERVLET


There are three different ways to create a servlet.
1. By implementing Servlet interface
2. By extending GenericServlet class
3. By extending HttpServlet class

But mostly a servlet is created by extending HttpServlet abstract class. HttpServlet gives the
definition of service() method of the Servlet interface. The servlet class that we will create will not
override service() method but it will override only doGet() or doPost() method.

When a request comes in for the servlet, the service () method is called by the container which will
invokes doGet, doPost methods depending on what type of request.

Now we will see the steps for writing servlet by extending HttpServlet class using netbeans IDE
which is using apache tomcat as Server.To create a servlet application in Netbeans IDE, you will need
to follow the following steps
Open Netbeans, Select file -> New Project
Select Java Web -> Web Application, then click on next as shown below

3.Give a name to your project and click next

Prepared By:Vaishali c.Sanap Page 5


Unit 6- Servlet Programming

4.As you finished the wizard ,you will see WebApp Project directory is created in project tab. To
create a servlet, right click on Source Package -> New -> Servlet as shown below.

5.Give a name to your servlet class file and click on next.On next screen select the check box” Add
information to deployment descriptor(web.xml) and select finish as shown below

Prepared By:Vaishali c.Sanap Page 6


Unit 6- Servlet Programming

6. Above step would create a web.xml file in WEB-INF folder and Format of web.xml file given
below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd">
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>
</web-app>

SERVLET INTERFACE
Servlet interface provides common behaviour to all the servlets. Servlet interface needs to be
implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods
that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life
cycle methods.

Methods of Servlet interface


There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of
servlet. These are invoked by the web container.

Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle method
of servlet and invoked by the web container
only once.
public void service(ServletRequest provides response for the incoming request. It
request,ServletResponse response) is invoked at each request by the web container.
public void destroy() is invoked only once and indicates that servlet
is being destroyed.

Prepared By:Vaishali c.Sanap Page 7


Unit 6- Servlet Programming

public ServletConfig getServletConfig() returns the object of ServletConfig.


public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.

Example:
import java.io.*;
import javax.servlet.*;

public class First implements Servlet


{
ServletConfig config=null;

public void init(ServletConfig config)


{
this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException
{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");

}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1016";}

GENERICSERVLET CLASS
GenericServlet class implements Servlet,ServletConfig and Serializable interfaces. It provides the
implementaion of all the methods of these interfaces except the service method. GenericServlet class
can handle any type of request so it is protocol-independent. You may create a generic servlet by
inheriting the GenericServlet class and providing the implementation of the service method.
Following table lists some of the methods of GenericServlet class.

Sr. Method Description


no.
1 public void init(ServletConfigconfig) Invoked only once .Used to initialize
the servlet.
2 public abstract void service(ServletRequest Provides service for the incoming
request, ServletResponse response) request. It is invoked at each time
when user requests for a servlet.
3 public void destroy() Invoked only once .Indicates that
servlet is being destroyed.
4 Public ServletConfig getServletConfig() Returns the object of ServletConfig.

Prepared By:Vaishali c.Sanap Page 8


Unit 6- Servlet Programming

5 public String getServletInfo() returns information about servlet like


writer, copyright, version etc.
6 public ServletContext get ServletContext() Returns the object of ServletContext.
7 public String getInitParameter(String name) Returns the parameter value for the
given parameter name.

8 public Enumeration Returns all the parameters defined in


getInitParameterNames() the web.xml file.

9 public String getServletName() Returns the name of the servlet object.

10 public void log(String msg) Writes the given message in the servlet
log file.
11 public void log(String msg,Throwable t) Writes the explanatory message in the
servlet log file and a stack trace.

Example:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;

public class NewServlet1 extends GenericServlet


{

public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException


{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");

}
}

HTTPSERVLET CLASS
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It
provides http specific methods such as doGet, doPost, doHead, doTrace etc.
Following table lists some of the methods of HttpServlet class.

Sr. Syntax Description


no.
1 public void service(ServletRequest Dispatches the request to the protected
req,ServletResponse res) service method by converting the request and
response object into http type.
2 protected void service(HttpServletRequest Receives the request from the service
req, HttpServletResponse res) method, and dispatches the request to the

Prepared By:Vaishali c.Sanap Page 9


Unit 6- Servlet Programming

doXXX() method depending on the incoming


http request type.
3 protected void doGet(HttpServletRequest req, Invoked by the web container and handles
HttpServletResponse res) the GET request.
4 protected void doPost (HttpServletRequest Invoked by the web container and handles
req, HttpServletResponse res) the POST request.
5 protected void doHead (HttpServletRequest Invoked by the web container and handles
req, HttpServletResponse res) the HEAD request.
6 protected void doOptions Invoked by the web container and handles
(HttpServletRequest req, HttpServletResponse the OPTIONS request.
res)
7 protected void doPut (HttpServletRequest req, Invoked by the web container and handles
HttpServletResponse res) the PUT request.
8 protected void doTrace (HttpServletRequest Invoked by the web container and handles
req, HttpServletResponse res) the TRACE request.
9 protected void doDelete (HttpServletRequest Invoked by the web container and handles
req, HttpServletResponse res) the DELETE request.
10 protected long getLastModified Returns the time when HttpServletRequest
(HttpServletRequest req) was last modified since midnight January 1,
1970 GMT.

Example:

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

public class HelloWorldServlet extends HttpServlet


{
private String message;

public void init() throws ServletException


{
message = "Hello World";// Do required initialization
}

public void doGet(HttpServletRequest request,HttpServletResponse response)


throws ServletException, IOException
{
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy()


{
// do nothing.
}
}

Here you can see that a HelloWorldServlet class is extended from HTTPServlet class and overriding
init(),doGet() and destroy() methods.
To run the file select “HelloworldServlet.java” in Project tab and right click on it and select “Run
File” and you will get following outcome:

Prepared By:Vaishali c.Sanap Page 10


Unit 6- Servlet Programming

WRITING SERVLET TO HANDLE GET AND POST METHOD


Handling form data in any HTML page is a very common task in web application. A typical example
is the user fills in fields of a form and submits it. The server will process the request based on the
submitted data, and send response back to the client. The following picture shows that flow how a
form data is processed with Java servlet on the server side:

To create a form in HTML we need to use some of the HTML tags like:
o <form>: to create a form.
o <input>, <select>, <textarea>…: to create form fields like text boxes, dropdown list, text
area, check boxes, radio buttons,… and submit button.

You need to specify the following attributes for the <form> tag to works with Java servlet.

o method=”post”: to send the form data as an HTTP POST request to the server. Generally,
form submission should be done in HTTP POST method. And the code inside the doPost
method in servlet class will get executed
or
method=”get”:to send the form data as an HTTP GET request to the server and the code
inside the doGet method in servlet class will get executed

o action=”URL of the servlet”: specifies relative URL of the servlet which is responsible for
handling data posted from this form.

Prepared By:Vaishali c.Sanap Page 11


Unit 6- Servlet Programming

Example1: Calling doGet() method using form GET Method


1. Write following code in HTML page
<html>
<head>
</head>
<body>
<FORM Method=GET Action="MyServlet3">
Enter your Name: <input type=text size=45 name=user>
<input type=submit value=SUBMIT>
</FORM>
</body>
</html>
As the <form Method=GET > so the doGet() method in MyServlet3 get executed. If you change it by
<form Method=POST >the doPost() method in MyServlet3 get executed.
2. Write following code in Servlet class
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet3 extends HttpServlet


{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user=request.getParameter("user");
out.println("<h2> Welcome "+user+"</h2>");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user=request.getParameter("user");
out.println("<h2> Hello "+user+"</h2>");
}
}

Prepared By:Vaishali c.Sanap Page 12


Unit 6- Servlet Programming

Output
Hello <Username entered by user>

Example2: Calling doPost() method using form POST Method


1. Write following code in HTML page
<html>
<head>
</head>
<body>
<FORM Method=POST Action=" MyServlet4">
Enter your Name: <input type=text size=45 name=user>
<input type=submit value=SUBMIT>
</FORM>
</body>
</html>
As <form Method=POST >the doPost() method in MyServlet4 get executed.
2. Write following code in Servlet class
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet4 extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user=request.getParameter("user");
out.println("<h2> Welcome "+user+"</h2>");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user=request.getParameter("user");
out.println("<h2> Hello "+user+"</h2>");
}

Prepared By:Vaishali c.Sanap Page 13


Unit 6- Servlet Programming

Output:
Welcome <username entered by user>

Example 3: calling doGet() method and doPost() method


1. Write following code in HTML page
<html>
<head>
</head>
<body>
<FORM Method=GET Action=" MyServlet5">
Enter your Name: <input type=text size=45 name=user>
<input type=submit value=SUBMIT>
</FORM>
</body>
</html>
2. write following code in Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet5 extends HttpServlet


{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user=request.getParameter("user");
out.println("<h2> Welcome "+user+"</h2>");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user=request.getParameter("user");

Prepared By:Vaishali c.Sanap Page 14


Unit 6- Servlet Programming

out.println("<h2> Hello "+user+"</h2>");


doPost(request,response);
}
}

In this as <form Method=GET> so doGet() method of servlet class will called and at the end of this
method we are calling doPost method .So both going to execute and you will get following outcome.

COOKIES IN SERVLET
A cookie is a small piece of information that is persisted between the multiple client requests. 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.

How Cookie works?


By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent
by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie: It is valid for single session only. It is removed each time when user
closes the browser.
2. 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.
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.

Prepared By:Vaishali c.Sanap Page 15


Unit 6- Servlet Programming

 Only textual information can be set in Cookie object.

COOKIE CLASS

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful
methods for cookies.

Methods of Cookie class


Methods Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot be
changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to


add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all
the cookies from the browser.

Example:

Index.html file

<html>

<head>

<title>TODO supply a title</title>

</head>

<body>

<form name="aa" method="Post" action="NewServlet">

Prepared By:Vaishali c.Sanap Page 16


Unit 6- Servlet Programming

name<input type="text" name="uid">

value <input type="text" name="pv">

<input type ="submit" value="cookie">

</form>

</body>

</html>

NewServlet.java file

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class NewServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

try (PrintWriter out = response.getWriter()) {

out.println("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");

out.println("<title>AK</title>");

out.println("</head>");

out.println("<body>");

String n=request.getParameter("uid");

String v=request.getParameter("pv");

Cookie c=new Cookie(n,v);

response.addCookie(c);

out.println("cookies added");

c.setMaxAge(60*90);

Prepared By:Vaishali c.Sanap Page 17


Unit 6- Servlet Programming

out.println("max age of cookies"+c.getMaxAge());

Cookie c1[]=request.getCookies();

for (int i=0;i<=c1.length;i++)

out.println("name="+c1[i].getName());

out.println("value="+c1[i].getValue());

out.println("</body>");

out.println("</html>");

} }}

SESSION TRACKING IN SERVLET


HTTP protocol and Web Servers are stateless, what it means is that , web server is not aware that
what exactly served in previous request. Every request is treated as new request and they can’t
identify if it’s coming from client that has been sending request previously.
But sometime you need to keep track of client activity across multiple request i.e storing session
information for a particular client.
Session is a conversional state between client and server and it can consist of multiple request and
response between client and server.
Since HTTP and Web Server both are stateless, the only way to maintain a session is when some
unique information about the session (session id) is passed between server and client in every request
and response.

Prepared By:Vaishali c.Sanap Page 18


Unit 6- Servlet Programming

There are Five different techniques used by Servlet application for session management. These are:
A. User Authentication – This is one of the common way to maintain a session between client and
server. In this method user provides authentication credentials on a login page and then this
authentication information between server and client is used to maintain the session. This is not
very effective method as it wont work if the same user is logged in from different browsers.
B. HTML Hidden Field – we can make some of the fields/ controls to hidden i.e. these are not
visible when the application is viewed in the browser. It acts as a storage area for storing any
page specific information. We can create a unique hidden field in the HTML and when user
starts navigating, we can set its value unique to the user and keep track of the session. This
method can’t be used with links and it’s not secure as one can get the hidden field value from the
HTML source.
C. URL Rewriting – In this method the information in form of string added at the end of the URL
to maintain the state of a web application. Most dynamic sites include string variables in their
URLs that tell the site what information to show the user.This is very tedious because we need to
keep track of this parameter in every response and make sure it’s not clashing with other
parameters.
D. Cookies – Cookies are small piece of information that is sent by web server in response header
and gets stored in the browser cookies. When client make further request, it adds the cookie to
the request header and we can utilize it to keep track of the session. This method would not work
if the client has disables the cookies.
E. Session Management API –Some of programming languages provides APIs for session
tracking. In java the javax.servlet.http package provides HttpSession interface which can be
used to get a sessionid. .An object of HttpSession can be used to view and manipulate
information about a session, such as the session identifier, creation time, and last accessed time.

Session Management with HttpSession


The servlet container uses HttpSession 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 request from the user . Following figure shows how it works.

Prepared By:Vaishali c.Sanap Page 19


Unit 6- Servlet Programming

Request,”Meena” new Server


Client Web
container ID:121
setattribute “meena
Response, 121

Request,121 Matching

1. On client's first request, the Web Container generates a unique session ID and gives it back to
the client with response.
2. The client sends back the session ID with each request.
3. The Web Container uses this ID, finds the matching session with the ID and associates the
session with the request.

An object that implements HttpSession interface is created by the servlet container and returned when
the getSession () method of HttpServletRequest is called. The HttpSession object provides methods
to read, add, and remove various session data as well as methods to view session information such as
the session identifier, creation time, and the time the session was last accessed. The syntax of
getSession() method is as follows:

A. HttpSession getSession() – This method always returns an object of HttpSession. It returns the
current session associated with this request, if the request has no session attached, then it creates
a new session and return it.
B. HttpSession getSession(boolean flag) – This method returns HttpSession object if request has
session else it returns null.

Example: Session Tracking


In following example we are passing the value of username and password to ValidateServlet class,
which then check the password value if it is “1234” then response will be redirected to
WelcomeServlet page ,which will show hello <username>.So in this way a session is maintained in
between the pages.
1. Write following code in HTML file
<html>
<body>
<form method="post" action="ValidateServlet">
User:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" ><br/>
<input type="submit" value="submit">

Prepared By:Vaishali c.Sanap Page 20


Unit 6- Servlet Programming

</form>
</body>
</html>

2. Write following code in ValidateServlet class


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

public class ValidateServlet extends HttpServlet


{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("WelcomeServlet");
}
else
{
PrintWriter out = response.getWriter();
out.println("Wrong password ");
out.close();
}
}
}

3. Write Following code in WelcomeServlet class


public class WelcomeServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)

Prepared By:Vaishali c.Sanap Page 21


Unit 6- Servlet Programming

throws ServletException, IOException


{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String)session.getAttribute("user");
out.println("Hello "+user);
out.close();
}
}

Prepared By:Vaishali c.Sanap Page 22

You might also like