[go: up one dir, main page]

0% found this document useful (0 votes)
21 views113 pages

Chap 3

Uploaded by

chandanaa0210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views113 pages

Chap 3

Uploaded by

chandanaa0210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

CHAPTER – 3 SERVELTS

V BCA
Module III: Java Servlets
Life Cycle of a Servlet
Using Tomcat for Servlet
Development

A Simple Servlet
The Servlet API
Servlet packaging
What is a Java Servlet?

❑Servlets are small programs that execute on the server side of a


Web connection
❑A java servlets is a java object that responds to HTTP requests, It
runs inside a servlet container.
❑A servlet container is capable to run multiple web applications at
the same time, each having multiple servlets running inside.
Life cycle of a Servlet
init() method
Three methods are central
to the life cycle of a servlet

service() method

destroy() method
SERVLET LIFE CYCLE

 A servlet, from its creation to destruction, undergoes a


number of states as:
 Instantiated or born
Initialized
 Ready to service
Servicing
 Dead or destroyed
SERVLET LIFE CYCLE (CONTD.)
SERVLET LIFE CYCLE (CONTD.)

1. init() method
SERVLET LIFE CYCLE (CONTD.)

1. service() method
SERVLET LIFE CYCLE (CONTD.)

2a. doGet() method

 doGet() shall be used when small amount of data and insensitive data like a query has to be sent as a request.
SERVLET LIFE CYCLE (CONTD.)

 2b. doPost()

doPost() shall be used when comparatively large amount of sensitive data has to be sent.
SERVLET LIFE CYCLE (CONTD.)

 Destroy()
Life Cycle of a Servlet

❑First, assume that a user enters a Uniform Resource Locator


(URL) to a Web browser

❑The browser then generates an HTTP request for this URL. This
request is then sent to the appropriate server

❑Second, this HTTP request is received by the Web server

❑The server maps this request to a particular servlet


Life Cycle of a Servlet

❑The servlet is dynamically retrieved and loaded into the address


space of the server

❑Third, the server invokes the init( ) method of the servlet

❑This method is invoked only when the servlet is first loaded into
memory

❑It is possible to pass initialization parameters to the servlet so it


may configure itself

❑Fourth, the server invokes the service( ) method of the servlet


Life Cycle of a Servlet

❑This method is called to process the HTTP request

❑You will see that it is possible for the servlet to read data that has
been provided in the HTTP request

❑It may also formulate an HTTP response for the client

❑The servlet remains in the server’s address space and is available to


process any other HTTP requests received from clients

❑The service( ) method is called for each HTTP request


Life Cycle of a Servlet

❑Finally, the server may decide to unload the servlet from its
memory

❑The server calls the destroy( ) method to relinquish any


resources such as file handles that are allocated for the
servlet

❑Important data may be saved to a persistent store

❑The memory allocated for the servlet and its objects can then be
garbage collected
USING TOMCAT FOR SERVLET DEVELOPMENT

 It is an open-source Java servlet container that implements many Java Enterprise


Specs such as the Websites API, Java-Server Pages and last but not least, the Java
Servlet.
 It is still one of the most widely used java-sever due to several capabilities such as
good extensibility, proven core engine, and well-test and durable.
A Simple Servlet

❑Basic steps

1. Create and compile the servlet source code.

2. Start Tomcat.

3. Start a Web browser and request the servlet.


A Simple Servlet

❑Create and Compile the Servlet Source Code


import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
A Simple Servlet
❑imports the javax.servlet package. This package contains the classes and
interfaces required to build servlets

❑Program defines HelloServlet as a subclass of GenericServlet

❑The GenericServlet class provides functionality that makes it easy to


handle requests and responses

❑Inside HelloServet, the service( ) method (which is inherited from


GenericServlet) is overridden. This method handles requests from a client

❑First argument is a ServletRequest object. This enables the servlet to


read data that is provided via the client request
A Simple Servlet

❑The second argument is a ServletResponse object. This enables the


servlet to formulate a response for the client
❑The call to setContentType( ) establishes the MIME type of the
HTTP response
❑getWriter( ) method obtains a PrintWriter. Anything written to this
stream is sent to the client as part of the HTTP response

