0% found this document useful (0 votes)
73 views94 pages

Unit 3: Servlet API and Overview: Prepared By: Prof. Ruchita Macwan

The document provides an overview of servlet API including servlet life cycle, HTTP methods, deployment descriptor, servlet context and config interface, attributes in servlet, request dispatcher interface, filter API, cookies and session management. It also discusses servlet vs CGI, servlet container, servlet loading and initialization, service and destroy methods.

Uploaded by

Rohan
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)
73 views94 pages

Unit 3: Servlet API and Overview: Prepared By: Prof. Ruchita Macwan

The document provides an overview of servlet API including servlet life cycle, HTTP methods, deployment descriptor, servlet context and config interface, attributes in servlet, request dispatcher interface, filter API, cookies and session management. It also discusses servlet vs CGI, servlet container, servlet loading and initialization, service and destroy methods.

Uploaded by

Rohan
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/ 94

Unit 3:

Servlet API and Overview

Prepared by:
Prof. Ruchita Macwan
Contents…

• Servlet Model: Overview of Servlet


• Servlet Life Cycle,
• HTTP Methods
• Structure and Deployment descriptor
• ServletContext and ServletConfig interface
• Attributes in Servlet
• Request Dispacher interface
• The Filter API: Filter, FilterChain, Filter Config
• Cookies and Session Management
• Understanding state and session
• Understanding Session Timeout and Session Tracking
• URL Rewriting
What does your web server do?
• A web server takes client request and gives
something back to the client.
What does your web client do?
• A web client lets the user request something on the
server, and shows user result of the request.
HTML and HTTP
HTML is a part of HTTP response
HTTP Methods
HTTP Request Methods
HTTP Get Method
• Note that the query string (name/value pairs) is sent in the
URL of a GET request:
/test/demo_form.asp?name1=value1&name2=value2

• GET requests can be cached


• GET requests remain in the browser history
• GET requests can be bookmarked
• GET requests should never be used when dealing with
sensitive data
• GET requests have length restrictions
• GET requests should be used only to retrieve data
HTTP POST Method
• Note that the query string (name/value pairs)
is sent in the HTTP message body of a POST
request:
POST /test/demo_form.asp HTTP/1.1
Host: google.com
name1=value1&name2=value2

• POST requests are never cached


• POST requests do not remain in the browser
history
• POST requests cannot be bookmarked
• POST requests have no restrictions on data
length
Two things web server won’t do alone

1. Dynamic Content
2. Saving Data on Server
Common Gateway Interface (CGI)
• CGI (Common Gateway Interface) is used to
provide dynamic content to the user.
• CGI is used to execute a program that resides
in the server to process data or access
databases to produce the relevant dynamic
content.
• Programs that resides in server can be written
in native operating system such as C++.
Disadvantages of CGI

• For each request CGI Server receives, it


creates new Operating System Process.

• If the number of requests from the client


increases then more time it will take to
respond to the request.
Servlets
• A servlet is a simple Java class, which is
dynamically loaded on a web server and
thereby enhances the functionality of the
server.
• Servlets are secure and portable as they run
on JVM embedded with the Web Server.
• Servlets can run on any Java enabled platform
and are usually designed to process HTTP
requests such as GET, POST etc.
Continue…
• CGI programs are used to execute programs
written inside the native language. But in
Servlet all the programs are compiled into the
Java bytecode which is then run in the Java
virtual machine.
• In Servlet, All the requests coming from the
Client are processed with the threads instead
of the OS process.
Servlets vs. CGI
Servlets CGI (Common Gateway Interface)

Servlets are portable CGI is not portable.


In Servlets each request is handled by IN CGI each request is handled by heavy weight
lightweight Java Thread OS process
In Servlets, Data sharing is possible In CGI, data sharing is not available.

