Download Servlets Packages

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Servlet
Introduction
Servlets are most often used to process or store a Java class in Java EE that conforms to the Java
Servlet API,[2] a standard for implementing Java classes that respond to requests. Servlets could
in principle communicate over any client–server protocol, but they are most often used with
the HTTP protocol. Thus "servlet" is often used as shorthand for "HTTP servlet".[3] Thus,
a software developer may use a servlet to add dynamic content to a web server using the Java
platform. The generated content is commonly HTML, but may be other data such as XML.
Servlets can maintain state in session variables across many server transactions by using HTTP
cookies, or rewriting URLs.
To deploy and run a servlet, a web container must be used. A web container (also known as a
servlet container) is essentially the component of a web server that interacts with the servlets.
The web container is responsible for managing the lifecycle of servlets, mapping a URL to a
particular servlet and ensuring that the URL requester has the correct access rights.
The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected
interactions of the web container and a servlet.[3]
A Servlet is an object that receives a request and generates a response based on that request. The
basic Servlet package defines Java objects to represent servlet requests and responses, as well as
objects to reflect the servlet's configuration parameters and execution environment. The
packagejavax.servlet.http defines HTTP-specific subclasses of the generic servlet elements,
including session management objects that track multiple requests and responses between the
web server and a client. Servlets may be packaged in a WAR file as a web application.
Servlets can be generated automatically from Java Server Pages (JSP) by the JavaServer Pages
compiler. The difference between servlets and JSP is that servlets typically embed HTML inside
Java code, while JSPs embed Java code in HTML. While the direct usage of servlets to generate
HTML (as shown in the example below) has become rare, the higher level MVC web framework
in Java EE (JSF) still explicitly uses the servlet technology for the low level request/response
handling via the FacesServlet. A somewhat older usage is to use servlets in conjunction with
JSPs in a pattern called "Model 2", which is a flavor of the model–view–controller.
What are Servlets?
A Java servlet is a Java program that extends the capabilities of a server. Although servlets can
respond to any types of requests, they most commonly implement applications hosted onWeb
servers.
Servlet technology is used to create web application (resides at server side and generates
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was popular as a server-side programming
language. But there was many disadvantages of this technology. We have discussed these
disadvantages below.
There are many interfaces and classes in the servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse etc.
Servlet can be described in many ways, depending on the context.
o
Servlet is a technology i.e. used to create web application.
o
Servlet is an API that provides many interfaces and classes including documentations.
o
Servlet is an interface that must be implemented for creating any servlet.
o
Servlet is a class that extend the capabilities of the servers and respond to the incoming
request. It can respond to any type of requests.
o
Servlet is a web component that is deployed on the server to create dynamic web page.
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a request coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from
a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

Performance is significantly better.

Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.

Servlets are platform-independent because they are written in Java.

Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So servlets are trusted.

The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.
Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.
Servlets Tasks:
Servlets perform the following major tasks:

Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.

Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.

Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.

Send the explicit data (i.e., the document) to the clients (browsers). This document can
be sent in a variety of formats, including text (HTML or XML), binary (GIF images),
Excel, etc.

Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.
Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java
Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.httppackages, which are a
standard part of the Java's enterprise edition, an expanded version of the Java class library that
supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time of writing this
tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any other Java class. After you install the
servlet packages and add them to your computer's Classpath, you can compile servlets with the
JDK's Java compiler or any other current compiler.
What is web application?
A web application is an application accessible from the web. A web application is composed of
web components like Servlet, JSP, Filter etc. and other components such as HTML. The web
components typically execute in Web Server and respond to HTTP request.
CGI(Commmon Gateway Interface)
CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.
Disadvantages of CGI
There are many problems in CGI technology:
1. If number of clients increases, it takes more time for sending response.
2. For each request, it starts a process and Web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Web Terminology
Servlet
Terminology
Description
Website:
static
vs
dynamic
It is a collection of related web pages that may contain text, images, audio and video.
HTTP
It is the data communication protocol used to establish communication between client and server.
HTTP
Requests
It is the request send by the computer to a web server that contains all sorts of potentially interesting
information.
Get vs Post
It give the difference between GET and POST request.
Container
It is used in java for dynamically generate the web pages on the server side.
Server:
Web
vs
Application
It is used to manage the network resources and for running the program or software that provides services.
Content
Type
It is HTTP header that provides the description about what are you sending to the browser.
HTTP (Hyper Text Transfer Protocol)
The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative,
distributed, hypermedia information systems. It is the data communication protocol used to
establish communication between client and server.
HTTP is TCP/IP based communication protocol, which is used to deliver the data like image
files, query results, HTML files etc on the World Wide Web (WWW) with the default port is
TCP 80. It provides the standardized way for computers to communicate with each other.
The Basic Characteristics of HTTP (Hyper Text Transfer Protocol):
o
It is the protocol that allows web servers and browsers to exchange data over the web.
o
It is a request response protocol.
o
It uses the reliable TCP connections by default on TCP port 80.
o
It is stateless means each request is considered as the new request. In other words, server
doesn't recognize the user by default.
The Basic Features of HTTP (Hyper Text Transfer Protocol):
There are three fundamental features that make the HTTP a simple and powerful protocol used
for communication:
o
HTTP is media independent: It refers to any type of media content can be sent by
HTTP as long as both the server and the client can handle the data content.
o
HTTP is connectionless: It is a connectionless approach in which HTTP client i.e., a
browser initiates the HTTP request and after the request is sends the client disconnects
from server and waits for the response.
o
HTTP is stateless: The client and server are aware of each other during a current request
only. Afterwards, both of them forget each other. Due to the stateless nature of protocol,
neither the client nor the server can retain the information about different request across
the web pages.
The Basic Architecture of HTTP (Hyper Text Transfer Protocol):
The below diagram represents the basic architecture of web application and depicts where HTTP
stands:
HTTP is request/response protocol which is based on client/server based architecture. In this web
browser, search engines, etc behaves as a HTTP clients, and the Web server like Servlet behaves
as a server.
HTTP Requests
The request sends by the computer to a web server that contains all sorts of potentially
interesting information is known as HTTP requests.
The HTTP client sends the request to the server in the form of request message which includes
following information:
o
The Request-line
o
The analysis of source IP address, proxy and port
o
The analysis of destination IP address, protocol, port and host
o
The Requested URI (Uniform Resource Identifier)
o
The Request method and Content
o
The User-Agent header
o
The Connection control header
o
The Cache control header
The HTTP request method indicates the method to be performed on the resource identified by
the Requested URI (Uniform Resource Identifier). This method is case-sensitive and should
be used in uppercase.
The HTTP request methods are:
HTTP Request Description
GET
Asks to get the resource at the requested URL.
POST
Asks the server to accept the body info attached. It is like GET request with extra info sent with the
request.
HEAD
Asks for only the header part of whatever a GET would return. Just like GET but with no body.
TRACE
Asks for the loopback of the request message, for testing or troubleshooting.
PUT
Says to put the enclosed info (the body) at the requested URL.
DELETE
Says to delete the resource at the requested URL.
OPTIONS
Asks for a list of the HTTP methods to which the thing at the request URL can respond
Advantage of Servlet
There are many advantages of servlet over CGI. The web container creates threads for
handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes
such as they share a common memory area, lightweight, cost of communication between the
threads are low. The basic benefits of servlet are as follows:
1. better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so we don't need to worry about memory leak,
garbage collection etc.
4. Secure: because it uses java language..
The advantages of servlets are discussed below.
1. Portability
2. Powerful
3. Efficiency
4. Safety
5. Integration
6. Extensibility
7. Inexpensive
8. Secure
9. Performance
Portability
Servlets are highly portable crosswise operating systems and server implementations because the
servlets are written in java and follow well known standardized APIs. Servlets are writing once,
run anywhere (WORA) program, because we can develop a servlet on Windows machine
running the tomcat server or any other server and later we can deploy that servlet simply on any
other operating system like Unix. Servlets are extremely portable so we can run in any platform.
So we can call servlets are platform independent one. Servlets are written entirely in java.
Powerful
We can handle several things with the servlets which were difficult or sometimes impossible to
do with CGI. For example the CGI programs can’t talk directly to the web server but the servlets
can directly talk to the web server. Servlets can share data among each other, they make the
database connection pools easy to implement. By using the session tracking mechanism servlets
can maintain the session which helps them to maintain information from request to request.
Servlets can do many things which are difficult to implement in the CGI programs.
Efficiency
The servlets invocation is highly efficient as compared to CGI programs. The servlet remains in
the server’s memory as a single object instance, when the servlet get loaded in the server. The
servlets are highly scalable because multiple concurrent requests are handled by separate threads.
That is we can handle N number of threads by using a single servlet class
Safety
As servlets are written in java, servlets inherit the strong type safety of java language. In java
automatic garbage collection mechanism and a lack of pointers protect the servlets from memory
management problems. In servlets we can easily handle the errors due to the exception handling
mechanism. If any exception occurs then it will throw an exception by using the throw statement.
Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the file
paths, perform logging, check authorization, and MIME type mapping etc.
Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands today, the
servlet API support Http Servlets, but in later date it can be extended for another type of servlets.
Java Servlets are developed in java which is robust, well-designed and object oriented language
which can be extended or polymorphed into new objects. So the java servlets take all these
advantages and can be extended from existing class to provide the ideal solutions. So servlets are
more extensible and reliable.
Inexpensive
There are number of free web servers available for personal use or for commercial purpose. Web
servers are relatively expensive. So by using the free available web servers you can add servlet
support to it.
Secure
Servlets are server side components, so it inherits the security provided by the web server.
Servlets are also benefited with Java Security Manager.
Performance
Servlets are faster than CGI programs because each scripts in CGI produces a new process and
these processes takes a lot of time for execution. But in case of servlets it creates only new
thread. Due to interpreted nature of java, programs written in java are slow. But the java servlets
runs very fast. These are due to the way servlets run on web server. For any program
initialization takes significant amount of time. But in case of servlets initialization takes place
first time it receives a request and remains in memory till times out or server shut downs. After
servlet is loaded, to handle a new request it simply creates a new thread and runs service method
of servlet. In comparison to traditional CGI scripts which creates a new process to serve the
request.
Life Cycle of a Servlet (Servlet Life Cycle)
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet

The servlet is initialized by calling the init () method.

The servlet calls service() method to process a client's request.

The servlet is terminated by calling the destroy() method.

Finally, servlet is garbage collected by the garbage collector of the JVM.
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance. The init
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:
1. public void init(ServletConfig config) throws ServletException
4) service method is invoked
The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only
once. The syntax of the service method of the Servlet interface is given below:
1. public void service(ServletRequest request, ServletResponse response)
2. throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory, thread
etc. The syntax of the destroy method of the Servlet interface is given below:
1. public void destroy()
Servlet API
1. Servlet API
2. Interfaces in javax.servlet package
3. Classes in javax.servlet package
4. Interfaces in javax.servlet.http package
5. Classes in javax.servlet.http package
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
Let's see what are the interfaces of javax.servlet package.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Servlet Container
It provides the runtime environment for JavaEE (j2ee) applications. The client/user can request
only a static WebPages from the server. If the user wants to read the web pages as per input then
the servlet container is used in java.
The servlet container is used in java for dynamically generate the web pages on the server side.
Therefore the servlet container is the part of a web server that interacts with the servlet for
handling the dynamic web pages from the client.
Servlet Container States
The servlet container is the part of web server which can be run in a separate process. We can
classify the servlet container states in three types:
o
Standalone: It is typical Java-based servers in which the servlet container and the web
servers are the integral part of a single program. For example:- Tomcat running by itself
o
In-process: It is separated from the web server, because a different program is runs
within the address space of the main server as a plug-in. For example:- Tomcat running
inside the JBoss.
o
Out-of-process: The web server and servlet container are different programs which are
run in a different process. For performing the communications between them, web server
uses the plug-in provided by the servlet container.
The Servlet Container performs many operations that are given below:
o
Life Cycle Management
o
Multithreaded support
o
Object Pooling
o
Security etc.
Content Type
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is
a HTTP header that provides the description about what are you sending to the browser.
MIME is an internet standard that is used for extending the limited capabilities of email by
allowing the insertion of sounds, images and text in a message.
The features provided by MIME to the email services are as given below:
o
It supports the non-ASCII characters
o
It supports the multiple attachments in a single message
o
It supports the attachment which contains executable audio, images and video files etc.
o
It supports the unlimited message length.
List of Content Types
There are many content types. The commonly used content types are given below:
o
text/html
o
text/plain
o
application/msword
o
application/vnd.ms-excel
o
application/jar
o
application/pdf
o
application/octet-stream
o
application/x-zip
o
images/jpeg
o
images/png
o
images/gif
o
audio/mp3
o
video/mp4
o
video/quicktime etc.
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
interfaces of javax.servlet package.Let's see what are the
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
Servlet Interface
1. Servlet Interface
2. Methods of 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
request,ServletResponse response)
provides response for the incoming request. It is invoked at each
request by the web container.
public void destroy()
is invoked only once and indicates that servlet is being destroyed.
public ServletConfig getServletConfig()
returns the object of ServletConfig.
public String getServletInfo()
returns information about servlet such as writer, copyright,
version etc.
GenericServlet class
1. GenericServlet class
2. Methods of GenericServlet class
3. Example of GenericServlet class
GenericServlet class implements Servlet, ServletConfig andSerializable interfaces. It provides
the implementation 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.
Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:
1. public void init(ServletConfig config) is used to initialize the servlet.
2. public
abstract
void
service(ServletRequest
request,
ServletResponse
response) provides service for the incoming request. It is invoked at each time when user
requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that
servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no
need to call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet
log file and a stack trace.
HttpServlet class
1. HttpServlet class
2. Methods of 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.
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
1. public void service(ServletRequest req,ServletResponse res) dispatches the request to
the protected service method by converting the request and response object into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives
the request from the service method, and dispatches the request to the doXXX() method
depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the
GET request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the
POST request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles
the HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles
the OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the
PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles
the TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles
the DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.
COOKIES Handling
Cookies are text files stored on the client computer and they are kept for various information
tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users:

Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.