❑Then println( ) is used to write some simple HTML source code as the
HTTP response

❑Compile this source code and place the HelloServlet.class file in the
Tomcat class files directory
A Simple Servlet

❑Start Tomcat

❑To start Tomcat, select Start Tomcat in the Start | Programs


menu, or run startup.bat from the C:\Program Files\Apache
Tomcat 4.0\bin\

❑Start a Web Browser and Request the Servlet

❑Start a Web browser and enter the URL shown here:


http://localhost:8080/examples/servlet/HelloServlet

❑Output of the servlet will be displayed in the browser display area


The Servlet API
❑Interfaces in javax.servlet Package

Interface Description

Servlet Servlet Declares life cycle methods for a servlet.

ServletConfig ServletConfig Allows servlets to get initialization


parameters.

ServletContext ServletContext Enables servlets to log events and access


information
about their environment.

ServletRequest ServletRequest Used to read data from a client request.

ServletResponse ServletResponse Used to write data to a client response.

SingleThreadModel SingleThreadModel Indicates that the servlet is thread safe.


The Servlet API
❑Classes in javax.servlet Package

Class Description

GenericServlet GenericServlet Implements the Servlet and


ServletConfig interfaces.
ServletInputStream ServletInputStream Provides an input stream for
reading requests from a client.

ServletOutputStream ServletOutputStream Provides an output stream for


writing responses to a client.

ServletException ServletException Indicates a servlet error occurred.

UnavailableException UnavailableException Indicates a servlet is unavailable.


The Servlet API

❑Servlet Interface

❑All servlets must implement the Servlet interface

❑It declares the init( ), service( ), and destroy( ) methods that


are called by the server during the life cycle of a servlet

❑A method is also provided that allows a servlet to obtain any


initialization parameters
The Servlet API
❑Servlet Interface

Method Description

void destroy( ) Called when the servlet is unloaded.

ServletConfig getServletConfig( ) Returns a ServletConfig object that


contains any initialization parameters.
String getServletInfo( ) Returns a string describing the servlet

void init(ServletConfig sc) throws Called when the servlet is initialized.


ServletException Initialization parameters for the servlet can
be obtained from sc. An
UnavailableException should be thrown if
the servlet cannot be initialized.
The Servlet API
❑Servlet Interface

Method Description

void service(ServletRequest req, Called to process a request from a client.


ServletResponse res) throws The request from the client can be read
ServletException, IOException from req. The response to the client can
be written to res. An exception is
generated if a servlet or IO problem
occurs.
The Servlet API
❑The ServletConfig Interface

Method Description

ServletContext getServletContext( ) Returns the context for this servlet.

String getInitParameter(String param) Returns the value of the initialization


parameter named param.
Enumeration getInitParameterNames( ) Returns an enumeration of all
initialization parameter names.
String getServletName( ) Returns the name of the invoking servlet.
The Servlet API
❑The ServletRequest
Method Description

Object getAttribute(String attr) Returns the value of the server attribute


named attr.
String getMimeType(String file) Returns the MIME type of file.

String getRealPath(String vpath) Returns the real path that corresponds


to the virtual path vpath.
String getServerInfo( ) Returns information about the server.

void log(String s) Writes s to the servlet log.


The Servlet API
❑The ServletRequest
Method Description

void log(String s, Throwable e) Write s and the stack trace for e to the
servlet log.
void setAttribute(String attr, Object Sets the attribute specified by attr to the
val) value passed in val.
Object getAttribute(String attr) Returns the value of the attribute
named attr.
String getCharacterEncoding( ) Returns the character encoding of
the request.
The Servlet API
❑The ServletRequest
Method Description

int getContentLength( ) Returns the size of the request. The


value –1 is returned if the size is
unavailable.
String getContentType( ) Returns the type of the request. A
null value is returned if the type
cannot be determined.
ServletInputStream Returns a ServletInputStream that can be
getInputStream( ) used to read binary data from the request.
throws IOException AnIllegalStateException is thrown if
getReader( ) has already beeninvoked for
this request.
The Servlet API
❑The ServletRequest
Method Description

String getParameter(String pname) Returns the value of the parameter


named pname.

Enumeration getParameterNames( Returns an enumeration of the


) parameter names for this request.