Servlets can link directly to the Web server CGI cannot directly link to Web server.
Session tracking and caching of previous Session tracking and caching of previous
computations can be performed computations cannot be performed
Automatic parsing and decoding of HTML form Automatic parsing and decoding of HTML form
data can be performed. data cannot be performed.
Servlets can read and Set HTTP Headers CGI cannot read and Set HTTP Headers
Servlets can handle cookies CGI cannot handle cookies
Servlets can track sessions CGI cannot track sessions
Servlets is inexpensive than CGI CGI is more expensive than Servlets
What is a Container?
• Servlets do not have a main method.
• They are under the control of another java
application called Container.
• When a web server like Apache gets a request
for a servlet it is not handed to servlet itself,
but to the Container in which servlet id
deployed.
What does container give you?
• Communication support
• Lifecycle Management
• Multithreading support
• Declarative security
• JSP support
Life Cycle of Servlet
Loading and initialization
• The container calls init() method on servlet
instance after the servlet instance is created.
• A servlet is normally created when a user invokes
a URL corresponding to the servlet for the first
time; however the servlet is loaded on the server
when a Servlet container maps user request to
the servlet.
• It is called only once in the servlet’s lifetime.
• The following code snippet shows init method
definition:
Continue…
public void init() throws ServletException
{
//Initialization Code
ServletConfig config=getServletConfig();
String param1=config.getInitParameter(“parameter1”);
}
Service() method
• Each time a server recieves a request for the
servlet, the server creates a new thread and
calls the service() method.
• The service() method verifies the HTTP
request type (GET, POST, PUT, DELETE etc.) and
accordingly calls doGet(), doPost(), doPut(),
doDelete() etc methods.
• The following code snippet explains
implementation of post() method:
Continue…
<html>
<form name=“myform” method=“post”>
<body>
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
</form>
</body>
</html>
Continue….
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
//Servlet Code
}
Destroy() method
• The destroy() method runs only once during the
lifetime of a servlet, and signals the end of the
servlet instance.
• A servlet container holds a servlet instance till the
servlet is active or its destroy() method is called.
• The following code snippet shows method signature
of destroy() method:
public void destroy()
• As soon as destroy() method is activated, the Servlet
Container releases the servlet instance.
Each Servlet runs in a separate thread
Exploring the Servlet API
• The below two packages have all the interfaces and classes,
which are required by Servlet API.
1. javax.servlet
2. javax.servlet.http

• javax.servlet package is used for serving protocol-less


requests.
• javax.servlet.http package is used for http protocol requests.
• Every servlet must implement the below interface
directly or indirectly (by extending the class which
already implements this interface:
javax.servlet.Servlet
Continue…
• Generally servlet implements javax.servlet.Servlet interface
indirectly, by extending one of the below two classes:

1. javax.servlet.GenericServlet: Defines a generic, protocol-


independent servlet. GenericServlet implements the Servlet
and ServletConfig interfaces.

2. javax.servlet.http.HttpServlet: It is an abstract class that


needs to be extended(inherit) to create a HttpServlet suitable
for a web application(website or online application).
How does Servlet Code looks like?
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Servlet1 extends HttpServlet {

String message;

@Override
public void init()
{
message = "This is my first servlet example.";
}
Continue…
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Servlet1</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Servlet1 at " + request.getContextPath() + "</h1>");
out.println(message);
out.println("</body>");
out.println("</html>");
}
@Override
public void destroy() {}
}
Deployment Descriptor
• When you deploy your servlet into web container, a
fairly simple XML document called the Deployment
Descriptor (DD) to tell the Container how to run
servlets and JSP’s.
• The two DD elements used for URL mapping are:
1. <servlet>
maps internal name to fully qualified class name.
2. <servlet-mapping>
maps internal name to public URL name.
Continue…
So, Deployment Descriptor is basically used for:
• Mapping URL to Servlet class.
• Initializing parameters.
• Defining Error page.
• Security roles.
• Declaring tag libraries.
Example
What does being a servlet offer you?
A Servlet Config Object
• One ServletConfig object per servlet.
• Use it to pass deploy time information to th
servlet that you don’t want to hardcore into
the servlet.
• Use it to access ServletContext.
• Parameters are configured in deployment
descriptor.
Methods of SevletConfig Interface

• getInitParameter(String)
• Enumeration getInitParameterNames()
• getServletContext()
• getServletName()
A ServletContext object
• One ServletContext per Web app.
• Used to acess the web app parameters.
• Used as a kind of application bulletin board
where you can put up messages.
• Used to get server info, including the name
and version of the container, and the version
of the API that’s supported.
Methods of SevletContext Interface