Browser stores this information on local machine for future use.

When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
This chapter will teach you how to set or reset cookies, how to access them and how to delete
them.
The Anatomy of a Cookie:
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly
on a browser). 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
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded. The expires field is an instruction to the
browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry
date. If the user points the browser at any page that matches the path and domain of the cookie,
it will resend the cookie to the server. The browser's headers might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A
servlet
will
then
have
access
to
the
cookie
through
the
request
methodrequest.getCookies() which returns an array of Cookie objects.
Servlet Cookies Methods:
Following is the list of useful methods which you can use while manipulating cookies in servlet.
S.N.
Method & Description
1
public void setDomain(String pattern)
This
method sets
the domain to
which
cookie
applies,
for
example
tutorialspoint.com.
2
public String getDomain()
This method gets the domain to which cookie applies, for example
tutorialspoint.com.
3
public void setMaxAge(int expiry)
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.
4
public int getMaxAge()
This method returns the maximum age of the cookie, specified in seconds, By
default, -1 indicating the cookie will persist until browser shutdown.
5
public String getName()
This method returns the name of the cookie. The name cannot be changed after
creation.
6
public void setValue(String newValue)
This method sets the value associated with the cookie.
7
public String getValue()
This method gets the value associated with the cookie.
8
public void setPath(String uri)
This method sets the path to which this cookie applies. If you don't specify a path,
the cookie is returned for all URLs in the same directory as the current page as well
as all subdirectories.
9
public String getPath()
This method gets the path to which this cookie applies.
10
public void setSecure(boolean flag)
This method sets the boolean value indicating whether the cookie should only be
sent over encrypted (i.e. SSL) connections.
11
public void setComment(String purpose)
This method specifies a comment that describes a cookie's purpose. The comment is
useful if the browser presents the cookie to the user.
12
public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the
cookie has no comment.
Setting Cookies with Servlet:
Setting cookies with servlet involves three steps:
(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");
Keep in mind, neither the name nor the value should contain white space or any of the
following characters:
[]()=,"/?@:;
(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 useresponse.addCookie to
add cookies in the HTTP response header as follows:
response.addCookie(cookie);
Example:
Let us modify our Form Example to set the cookies for first and last name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Setting Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body></html>");
}
}
Compile above servlet HelloForm and create appropriate entry in web.xml file and finally try
following HTML page to call servlet.
<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Keep above HTML content in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would accesshttp://localhost:8080/Hello.htm,
here is the actual output of the above form.
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button. This would display first
name and last name on your screen and same time it would set two cookies firstName and
lastName which would be passed back to the server when next time you would press Submit
button.
Next section would explain you how you would access these cookies back in your web
application.
Reading Cookies with Servlet:
To read cookies, you need to create an array of javax.servlet.http.Cookieobjects by calling
the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use
getName() and getValue() methods to access each cookie and associated value.
Example:
Let us read cookies which we have set in previous example:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class ReadCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" );
if( cookies != null ){
out.println("<h2> Found 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>");
}
out.println("</body>");
out.println("</html>");
}
}
Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you would
have set
first_name
cookie
as
"John"
and
last_name
cookie
as
"Player" then
running http://localhost:8080/ReadCookies would display the following result:
Found Cookies Name and Value
Name : first_name, Value: John
Name : last_name, Value: Player
Delete Cookies with Servlet:
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow
up following three steps:

Read an already exsiting cookie and store it in Cookie object.

Set cookie age as zero using setMaxAge() method to delete an existing cookie.

Add this cookie back into response header.
Example:
Following example would delete and existing cookie named "first_name" and when you would
run ReadCookies servlet next time it would return null value for first_name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class DeleteCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Delete Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" );
if( cookies != null ){
out.println("<h2> Cookies Name and Value</h2>");
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/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}else{
out.println(
"<h2>No cookies founds</h2>");
}
out.println("</body>");
out.println("</html>");
}
}
Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now
running http://localhost:8080/DeleteCookies would display the following result:
Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as
follows:
Found Cookies Name and Value
Name : last_name, Value: Player
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select
Internet Options. To delete all cookies, press Delete Cookies.
SESSION TRACKING
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client
opens a separate connection to the Web server and the server automatically does not keep any
record of previous client request.
Still there are following three ways to maintain session between web client and web server:
Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the recieved cookie.
This may not be an effective way because many time browser does not support a cookie, so I
would not recommend to use this procedure to maintain the sessions.
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:
You can append some extra data on the end of each URL that identifies the session, and the
server can associate that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is
attached as sessionid=12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't
support cookies but here drawback is that you would have generate every URL dynamically to
assign a session ID though page is simple static HTML page.
The HttpSession Object:
Apart from the above mentioned three ways, servlet provides HttpSession Interface which
provides a way to identify a user across more than one page request or visit to a Web site and to
store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an
HTTP server. The session persists for a specified time period, across more than one connection
or page request from the user.
You
would
get
HttpSession
object
by calling
the
public
method getSession() of
HttpServletRequest, as below:
HttpSession session = request.getSession();
You need to call request.getSession() before you send any document content to the client. Here
is a summary of the important methods available through HttpSession object:
S.N.
Method & Description
1
public Object getAttribute(String name)
This method returns the object bound with the specified name in this session, or null
if no object is bound under the name.
2
public Enumeration getAttributeNames()
This method returns an Enumeration of String objects containing the names of all
the objects bound to this session.
3
public long getCreationTime()
This method returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
4
public String getId()
This method returns a string containing the unique identifier assigned to this session.
5
public long getLastAccessedTime()
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.
6
public int getMaxInactiveInterval()
This method returns the maximum time interval, in seconds, that the servlet
container will keep this session open between client accesses.
7
public void invalidate()
This method invalidates this session and unbinds any objects bound to it.
8
public boolean isNew(
This method returns true if the client does not yet know about the session or if the
client chooses not to join the session.
9
public void removeAttribute(String name)
This method removes the object bound with the specified name from this session.
10
public void setAttribute(String name, Object value)
This method binds an object to this session, using the name specified.
11
public void setMaxInactiveInterval(int interval)
This method specifies the time, in seconds, between client requests before the servlet
container will invalidate this session.
Session Tracking Example:
This example describes how to use the HttpSession object to find out the creation time and the
last-accessed time for a session. We would associate a new session with the request if one does
not already exist.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime =
new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your web page.
if (session.isNew()){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
" <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}
Compile above servlet SessionTrack and create appropriate entry in web.xml file. Now
running http://localhost:8080/SessionTrack would display the following result when you would
run for the first time:
Welcome to my website
Session Infomation
Session info
value
id
0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time
Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access
Tue Jun 08 17:26:40 GMT+04:00 2010
User ID
ABCD
Number of visits
0
Now try to run the same servlet for second time, it would display following result.
Welcome Back to my website
Session Infomation
info type
value
id
0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time
Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access
Tue Jun 08 17:26:40 GMT+04:00 2010
User ID
ABCD
Number of visits
1
Deleting Session Data:
When you are done with a user's session data, you have several options:

Remove a particular attribute: You can call public void removeAttribute(String
name) method to delete the value associated with a particular key.

Delete the whole session: You can call public void invalidate()method to discard an
entire session.

Setting
Session
timeout: You
can
call public
void
setMaxInactiveInterval(int
interval) method to set the timeout for a session individually.

Log the user out: The servers that support servlets 2.4, you can calllogout to log the
client out of the Web server and invalidate all sessions belonging to all the users.

web.xml Configuration: If you are using Tomcat, apart from the above mentioned
methods, you can configure session time out in web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in
Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in
seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( )
returns 900.
Servlet API
6. Servlet API
7. Interfaces in javax.servlet package
8. Classes in javax.servlet package
9. Interfaces in javax.servlet.http package
10. Classes in javax.servlet.http package
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
Let's see what are the interfaces of javax.servlet package.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
15. Servlet
16. ServletRequest
17. ServletResponse
18. RequestDispatcher
19. ServletConfig
20. ServletContext
21. SingleThreadModel
22. Filter
23. FilterConfig
24. FilterChain
25. ServletRequestListener
26. ServletRequestAttributeListener
27. ServletContextListener
28. ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
12. GenericServlet
13. ServletInputStream
14. ServletOutputStream
15. ServletRequestWrapper
16. ServletResponseWrapper
17. ServletRequestEvent
18. ServletContextEvent
19. ServletRequestAttributeEvent
20. ServletContextAttributeEvent
21. ServletException
22. UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
9. HttpServletRequest
10. HttpServletResponse
11. HttpSession
12. HttpSessionListener
13. HttpSessionAttributeListener
14. HttpSessionBindingListener
15. HttpSessionActivationListener
16. HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
8. HttpServlet
9. Cookie
10. HttpServletRequestWrapper
11. HttpServletResponseWrapper
12. HttpSessionEvent
13. HttpSessionBindingEvent
14. HttpUtils (deprecated now)
Servlet Concurrency
A Java servlet container / web server is typically multithreaded. That means, that multiple
requests to the same servlet may be executed at the same time. Therefore, you need to take
concurrency into consideration when you implement your servlet.
To make sure that a servlet is thread safe, there are a few basic rules of thumb you must follow:
1. Your servlet service() method should not access any member variables, unless these
member variables are thread safe themselves.
2. Your servlet service() should not reassign member variables, as this may affect other
threads executing inside the service() method. If you really, really need to reassign a
member variable, make sure this is done inside a synchronized block.
3. Rule 1 and 2 also counts for static variables.
4. Local variables are always thread safe. Keep in mind though, that the object a local
variable points to, may not be so. If the object was instantiated inside the method, and
never escapes, there will be no problem. On the other hand, a local variable pointing to
some shared object, may still cause problems. Just because you assign a shared object to
a local reference, does not mean that object automatically becomes thread safe.
The request and response objects are of course thread safe to use. A new instance of these are
created for every request into your servlet, and thus for every thread executing in your servlet.
Here is a diagram which illustrates the servlet concurrency rules / issues mentioned above. The
red boxes represent state (variables) that your servlet's service() method should be careful about
accessing.
Java Servlet Concurrency Rules.