String[ ] Returns an array containing values


getParameterValues(String name ) associated with the parameter
specified by name
String getProtocol( ) Returns a description of the
protocol
The Servlet API
❑The ServletRequest

Method Description

BufferedReader getReader( ) Returns a buffered reader that can be


throws IOException used to read text from the request. An
IllegalStateException is thrown if
getInputStream( ) has already been
invoked for this Request
The Servlet API
❑The ServletRequest
Method Description

String getRemoteAddr( ) Returns the string equivalent of the


client IP address.

String getRemoteHost( ) Returns the string equivalent of the client


host name.

String getScheme( ) Returns the transmission scheme of the


URL used for the request (for example,
“http”, “ftp”).
String getServerName( ) Returns the name of the server

int getServerPort( ) Returns the port number.


The Servlet API
❑The ServletResponse
Method Description

String getCharacterEncoding( ) Returns the character encoding for the


response.

ServletOutputStream Returns a ServletOutputStream that


getOutputStream( ) can be used to write binary data to the
throws IOException response.
An IllegalStateException is thrown if
getWriter( ) has already been
invoked for this request.
The Servlet API
❑The ServletResponse
Method Description

PrintWriter getWriter( ) Returns a PrintWriter that can be


throws IOException used to write character data to the
. response.
An IllegalStateException is thrown if
getOutputStream( ) has already
been invoked for this request.
void setContentLength(int size) Sets the content length for the response
to size.

void setContentType(String type) Sets the content type for the response to
type.
The Servlet API

❑The GenericServlet Class

❑The GenericServlet class provides implementations of the


basic life cycle methods for a servlet and is typically subclassed
by servlet developers

❑GenericServlet implements the Servlet and ServletConfig


interfaces

❑Method to append a string to the server log file is available


void log(String s)
void log(String s, Throwable e)
Here, s is the string to be appended to the log, and e is an exception
that occurred
The Servlet API

❑The ServletInputStream Class

❑The ServletInputStream class extends InputStream

❑It is implemented by the server and provides an input stream that a


servlet developer can use to read the data from a client request

❑It defines the default constructor. In addition, a method is provided


to read bytes from the stream

❑Methods :- int readLine(byte[] b, int off, int len) it reads the input
stream.
The Servlet API

❑The ServletOutputStream Class

❑The ServletOutputStream class extends OutputStream

❑It is implemented by the server and provides an output stream that


a servlet developer can use to write data to a client response

❑A default constructor is defined. It also defines the print( ) and


println( ) methods, which output data to the stream
The Servlet API

❑The Servlet Exception Classes

❑javax.servlet defines two exceptions

❑First is ServletException, which indicates that a servlet


problem has occurred

❑The second is UnavailableException, which extends


ServletException. It indicates that a servlet is unavailable
Servlet Packaging

Placing all the servlets in the same directory results in


massive, hard-to-manage collection of classes and risks name
conflicts when two developers choose same name for a servlet
or a utility class
When you put your servlets in packages, you need to

Place the files in a subdirectory that makes


the intended package name

Insert a package statement in the


class file

Example: package com;


19.7 GENERICSERVLET

 The class javax.servlet.GenericServlet implements


the javax.servlet.Servlet interface and for convenience,
the javax.servlet.ServletConfig interface.
 A servlet class is usually created by extending either the
GenericServlet class or its descendant
javax.servlet.http.HttpServlet class unless the
servlet needs another class as a parent.
 The GenericServlet class defines a generic protocol
independent servlet, in the sense that it can be extended to
provide implementation of any protocol, such as HTTP, FTP, and
SMTP.
 The GenericServlet class was created to make writing servlets
easier.
19.8 HTTPSERVLET
19.9 FIRST SERVLET

 An IDE is an Integrated Development Environment and it makes


creating applications a lot easier.
 It is the simplest way to create servlet applications.
 It is a software application that provides facilities to computer
programmers for software development.
 Eclipse, MyEclipse, Netbeans are examples of some popular Java
IDEs.
 The installation and configuration of Netbeans IDE and the