• getInitParameter(String)
• getInitParameterNames()
• getAttribute(String)
• getAttributeNames()
• setAttribute(String)
• removeAttribute()
Init Parameters
• We have already seen the request parameters that
come with doGet() or doPost() but servlets have
initialization parameters as well.
• Each registered servlet name can have specific
initialization (init) parameters associated with it.
• Init parameters are available to the servlet at any time;
they are often used in init() to set initial or default
values for a servlet or to customize the servlet’s
behavior in some way.
Example…
Context init parameters
• Context init parameters work just like servlet init
parameters, except context parameters are available
to the entire webapp, not just a single servlet.
• It means that any servlet and JSP in the web app
automatically has access tp context init parameters.
• Hence there is no need about configuring DD for
every servlet.
• And when the value of the parameter changes you
only have to change it at one place.
Example…
Continue….
Continue…
• When the Container initializes a servlet, it
makes a unique ServletConfig for the servlet.
• The Container reads the servlet init
parameters from the DD and gives them to
the ServletConfig, then passes the
ServletConfig to the servlet’s init() method.
• The servlet init parameters are read only once
when the container initializes the servlet.
Difference between the two
parameters
Attributes in Servlet
• An attribute is an object set into one of the three other
servlet API objects-ServletContext, HttpServletRequest or
HttpSession.
• It can be simply thought as a name value pair where
name is a String and the value is an object.
• An attribute is like an object pinned to a bulletin board.
Somebody stuck it on the board so that others can get it.
• The question is what is the scope of this attributes. In
other words who can see these attributes and how long
does it live.
Attributes are not parameters
Three scopes: Context, Request & Session

• Context Scope
Continue…
• Context scope or application scope starts from the point
where a web application is put into service (started) till it is
removed from service (shutdown) or the web application is
reloaded. Parameters/attributes within the application scope
will be available to all requests and sessions.
• Application scope is denoted by
javax.servlet.ServletContext interface.
• In a servlet, you can get application object by
calling getServletContext() from within the servlets code
directly (the servlet itself implements the ServletConfig
interface that contains this method) or by explicitly
calling getServletConfig().getServletContext().
• The web container provides one ServletContext object per
web application per jvm.
Session scope
Continue…

• A session scope starts when a client (e.g. browser window)


establishes connection with our web application till the
point where the browser window is closed.
• Session scope spans across multiple requests from the
same client.
• Session scope is denoted by
javax.servlet.http.HttpSession interface.
• In a servlet, you can get Session object by
calling request.getSession().
Request scope
Continue…
• Request scope start from the moment an HTTP request hits a servlet in
our web container and end when the servlet is done with delivering the
HTTP response.
• With respect to the servlet life cycle, the request scope begins on entry to
a servlet’s service() method and ends on the exit from that method.
• A ‘request’ scope parameter/attribute can be accessed from any of
servlets or jsps that are part of serving one request. For example, you call
one servlet/jsp, it then calls another servlet/jsp and so on, and finally the
response is sent back to the client.
• Request scope is denoted by
javax.servlet.http.HttpServletRequest interface.
• Container passes the request object as an argument of type
HttpServletRequest to Servlet's service method.
Attribute API
• The three attribute scopes-context, request and session are
handled by ServletContext, ServletRequest, and HttpSession
interfaces.
• The API methods for attributes are exactly the same in every
interface which are:
 Object getAttibute(String name)
 setAttribute(String name, Object value)
 removeAttribute(String name)
 Enumeration getAttributeNames()
Context attributes: Are they thread safe??
Request Dispatcher Interface
• While building a complex web application there might be a need to distribute the
request to multiple servlets. This is where request dispatching comes into use.

• Due to this requirement servlet container supports request dispatching within the
same context.

• The javax.servlet.RequestDispatcher is an interface that enables the Servlet


Container to dispatch the request from a web application to another within the
same context.

• In order to dispatch the request we need to perform these tasks:


a. Get a RequestDispatcher object.
b. Use the forward() method or include method of RequestDispatcher
Continue…
• There are mainly two ways to create the RequestDispatcher
object:
1. By using ServletRequest object RequestDispatcher
rd=request.getRequestDispatcher(“welcome.jsp");
rd.forward(req,res);
(or)
rd.include(req,res);

2. By using getRequestDispatcher() method of ServletContext


RequestDispatcher rd=getServletContext().getRequestDispatcher(“welcome.jsp");
rd.forward(req,res);
(or)
rd.include(req,res);
Continue…
• There are mainly two methods of the RequestDispatcher
object:
a. forward()
When you invoke a forward request, the request is sent to another resource on
the server, without the client being informed that a different resource is going to
process the request.

b. include()
When you invoke a include request, it includes the response of the requested
response in the current servlet/jsp response.
SendRedirect Method
• The sendRedirect() method of HttpServletResponse interface can be used
to redirect response to another resource, it may be servlet, jsp or html file.
• It accepts relative as well as absolute URL.
• It works at client side because it uses the url bar of the browser to make
another request.
• The SendRedirect() method causes the web container to return to the
browser indicating that a new URL should be requested.
• Since the browser issues a completely new request any object that are
stored as request attributes before the redirect occurs will be lost.
• Syntax:
response.sendRedirect(“url");
e.g.
response.sendRedirect("http://www.google.com");
Servlet Filter API
• A filter is a java class that is called for responding to
the requests for resources such as servlets and JSP.
• Filters intercept and process requests before the
requests are forwarded to servlets and process the
response after the response has been generated by
servlet.
• Filters need to be configured in order to serve client
requests.
• Filters can also be put into chain, where multiple
filters can b invoked one after the other.
Need of Filters
• Suppose a web application formats data to presented to client
in specific format say word. At a later point of time client
requires data in some other format say excel, pdf etc. then
instead of modifying the code every time a filter can be
created to transform data dynamically.

• Thus filters were introduced to implement additional


functionalities such as verifying login credentials, maintaining
server log etc.

• Filters can be reused in other web applications also.


Applications of Filters

• Session validation
• Logging operations
• Authentication
• Data compression
• Encryption/Decryption
• Image conversion
The Filter API

The filter API includes three interfaces:


• Filter
• FilterConfig
• FilterChain
The Filter Interface
• For creating any filter, you must implement
the javax.servlet.Filter interface.
• Filter interface calls methods during life cycle
of a filter.
1. init()
2. doFilter()
3. destroy()
The Filter Interface

Method Description
init() method is invoked only once. It is
public void init(FilterConfig config)
used to initialize the filter.
doFilter() method is invoked every time
public void doFilter(ServletRequest
when user request to any resource, to
request,ServletResponse response,
which the filter is mapped.It is used to
FilterChain chain)
perform filtering tasks.
This is invoked only once when filter is
public void destroy()
taken out of the service.
The FilterConfig Interface
• The javax.servlet.FilterConfig interface is an argument to the init()
method.
• The Container gives us through this interface some information about
initial parameters and access to the ServletContext as well.

Method Description
public String getFilterName() Returns the filter-name of this filter as defined
in the deployment descriptor.
public ServletContext getServletContext() Returns a reference to the ServletContext in
which the caller is executing.
public String getInitParameter(String name) Returns a String containing the value of the
named initialization parameter, or null if the
parameter does not exist.
public Enumeration getInitParameterNames() Returns the names of the filter's initialization
parameters as an Enumeration of String
objects, or an empty Enumeration if the filter
has no initialization parameters.
The FilterChain Interface
• The javax.servlet.FilterChain interface is an argument to the doFilter()
method. This interface has only one method, doFilter(), which are used by
the programnmer to causes the next filter in the chain to be invoked.

Method Description
public void doFilter(ServletRequest Causes the next filter in the chain to be
request, ServletResponse response) invoked, or if the calling filter, is the last
filter in the chain, causes the resource at
the end of the chain to be invoked.
The FilterChain Interface
Configuring a Filter
• The deployment descriptor is used to tell the container which, if any, filters in which
sequence to call for each servlet in the application.

• web.xml:-

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
Configuring a Filter
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>

</web-app>
Understanding session and state
• The HTTP protocol uses stateless connections.
• The client browser makes a connection to the server,
sends the request, gets the response, and closes the
connection.
• In other words, the connection exists for only a single
request/response.
• Because the connections don’t persist, the Container
doesn’t recognize that the client making a second
request is the same client from previous request.
• As far as the Container is concerned each request is
from a new client
Continue…
• A session can be defined as a collection of HTTP requests
shared between a client and web server over a period of
time.
• While creating a session its lifetime is set (by default: 30
min) after which the session expires and the resources
are returned back to servlet engine.
• To check whether the request is from the same client,
the Container generates a unique session id and gives it
back to the client along with response.
• The client sends back the session id with each
subsequent request.
• The Container sees the id, finds the matching id and
associates the session with the request.
Session Tracking
• Session tracking is a process of gathering the user
information from Web pages, which can be used in an
application.
• Session tracking involves identifying the user session by
related id numbers and tying the requests to their sessions
by using the said id number.
• Following session tracking mechanisms can be used to track
session details:
1. Http session object
2. Cookies
3. Hidden form fields
4. URL Rewriting
Http Session object
• An HttpSession object can hold conversational state across multiple
requests from the same client.
• In other words, it persists for an entire session with a specific client.
• We can use it to store everything we get back from the client in all the
requests the client makes during a session.
• HttpSession object is obtained by calling the public method getSession()
of HttpServletRequest, as below:
HttpSession session = request.getSession();
or
HttpSession session = request.getSession(boolean);
where , true= request for new session
false= request for previous session
Methods of Http Session object
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.
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.
Continue…
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.
Setting session timeout
• Three ways a session can die:
1. It times out.
2. Invalidate() method is called on session
object.
3. The application goes down(crashed).
Setting session timeout
1. Configuring session timeout in web.xml:
<session-config>
<session-timeout>
90 //time in mins
</session-timeout>
</session-config>

2. Setting session timeout for a particular session:


session.setMaxInactiveInterval(60*20); // 20 mins

3. Calling invalidate method of HttpSession object:


session.invalidate();
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:
1. Server script sends a set of cookies to the browser. For
example name, age, or identification number etc.
2. Browser stores this information on local machine for
future use.
3. 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.
Cookies
• Cookies are usually set in an HTTP header.
• A servlet that sets a cookie might send
headers that look something like this:
HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server:
Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-
Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection:
close Content-Type: text/html
Servlet Cookies Methods
S.N. Method & Description
public void setDomain(String pattern)
1 This method sets the domain to which cookie applies, for example
tutorialspoint.com.
public String getDomain()
2 This method gets the domain to which cookie applies, for example
tutorialspoint.com.
public void setMaxAge(int expiry)
3 This method sets how much time (in seconds) should elapse before the cookie
expires. If you don't set this, the cookie will last only for the current session.
public int getMaxAge()
4 This method returns the maximum age of the cookie, specified in seconds, By default,
-1 indicating the cookie will persist until browser shutdown.
public String getName()
5 This method returns the name of the cookie. The name cannot be changed after
creation.
public void setValue(String newValue)
6
This method sets the value associated with the cookie.
Servlet Cookies Methods
public String getValue()
7
This method gets the value associated with the cookie.
public void setPath(String uri)
This method sets the path to which this cookie applies. If you don't specify
8
a path, the cookie is returned for all URLs in the same directory as the
current page as well as all subdirectories.
public String getPath()
9
This method gets the path to which this cookie applies.
public void setSecure(boolean flag)
10 This method sets the boolean value indicating whether the cookie should
only be sent over encrypted (i.e. SSL) connections.
public void setComment(String purpose)
11 This method specifies a comment that describes a cookie's purpose. The
comment is useful if the browser presents the cookie to the user.
public String getComment()
12 This method returns the comment describing the purpose of this cookie, or
null if the cookie has no comment.
Setting cookies in Servlet
(1) Creating a Cookie object: You call the Cookie constructor with a cookie
name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");

(2) Setting the maximum age: You use setMaxAge to specify how long (in
seconds) the cookie should be valid. Following would set up a cookie for
24 hours.
cookie.setMaxAge(60*60*24);

(3) Sending the Cookie into the HTTP response headers: You use
response.addCookie to add cookies in the HTTP response header as
follows:
response.addCookie(cookie);
Retrieving cookies in Servlet
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null )
{
out.println("<h2>Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}
else{ out.println( "<h2>No cookies founds</h2>");}
Deleting cookies in Servlet
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null )
{
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 )
{
cookie.setMaxAge(0); response.addCookie(cookie);
out.print("Deleted cookie : " + cookie.getName( ) + "<br/>");
}
}}
else{ out.println( "<h2>No cookies founds</h2>");}
Hidden Form Fields
• 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">

• This entry means that, when the form is submitted, the specified name
and value are automatically included in the GET or POST data.
• Each time when web browser sends request back, then session_id value
can be used to keep the track of different web browsers.
• This could be an effective way of keeping track of the session but clicking
on a regular (<A HREF...>) hypertext link does not result in a form
submission, so hidden form fields also cannot support general session
tracking.
URL Rewriting
• The javax.servlet.HttpServletResponse class includes
a method that will encode a URL with the current
session ID, in the event that the user making the
servlet request has disabled cookies.
• In fact, if you use the
HttpServletResponse.encodeURL(String url) method
to encode the URLs that are used in a servlet, this
method takes care of URL rewriting if necessary, and
you won't have to worry about whether cookies are
enabled in users' browsers.
URL Rewriting Example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class URLRewritingServlet extends HttpServlet {


//Initialize global variables

public void init(ServletConfig config)


throws ServletException {

super.init(config);
}

//Process the HTTP Get request


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

response.setContentType("text/html");
PrintWriter out = response.getWriter();
URL Rewriting Example
out.println("<html>");
out.println("<head><title>URL Rewriting</title></head>");
out.println("<body>");

// Encode a URL string with the session id appended


// to it.
String url = response.encodeRedirectURL(
"http://localhost:8000/servlet/checkout?sid=5748");

// Redirect the client to the new URL


response.sendRedirect(url);
out.println("</body></html>");
out.close();
}
}
Thank you

You might also like