creation of servlet applications on Netbeans IDE is dealt with
extensively in the text.
19.10 PASSING PARAMETERS TO SERVLETS
19.11 RETRIEVING PARAMETERS
19.12 Server-side include
Server-Side Include (SSI) allows embedding servlets within
HTML pages. The following directives are used:

❑ echo
❑ Printenv
❑ config
❑ fsize
❑ flastmod
❑ include
❑ set
❑ if elif endif else
19.13 COOKIES

 HTTP is stateless.
 This means that every HTTP request is different from others.
 Sometimes, it is necessary to keep track of a sequence of
related requests sent by a client to perform some designated
task.
This is called session tracking.
Cookies are one of the solutions to session tracking.
COOKIES (CONTD.)

 A cookie is a [key, value] pair created by the server and is


installed in the client’s browser when the client makes a
request for the first time.
 A browser also maintains a list of cookies installed in it and
sends it to the server as a part of subsequent HTTP requests.
LIMITATIONS OF COOKIES

 Cookies work correctly provided the web browsers have


enabled cookie support.
 Cookies can carry small pieces of information and are not a
standard means of communication.
 Web browsers limit the number of cookies to 20 per web
server.
 The value of a cookie should never exceed 4 KB.
 Cookies cannot identify a particular user.
 Intruders can snoop, steal cookies and attack sessions. This is
called session hijacking.
19.14 FILTERS

 Filters are objects that are installed between the client and the
server to inspect requests and responses.
 They can transform the request or modify the response or
both.
 The filters are not servlets and hence cannot create actual
responses.
 Filters process requests before they reach a servlet and/or
process responses after leaving a servlet.
FILTERS (CONTD.)

 A filter can do the following:


 Intercept and inspect requests before dispatching them
to the servlets.
 Modify requests’ headers and data and discard or filter
requests.
 Intercept and inspect responses before dispatching to the
clients.
 Modify requests’ headers and data and discard or filter
responses.
FILTERS (CONTD.)

 A filter can work on behalf of a single servlet or a group of


servlets.
 Filters are typically used in the following areas:
 Authentication
 Logging and auditing
 Image compression
 Data compression
 Encryption
 Tokenization
 XML transformation
19.15 PROBLEMS WITH SERVLETS

 Servlets are not useful for generating presentation content such as HTML. If the size of the
HTML document is large, it is a tedious process.
 Another drawback of the servlet over Java Server Pages (JSP) is that the source has to be
recompiled after any modification is done.
 Moreover, the web server has to be restarted to see the effect of the modified code.
However, JSP can perform these tasks automatically.
 Servlets often contain presentation logic as well as processing logic, which makes the code
difficult to read, understand and extend. If the presentation logic changes, the servlet code
has to be modified, recompiled, and redeployed.
19.16 SECURITY ISSUES

 A sandbox is a container of servlets where restrictions are imposed.


 Take sufficient care while writing the file upload code. If not implanted carefully, users
may fill the hard disk of the server by uploading large files.
 Review the code that accesses files/database based on the user input. For example,
do not allow users to execute arbitrary SQL commands.
 If allowed, users may fire some harmful SQL commands that could delete database
tables.
Let’s memorize

Life Cycle of Servlet

Using Tomcat for Servlet


Development
A Simple Servlet

The Servlet API

Servlet Packaging
Here you’ll learn about

HTML building utilities

Single Thread Model Interface

Handling Client Request: Form Data

Handling Client Request: HTTP Request


Headers
HTML Building Utilities

An HTML document is structured as follows:

<!DOCTYPE> tells the HTML validators which version of


HTML you are using
These validators are valuable debugging services, such as syntax
errors in HTML
HTML Building Utilities

Most Popular online validators are


❑World wide web consortium
(http://validator.w3.org)

❑Web Design Group

(http://www.htmlhelp.com/tools/validator)

To generate HTML with println statements, especially


long tedious lines like DOCTYPE declaration
HTML Building Utilities
Single Thread Model Interface

The servlet programmer should implement SingleThreadModel


interface to ensure that servlet can handle only one request at a
time

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

You don’t have to worry about simultaneous access to regular


fields (instance variables) of the servlet
Single Thread Model Interface
Syntax

public class MyServlet extends HttpServlet implements


SingleThreadModel{

}

Note: This interface is currently deprecated since Servlet API 2.4


because it doesn't solves all the thread-safety

So it is recommended to use other means to resolve these thread


safety issues such as synchronized block
Handling Client Request: Form Data
Handling Client Request

❑Whenever we want to send an input to a servlet that input


must be passed through html form

❑Every form will accept client data and it must send to a


servlet which resides in server side

❑Since html is a static language which cannot validate the client


data. Hence, in real time applications client data will be accepted
with the help of html tags by developing form and every form must
call a servlet
Handling Client Request: Form Data
Form Data

❑Form data can be attached to the end of the URL after a question
mark for GET requests, or send to the server on a separate line for
POST requests
Handling Client Request: Form Data
Reading form data from servlets

❑getParameter()

❑getParameterValues()

❑getParameterNames()
Handling Client Request: Form Data
Reading form data from servlets
Handling Client Request: Form Data
Reading form data from servlets
Handling Client Request: Form Data
Reading form data from servlets
Handling Client Request: HTTP
Request Headers
HTTP Request Headers
❑HTTP information that is sent from the browser to the server in
the form of request headers

❑HTTP request headers are distinct from the form data

❑Form data results directly from user input and is sent as part of
the URL for GET requests and on a separate line for POST requests

❑Request headers, on the other hand, are indirectly set by the


browser and are sent immediately following the initial GET or POST
request line
Handling Client Request: HTTP
Request Headers
Reading Request headers from Servlet
❑Header names are not case sensitive

❑List of headers that are generally used are:


Handling Client Request: HTTP Request Headers
Reading Request headers from Servlet
HTTP Request Headers
HTTP 1.1 Request Headers
HTTP Request Headers

HTTP 1.1 Request Headers


HTTP Request Headers
Let’s memorize

HTML building utilities

Single Thread Model Interface

Handling Client Request: Form Data

Handling Client Request: HTTP


Request Headers
Here you’ll learn about

Generating Server Response:


HTTP Status Codes

Generating Server Response:

HTTP Response Headers


Generating Server Response: HTTP
Status Codes
❑When a web server responds to a request from a browser, the
response typically consists of a status line, some response headers,
a blank line, and the document
❑Example
Generating Server Response: HTTP
Status Codes
❑HTTP response status line consists of an HTTP version, a status
code, and an associated message
❑Message is directly associated with the status code and the HTTP
version is determined by the server

❑All the servlet needs to do is to set the status code by setStatus


method of HttpServletResponse

❑If your response includes a special status code and a document,


be sure to call setStatus before actually returning any of the content
via PrintWriter
Generating Server Response: HTTP
Status Codes
Generating Server Response: HTTP
Status Codes
HTTP 1.1 Status Codes
Status code Constant
Description
& Message Name
200 SC_OK A value of 200 means that everything is fine.
204 SC_NO_CONTEN Browser should keep displaying previous document, no new document
T
is available
400 SC_BAD_REQUE status indicates bad syntax in the client request.
ST
401 SC_UNAUTHOR signifies that the client tried to access a password-protected page
IZED without proper identifying information in the Authorization header. The
response must include a WWW-Authenticate header.
404 SC_NOT_FOUN This value is the standard “no such page” response.
D
503 SC_SERVICE_UN signifies that the server cannot respond because of maintenance or
AVAILABLE overloading
504 SC_GATEWAY_T is used by servers that act as proxies or gateways;.
IMEOUT
Generating Server Response: HTTP
Response Headers
❑The most general way to specify headers is to use the setHeader
method of HttpServletResponse

❑Syntax:
public void setHeader(string headername, int headervalue)
❑Example: response.setHeader(“Refresh”, 5);

❑You must set the headers before the first use of the PrintWriter or
OutputStream that transmits the document content
Generating Server Response: HTTP
Response Headers
❑HttpServletResponse also has two specialized methods to set
headers that contain dates and integers

❖ setDateHeader(String header, long milliseconds)


❖ setIntHeader(String header, int headerValue)

❑Example: response.setHeader(“Refresh”, 5);


Generating Server Response: HTTP
Response Headers
❑HttpServletResponse also supplies a number of methods for
specifying common headers
Methods Meaning

setContentType() • sets the Content-Type header(MIME)


• used by the majority of servlets

setContentLength() • sets the Content-Length header


• used for persistent (keep-alive) HTTP connections.

addCookie() Adds a value to the Set-Cookie header

sendRedirect() Sets Location header (as well as sets the status code)
HTTP 1.1 Response Headers
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.
Connection instructs the browser whether to use persistent in HTTP connections or not.

Content-Encoding indicates the way in which the page was encoded during transmission.
HTTP 1.1 Response Headers
Header Name Meaning
Content-Language This header signifies the language in which the document is written. 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.
HTTP 1.1 Response Headers

Header Name Meaning


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
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.
Set-Cookie This header specifies a cookie associated with the page.
Server, Retry –After, Trailer, Transfer- Encoding, WWW-Authenticate
Let’s memorize

Generating Server Response:

HTTP Status Codes

Generating Server Response:

HTTP Response Headers


Here you’ll learn about

Handling Cookies

Session Tracking
Handling Cookies

Cookies are small bits of textual information that a web server sends
to a browser and that browser returns unchanged when later visiting
the same website or domain

Cookies are text files stored on the client computer and they are
kept for various information tracking purpose

Java Servlets transparently supports HTTP cookies


Handling Cookies
Benefits of Cookies

❑Identifying a user during an e-commerce

❑Avoiding username and password

❑Customizing a site

❑Focusing advertising
Handling Cookies

Problems with Cookies

❑Cookies are not a serious security threat but they can present a
significant threat to privacy

❑Cookies are never interpreted or executed in any way and thus


cannot be used to insert viruses or attack your system

❑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
Handling Cookies

javax.servlet.http.Cookie class provides the functionality of using


cookies
Call the Cookie constructor with a cookie name and a cookie value

Constructors Description

Cookie( ) Construct cookie

Cookie(String name, String Constructs a cookie with a specified name


value) and value
Handling Cookies

Before adding the cookie to the outgoing headers, you can set
various characteristics of the cookie by using
setXxx methods
getXxx methods

where Xxx is the name of the attribute you want to


specify
Handling Cookies
Methods Description
public String getComment( ) These methods look up or specify a comment associated with
the cookie.
public void setComment(String The comment is used purely for informational purposes on the
comment) server; it is not sent to the client
public String getDomain( ) These methods get or set the domain to which the cookie
public void setDomain(String applies. the browser only returns cookies to the exact same
domainPattern) hostname that sent them.
public int getMaxAge( ) These methods tell how much time (in seconds) should elapse
before the cookie expires.
public void setMaxAge(int lifetime) • A negative value, which is the default, indicates that the
cookie will last only for the current session and will not be
stored on disk.
• value of 0 instructs the browser to delete the cookie.

public String getName( ) This pair of methods gets or sets the name of the cookie.
public void setName(String
cookieName)
Handling Cookies

Methods Description
public String getPath( ) These methods get or set the path to which the cookie applies. If you
public void setPath(String don’t specify a path, the browser returns the cookie only to URLs in or
path) below the directory containing the page that sent the cookie.
public boolean getSecure( ) This pair of methods gets or sets the Boolean value indicating whether
public void setSecure(boolean the cookie should only be sent over encrypted (i.e., SSL) connections.
secureFlag) The default is false; the cookie should apply to all connections.

public String getValue( ) The getValue method looks up the value associated with the cookie;
public void setValue(String The setValue method specifies it.
cookieValue)

public int getVersion( ) These methods get/set the cookie protocol version the cookie complies
public void setVersion(int with. Version 0, the default, follows the original Netscape specification
version) Version 1, not yet widely supported
Handling Cookies
Creating Cookie

1. Creating a new Cookie


Cookie ck = new Cookie(“username”, value);

2. Setting up lifespan for cookie


ck.setMaxAge(30*60);

3. Sending the cookie to the client


response.addCookie(ck);

4. Getting cookies from client request


Cookie ck[ ] = request.getCookies();
Handling Cookies

5. Iterating through the array of cookies

Cookie[ ] ck = request.getCookies( );
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue();
}
6. Removing Cookies
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
Session Tracking

Session Tracking is a way to maintain state (data) of an user

HTTP is a stateless protocol

All requests and responses are independent

But sometimes you need to keep track of client's activity


across multiple requests

For example, When a User logs in to website, no matter on which


web page he visits after logging in, his credentials will be with the
server, until he logs out. So this is managed by creating a session
Session Tracking

Session Management is a mechanism used by the Web


container to store session information for a particular user
Session Tracking

There are four different techniques used by Servlet application


for session management

1. Cookies

2. URL- Rewriting

3. Hidden form fields

4. HttpSession
Session Tracking

1. Cookies ❑Cookies are small pieces of information that are sent in response from
the web server to the client

❑Cookies are stored on client's computer. They have a lifespan and are
destroyed by the client browser at the end of that lifespan

Advantage of cookie

❑Cookies are maintained at client side

❑Simplest technique of maintaining the state


Session Tracking

Disadvantage of cookie

❑It will not work if cookie is disabled from the browser

❑Only textual information can be set in Cookie object


Session Tracking

2. URL- Rewriting

❑If the client has disabled cookies in the browser then


session management using cookie wont work

❑In that case URL Rewriting can be used as a backup

❑In URL rewriting, a token(parameter) is added at the end of


the URL. The token consist of name/value pair separated by
an equal(=) sign
Session Tracking

❑When the User clicks on the URL having parameters, the


request goes to the Web Container with extra bit of
information at the end of URL

❑The getParameter() method is used to get the parameter


value at the server side
Advantage of URL-Rewriting

❑It will always work whether cookie is disabled or not


(browser independent)

❑Extra form submission is not required on each pages


Session Tracking

Disadvantage of URL-Rewriting

❑It will work only with links

❑It can send Only textual information


Session Tracking

3. Hidden form fields

❑Hidden form field can also be used to store session information


for a particular client

❑User information is stored in hidden field value and retrieved


from another servlet

<INPUT TYPE="HIDDEN" NAME="session" VALUE=“username">


Session Tracking

Advantage of Hidden form fields


❑Does not have to depend on browser whether the cookie is
disabled or not

❑Inserting a simple HTML Input field of type hidden is


required. Hence, its easier to implement

Disadvantage of Hidden form fields

❑Extra form submission is required on every page. This is a


big overhead
Session Tracking

4. HTTP Session
❑HttpSession object is used to store entire session with a
specific client

❑We can store, retrieve and remove attribute


from HttpSession object

❑Any servlet can have access to HttpSession object throughout


the getSession() method of the HttpServletRequest object
Session Tracking

Creating a session
HttpSession session =request.getSession();
// getsession() method returns a session. If the session already
exists, it returns the existing session else create a new session

HttpSession session = request.getSession(true);


// getsession(true) always returns new session

Getting a pre-existing session


HttpSession session = request.getSession(false);
//getSession(false)will check existence of session, If session exists,
then it returns the reference of that session object, if not, this
methods will return null
Session Tracking

Destroying a session
session.invalidate( ); //destroy a session
Session Tracking

Methods in HTTP Session class


1 public Object getValue(String name)
public Object getAttribute(String name)

These methods extract a previously stored value from a session object. They return null if there is no
value associated with the given name. getAttribute is preferred and getValue is deprecated.
2 public void putValue(String name, Object value)
public void setAttribute(String name, Object value)

These methods associate a value with a name. Use putValue with servlets and either setAttribute
(preferred) or putValue (deprecated) with version 2.2 servlets.
3 public void removeValue(String name)
public void removeAttribute(String name)

These methods remove any values associated with the designated name. If the value being removed
implements HttpSessionBindingListener, its valueUnbound method is called.
Session Tracking
Methods in HTTP Session class

4 public String[ ] getValueNames()


public Enumeration getAttributeNames()

These methods return the names of all attributes in the session. Use getValueNames in version 2.1
of the servlet specification. In version 2.2, getValueNames is supported but deprecated; use
getAttributeNames instead.
5 public String getId()

This method returns the unique identifier generated for each session. It is sometimes used as the
key name when only a single value is associated with a session, or when information about sessions
is being logged.
6 public int getMaxInactiveInterval()
public void setMaxInactiveInterval(int seconds)

These methods get or set the amount of time, in seconds, that a session should go without access
before being automatically invalidated. A negative value indicates that the session should never time
out

You might also like