0% found this document useful (0 votes)
38 views90 pages

Servlets Notes Unit 4

The document provides an overview of web applications, focusing on static and dynamic resources, server-side programming, and the advantages of using server-side programs like Java servlets. It explains the roles of web servers and web containers, the HTTP protocol, and the differences between GET and POST request methods. Additionally, it discusses the deployment and packaging of web applications according to J2EE specifications.

Uploaded by

darshanjain1905
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)
38 views90 pages

Servlets Notes Unit 4

The document provides an overview of web applications, focusing on static and dynamic resources, server-side programming, and the advantages of using server-side programs like Java servlets. It explains the roles of web servers and web containers, the HTTP protocol, and the differences between GET and POST request methods. Additionally, it discusses the deployment and packaging of web applications according to J2EE specifications.

Uploaded by

darshanjain1905
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/ 90

Matrix Computers (Page 1 of 90)

10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan


9414752750, 9414930104, 9414244351, 0141-2399633

Unit IV Servlets
Introduction to Web-Applications:
A web application is nothing but a web-site. A web application can be thought of as a collection of two types
of resources Static, Dynamic Resources. Web applications are deployed (installed) on the web servers (web-
containers) and are normally accessed through the web Clients, which is normally a web browser. The
communication between web client and web server takes place through HTTP protocol (Set of rules).

1. Static Resources:
These are normally non-executable resources. In some cases static resources may also be the executable
resources but they do not execute on the server. These are only for view purpose. A typical application might
have following types of static resources:
• HTML • Documents
• Images, Audio and Video files • Spreadsheets
• Applets • Text Files
A web client can ask for any static resource by just specifying the URL. Web server simply returns the
specified resource to the client without any processing. The client decides what to do with the static resource.
The most common static resource is the HTML page. The web browser interprets the HTML page and
displays in the browser window. For other type of static resources the action taken may differ from browser
to browser. The browser either displays the contents of the resource on its own or with the help of software
corresponding to the static resource. For example, Internet Explorer may open a .doc file using MS-word
software. The browser prompts for saving the contents in case it is not able to display/process the contents.

2. Dynamic Resources:
These are executable resources. The dynamic resources are also accessed by directly or indirectly specifying
the URL. But the action taken by web server is different in case of dynamic resources. The dynamic sources are
Java programs. The server executes the appropriate component and then returns the result to the client normally
as HTML using HTTP protocol. A web application can have following types of dynamic resources:
• CGI: Common Gateway Interface (CGI) is a technology to generate dynamic web contents. CGI enables the
web server to call an external program and pass HTTP request information to that external program to process
the request. The response from the external program is then passed back to the web server, which forwards it
RIX
AT
M

to the client browser. CGI programs can be written in any language that can be called by the web server. Perl is
a language to write CGI programs.
• Servlets: Java servlets are small, platform independent server side programs that programmatically extend the
functionality of the web server.
• Java server pages(JSPs): Java Server Pages is an extension of the java servlets technology. However, in
contrast to servlets, which are pure Java programs, JSP pages are text-based documents. A JSP page contains
two parts:
• HTML for the static content
• JSP tags and scriptlets written in java to encapsulate the logic that generate the dynamic content. Since a
JSP page provides a general representation of content that can produce multiple views depending on the
result of JSP tags and scriptlets, a JSP page acts like a template for producing content.

Introduction to Server Side Programming:


All of us (or most of us) would have started programming in Java with the ever famous “Hello World!” program.
If you can recollect, we saved this file with a .java extension and later compiled the program using javac and
then executed the class file with java. Apart from introducing you to the language basics, the point to be noted
about this program is that – “It is a client side program”. This means that you write, compile and also execute
the program on a client machine (e.g. Your PC). No doubt, this is the easiest and fastest way to write, compile
and execute programs. But, it has little practical significance when it comes to real world programming.
Why Server Side Programming?
Though it is technically feasible to implement almost any business logic using client side programs, logically or
functionally it carries no ground when it comes to enterprise applications (e.g. banking, air ticketing, e-shopping
etc.). To further explain, going by the client side programming logic; a bank having 10,000 customers would
Matrix Computers (Page 2 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

mean that each customer should have a copy of the program(s) in his or her PC which translates to 10,000
programs! In addition, there are issues like security, resource pooling, concurrent access and manipulations to
the database which simply cannot be handled by client side programs. The answer to most of the issues
mentioned above is – “Server Side Programming”.

Advantages of Server Side Programs:


The list below highlights some of the important advantages of Server Side programs.
• All programs reside in one machine called the Server. Any number of remote machines (called clients) can
access the server programs.
• New functionalities to existing programs can be added at the server side which the clients’ can advantage without
having to change anything from their side.
• Migrating to newer versions, architectures, design patterns, adding patches, switching to new databases can be
done at the server side without having to bother about clients’ hardware or software capabilities.
• Issues relating to enterprise applications like resource management, concurrency, session management,
security and performance are managed by server side applications.
• They are portable and possess the capability to generate dynamic and user-based content (e.g. displaying
transaction information of credit card or debit card depending on user’s choice).
RIX
AT
M

Web Server and the Web Container:


Web Server:A web server is a computer program that delivers (serves) content, such as Web pages, using the Hypertext
Transfer Protocol (HTTP), over the World Wide Web. The term Web server can also refer to the computer or virtual
machine running the program. The primary function of a Web server is to deliver Web pages to clients. This means
delivery of HTML documents and any additional content that may be included by a document, such as images, style
sheets and JavaScripts.

Vendor Product
Apache Apache
Microsoft IIS(Internet Information Server)
Google GWS

Web Container:- It contains & manages all the web resources. It is a runtime environment for web components that
includes security, concurrency, lifecycle management, transaction, deployment, and other services.
• Sun Java System Web Server
• Tomcat for Java WSDP

The web applications are deployed on the web servers. The Web server handles all the communication between
web client and the web application. As discussed earlier a web application is simply collection of static and dynamic
resources. Any resource belonging to a web application is identified by URL. The client can access any resource by just
specifying the URL. Web server might have some common resources, which do not belong to any web application. Such
resources are normally static resources. If client asks for some resources not belonging to any application, the web
server can directly send resource to the client.
Matrix Computers (Page 3 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

If the client asks for some resource belonging to web application then it is not served directly by the web server.
Web server passes the request to the web container, which is a component responsible for running the web applications.
If the resource is static then web container simply passes the resource to the web server and then web server
sends the resource to the web client. On the other hand if the resource is dynamic then the web container executes the
resource and receives the result normally in the form of HTML and then passes the result to the web server which then
passes it to the web client.

Diagram to show interaction between client and web application


Servlets:
The java servlet API provides a simple framework for building application on such web servers. Servlets are java
classes that are used to create dynamic web applications. Servlets can run on any Java-enabled platform. Java Servlets
are usually designed to process HTTP requests, such as GET, and POST. A servlet container allows multiple requests
for the same servlet by creating a different thread to service each request. Means each servlet class has only one object
for all the requests.

Servlet API History:


Version Platform Important Changes

Servlet 4.0 Dec 2014 JavaSE 8


Servlet 3.1 Dec 2011 JavaSE 7 Pluggability, Ease of development, Async Servlet, Security, File Uploading
RIX
AT

Servlet 3.0 Dec 2009 JavaSE 6


M

Servlet 2.5 Sep 2005 JavaSE 5 Requires JavaSE 5, supports annotations


Servlet 2.4 Nov 2003 J2SE 1.3 web.xml uses XML Schema
Servlet 2.3 Aug 2001 J2SE 1.2 Addition of Filter
Servlet 2.2 Aug 1999 J2SE 1.2 Becomes part of J2EE, introduced independent web applications in .war
files
Servlet 2.1 Nov 1998 Unspecified First official specification, added RequestDispatcher, ServletContext
Servlet 2.0 JDK 1.1 Part of Java Servlet Development Kit 2.0
Servlet 1.0 Jun 1997

Advantages of Java Servlets:


• Portability: As we know that the servlets are written in java and follow well known standardized APIs so they
are highly portable across operating systems and server implementations. We can develop a servlet on
Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly
on any other operating system like Unix server running on the iPlanet/Netscape Application server. So servlets
are write once, run anywhere (WORA) program.
• Powerful: We can do several things with the servlets which were difficult or even impossible to do with CGI, for
example the servlets can talk directly to the web server while the CGI programs can't do. Servlets can share
data among each other, they even make the database connection pools easy to implement. They can maintain
the session by using the session tracking mechanism which helps them to maintain information from request
to request. It can do many other things which are difficult to implement in the CGI programs.
• Efficiency:- Servlets are highly efficient because only one object of the servlet class is loaded in memory. It
creates multiple threads to serve multiple requests.
Matrix Computers (Page 4 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

• Safety:- As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic
garbage collection and a lack of pointers mean that servlets are generally safe from memory management
problems. In servlets we can easily handle the errors due to Java's exception handling mechanism. It also uses
exception handling which is very efficient mechanism in error handling.
• 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.
• 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.

MIME:-
MIME (Multipurpose Internet Mail Extensions) is a mechanism for Specifying and describing the format of
Internet Message Bodies. When the Web Server receives a request from a client, it uses the MIME type mappings to
determine the kind of resource that is requested. Some MIME types are:-
type=text/html gives output in text/html form
type=text/plain Plain Text
type=text/richtext Rich Text Format
type=application/vnd.ms-powerpoint Microsoft Power Point.
type=application/vnd.ms-excel Microsoft Excel.
type=application/vnd.ms-word Microsoft Word.
Note:- Use these inside setContentType("text/html") method to get output in the required form.

The HTTP (Hypertext Transfer Protocol) Protocol:


HTTP is the protocol that allows web servers and browsers to exchange data over the web. It is a request and
response protocol. The HTTP is an application-level protocol (generally implemented over TCP/IP Connection). The
HTTP is a stateless protocol based on requests & responses. In this paradigm, client application (such as your web
browser) sends request to the server (Such as the web server of an online store) to receive info (such as downloading
a catalog) or to initiate specific processing on the server (such as placing an order).
Key Features of HTTP:
• HTTP is a very simple and lightweight protocol.

RIX
AT

In this protocol, the clients always initiate requests. The Server can never make a Callback Connection to the
M

Client.
• The HTTP requires the clients to establish connections prior to each request and the servers to close the
connection after sending the response. This guarantees that the client cannot hold on to a connection after
receiving the response. Either the client or the server can prematurely terminate the connection.

HTTP Request Methods:


As an application-level protocol, HTTP defines the types of request that clients can send to servers and the types of
response that servers can send to clients.
• The Get Request Method
• The Post Request Method

The Get Request Method:-


The Get Request is the simplest & most frequently used request method for accessing static resources such
as HTML documents, image etc. The Get method is used when the resource is accessed by specifying the URL in the
web browser or by clicking on a hyperlink.
Get request can also be used to retrieve dynamic information by using additional query parameters in the
request URL of a dynamic resource. Hyperlink like:
http://www.matrix.com/testapp?name=matrix&address=mansarovar
The data is transmitted as the part of URL if GET method is used. Sometimes we employ GET method even
when accepting data from the client using the form. In this case any data provided in the form is appended to the URL
as query parameters before sending to the server.
Matrix Computers (Page 5 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

The Post Request Method :


Post requests are used when we need to send large amount of complex information to the server. The Post
request allows the encapsulation of multi-part message into the request body. For example, you can use post request
to upload text & binary files.
Normally we send data using post method through form by specifying “POST” as the method. The data is
transmitted as part of the body. So it is possible to send the large amount of data when using post request.

Limitation of Get Method:


• Firstly since a Get request contains the complete request info appended to the URL. Itself, it allows browser to
bookmark the page & revisit later. Depending on the type & how sensitive the request parameters are this may
or may not be desirable.
• Secondly some servers might pose restrictions on the length of request URL. This limits the amount of info that
can be appended to the request URL.
Note: The HTTP/1.1 does not impose any upper limit on the length. However server/clients using HTTP/1.0 may
not support unreasonably long length.

Deploying and Packaging:


The process of installing a web application is known as deployment. While deploying a web application we need
to create a folder/directory structure as per J2EE specification for web applications, which is independent of web-
server/web-container. Putting resources of a web application in the appropriate folders/directories in the standard
folder/directory hierarchy is called packaging.
The design and development process in web applications are clearly separated from those of deployment and
packaging. As discussed earlier a web application is a collection of many different types of files (resources). A typical
web application might include:-
• Servlets and Helper classes • Applet Classes
• HTML Pages • Jar files
• Images, Audio and Video files • A deployment descriptor and other
• Java Server Pages(JSP Pages) configuration file.
A web application is organized with a structured hierarchy of directories, with particular types of files stored in
particular directories. These directories can then be packaged into a Web Application Archive (WAR) file.
RIX
AT
M

The requirements for Developing & Hosting Web Applications:


The following are the most essential requirements for developing and hosting web applications:
1. A Programming Model and an API –for developing and hosting web applications.
2. Server-side Running Support –This includes support for network services and a runtime for executing the
applications.
3. Deployment Support –Deployment is the process of installing the application on the server. Deployment could
also include customizing the application. For building and running web applications, the J2EE provides the
following to meet each of the above requirements:
• Java Servlets and Java Server Pages(JSP):-These are building blocks for developing web Applications in
J2EE. Java Servlets and JSP are called the Web Components.
• Web Container for Hosting Web Applications:-The web container is essentially a java runtime providing an
implementation of the java servlets API and other facilities for JSP pages. The Web container is responsible
for initializing, invoking and managing the life cycle of java servlets and JSP.
• Packaging Structure and Deployment Descriptor:-The J2EE specification defines a packaging structure for
web applications. The specification also defines a deployment descriptor for each web applications. The
deployment descriptor is an XML file that lets you customize the web application at deployment time.

Directory Structure:
The directory structure of a web application has two parts:
1. A directory WEB-INF that contains the resources, which are not to be directly downloaded to a client. This
Directory is private. The client does not have direct access to the files in this directory. The WEB-INF
directory typically contains dynamic resources such as servlets, as well as configuration files.
Matrix Computers (Page 6 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

2. A directory that contains those resources that are intended to be public ally available. This includes all the
subdirectories of this directory, except the private WEB-INF directory. This Directory typically contains
static resources such as HTML and image files. The JSP files, which have static as well as dynamic
contents, are also stored in this directory.
For example, a web-application could have the directory structure.

MyApp- is the root directory of the web application.

Public Resources- Files in MyApp (or subdirectories excluding WEB-INF)


Files in images folder (or subdirectories)
Files in documents folder (or subdirectories)
RIX
AT
M

Private Resources- Files contained within the WEB-INF directory. These are resources that are only accessible to
the web container.

Public Resources:
A public resource is any file that is accessible to the client of the web application. Typical public resources are:
• HTML, XML and JSP
• Image, Audio and Video files.
• Java Applets- classes as well as jar files containing applets.
• Microsoft office documents: word, Excel, etc.

Client browsers can download these resources unchanged and render them as required. For example, when
an HTML page includes <APPLET> tag that refers to an applet in a jar file, the web container delivers the JAR file to
the client browser unchanged.
Typically, the container reads the static resources from the file system, and writes the contents directly to the
network connection. The interpretation of the contents of theses resources is the responsibility of the client browser. In
order to help the browser render the file correctly, the container sends the MIME type of the file. These MIME types
can be set in the deployment descriptor of the web application.
Note: Although JSP pages are included as public resources in a web application; the container does not show them
directly to clients. The container automatically converts JSP Pages into Servlets. The servlet is then compiled and
invoked to generate the response for the client. However, since a JSP Page is often considered more near to an HTML
document than a java class, JSP Pages are also included under public resources.

Private resources:
Matrix Computers (Page 7 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Private resources are certain resources that clients should not load directly. There may be files that the client
should not view, such as configuration files or they may be files that the container must perform some processing on
before sending the response to the client, like servlets. These private resources are stored in the WEB-INF directory,
or its subdirectories.
The types of resources that clients should not download directly include:
• Servlets-These components include application logic, and possibly access to other resources such as
databases.
• Any other files in the web application that servlets access directly.
• Resources that meant for execution or use on the server side, such as java class files and JAR files of classes
used by your servlets.
• Temporary files created by your applications.
• Deployment descriptors and other configuration files.
These resources are private and as such are accessible only their own web application and the container. In order to
accommodate private resources the web container requires the WEB-INF directory to be present in your application.
If your web application does not contain this directory it will not work.

The WEB-INF directory contains:


• A web.xml file (Deployment descriptor).
• A directory named classes. This stores server-side Java class files such as servlets and other classes.
• A lib directory. It contains JAR files used by the web application.

Advantage of the structure:


1. Each application exists in a ‘sand-box’. The public and private resources of an application that the container
may be running.
2. When a new application is added to the J2EE server, we can simply add the appropriate context root in the
deploy tool of the reference implementation, without distributing any other application.
3. The Container knows where to look for classes. This means that you do not need to explicitly add these classes
and JAR files to the CLASSPATH.
4. The difference between a conventional web server and a web container is that each web application has its
own document root.
5. Similar to the public resources, private resources of different web applications are stored in different folders.
RIX
AT
M

6. According to the Servlet specification a container should load classes/JAR files of each web application using
a different class loader. It is for this reason that servlets, JSP Pages and other classes that are part of one web
application cannot see classes in other applications
Thus even if you deployed the same web application twice (each mapping to a different URL), as for as
container is concerned, they are two entirely different applications. Such applications cannot share information. As a
result, web containers create a virtual partitioning of web applications within the container.

Deploying Web Application:


A web application can be deployed simply by creating the directory structure and putting the files/resources in
the appropriate folders as discussed in the previous section. We can also deploy the application using a WAR file,
which is described in the next section.
The folder structure is independent of the web-server (and web-container). But the folder under which the
structure is to be created may differ from server to server. For example, the structure must be created in webapps
folder if you are using Tomcat as the server.

Web Archive Files:


The various directories and files that make up a web application can be packaged into a web application
archive (WAR) file. The process is similar to the packaging of java class files into JAR files. The purpose of the
packaging is the same; it is to provide a simplified way to distribute Java class files and their related resources. WAR
files can be created using the same jar tool that is used to create JAR files. The web application can be deployed as a
WAR file, rather than the unpacked collection of directories and files.
Example: jar –cf MyApp.war *
This command packs all the contents under the current directory, including subdirectories into an archive file called
MyApp.war.
Matrix Computers (Page 8 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

-c option is used for creating a new archive file.


-f option is used to specify the target archive file name.
If the verbose option is specified using –v, the names of the files and directories included in the archive will be
output to the screen.
You can use the following command to view the contents during WAR file creation:
Jar –cvf MyApp.war
Note: Instead of including all the contents, you may select individual files and subdirectories while creating WAR files.
You can also use a standard ZIP to create and manipulate WAR files. Note that jar-tool automatically create the META-
INF sub-directory and its contents.

Deploying a WAR File:


Any servlet 2.2 or higher complaint server will automatically deploy an application packaged as WAR file, as
long as the location of a WAR file is explicitly stated or war file is copied into appropriate folder.

When should WAR file be used?


1. Should be used when deploy the final application.
2. During development try to use auto reload feature for java classes.
Mapping Request to Applications:
In a Web container each web application is associated with context and all resources in a web application exist
relative to the context.

Tips to create servlets:


1. Write a public class by extending HttpServlet class.
2. If request method is get then override doGet(), method is post then override doPost(). If you are unknown to
request method then override service() method.
3. The default request method (in form tag of HTML) is get. In hyperlink the request method is also get.
4. Save servlet class by using .java extension.
5. Compile as a normal .java file and save .class file in classes directory of WEB-INF folder.
6. Check that WEB-INF directory is in uppercase.
7. Create web.xml file in WEB-INF directory.
8. The root tag of web.xml should be <web-app>. Write appropriate syntax. If there is an error in web.xml file then
RIX
AT
M

application will not start.


9. If you are making some changes in Servlet class then compile it again and save into classes folder.
10. If you are using Tomcat Server and making changes in application then Restart tomcat server or reload
application, otherwise changes may not effect.
11. Write servlet class using packages. Writing a servlet class without package is discouraging.
12. Use naming conventions for servlets provided by Sun Microsystems.

Web Servers:
There are many web server’s available in industry. Some popular web server’s are:- Apache web server - the
HTTP web server, Apache Tomcat, Microsoft Windows Server 2003 Internet Information Services (IIS), Jigsaw, Sun
Java System Web Server, Bea Weblogic Server, IBM WebSphere Server. Tomcat is one of the most popular open
source web sever for deploying and running web applications

Tomcat Server:
Apache Tomcat is a Web Server not an application server. You can change port number for apache tomcat at
the time of installation. By default it listens on port number 8080. To change port number after installation
1. Open tomcat\conf directory and then open server.xml in notepad.
2. Look for the following code in server.xml:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
3. delete 8080 port number and write a new port number and save server.xml. Don’t change any other coding.
4. Now Start Tomcat and use port number given by you in server.xml.
Matrix Computers (Page 9 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

If there is any error regarding your application or any exception. To find out the errors go to Tomcat\logs
directory and search for stderror_date text file. When we use System.out.print() in web applications then it gives output
in Tomcat\logs directory’s stdout_date file. Like today is 17-march-2010 and you are running your application then
error will be present in stderr_20100317 and output will be present in stdout_20100317.

Tomcat Installation:
The installation process is described for tomcat 5.5/6.0:
1. Download the setup file (says apache tomcat 6.0.20.exe) from the apache web site.
2. Make sure J2SE is installed on your machine. If JDK (J2SE) is installed in directory c:\JDK1.6 then the
environmental variable JAVA_HOME should be set to c:\JDK1.6 but it is not mandatory.
3. Double click on the setup-file to install the tomcat. The installer will guide you through the entire installation
process.
4. When it asks for destination folder you can specify any location (like C:\Tomcat 6.0 or D:\Tomcat6.0). This
directory is known as tomcat’s home directory. The CATALINA_HOME environment variable points to this
folder.
5. The installer then asks for port number, username and password. The default port number is 8080; you can
change it or make it your port number. The default user name is admin, you can also change it. And insert your
password.
6. The installer then asks of the path of J2SE (JDK) or JRE (Java Runtime Environment) installed on the machine.
By default Tomcat selects path form JAVA_HOME or you can choose path to another JRE installed on your
machine.
So if Tomcat is installed in C:\Tomcat6.0 and JDK is installed in C:\JDK6.0 The environmental variable
CATALINA_HOME= C:\Tomcat6.0
JAVA_HOME= C:\JDk6.0

Tomcat Installation Directory has these folders:


1. bin – executables (tomcat6.exe to start the tomcat)
2. lib – it has jar files visible to web applications as well as internal tomcat code.
3. conf – server level configuration.
• server.xml – for configuration tomcat server.
• web.xml – contains default configuration for all the web applications.

RIX

4. logs log files .


AT
M

5. server – server web applications, admin (server administration), manager.


6. shared – classes visible to all the web applications, but not to internal tomcat code.
7. temp – temporary files.
8. webapps – user web applications (deploy or create your web application in this directory), tomcat
example applications.
9. work – session information, jsp compilation files.

JBoss Server:
JBoss is an application server, it is build upon tomcat server. To handle web application JBoss internally uses
tomcat server.
1. To install JBoss double click on installer.jar file or use command
java –jar installer.jar.
2. Select language English and
3. click next->next->next
4. To uninstall JBoss double click on uninstaller.jar or use java –jar uninstaller.jar command.

Suppose you installed JBoss in C:\Program Files\jboss-4.0.4RC1 directory then the home directory for JBoss is jboss-
4.0.4RC1.
1. Double click on bin\run.bat or run.jar file to start JBoss Server.
2. To stop the server just use ctr+c on DOS window on which server is started..
3. Deploy or create applications in \server\default\deploy directory structure.
4. If you are creating application in \server\default\deploy directory itself then use war extension with your
application, the rest process is same as creating application using Tomcat.
Matrix Computers (Page 10 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

JBoss also listens port number 8080, to change port number go to \server\default\deploy\jbossweb-
tomcat55.sar and open server.xml in notepad to change port number. The code in server.xml may be like this:
<Connector port="8080" address="${jboss.bind.address}"
maxThreads="250" strategy="ms" maxHttpHeaderSize="8192"
emptySessionPath="true"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true"/>

Note You must ensure that you have a JAVA_HOME environment variable that points to the location of the directory
where you installed J2SE JDK.
Like JAVA_HOME
C:\Program Files\Java\jdk1.6.0_01

print() vs. println() in advance java:-


print() and println() both prints on same line in browser. If your output is in HTML form and want to print in
second line use break tag <br> of HTML language in print() or println() function.

Example:-
PrintWriter out=response.getWriter();
out.print(“name”);
out.print(“<br>”);
out.print(“fname”);
out.close();
Note:- After use close the PrintWriter object using close() method.

Port:-
A port is a connection between a server and a client. Ports are identified by positive integers. Port is a software
notion, not a hardware notion, so there may be many of them. A service is associated with a specific port
Typical port numbers:
21—FTP, File Transfer Protocol
25—SMTP, Simple Mail Transfer Protocol
RIX
AT
M

53—DNS, Domain Name Service


80—HTTP, Hypertext Transfer Protocol
8080—HTTP (used for testing HTTP)

Example 1 My First Application:- Testing Application


index.html
1. <html>
2. <head>
3. <title> Testing Application Matrix computers</title>
4. </head>
5. <body>
6. <h1>Welcome to Matrix Computers</h1>
7. <form action=testingapp method=post>
8. Username <input type=text name=username><br>
9. Password <input type=password name=password><br>
10. <input type=submit Value=Submit>
11. </form>
12. </body>
13. </html>
web.xml
1. <web-app>
2. <display-name>Testing Application</display-name>
3. <servlet>
Matrix Computers (Page 11 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

4. <servlet-name>Testing</servlet-name>
5. <servlet-class>TestingApp</servlet-class>
6. </servlet>
7. <servlet-mapping>
8. <servlet-name>Testing</servlet-name>
9. <url-pattern>/testingapp</url-pattern>
10. </servlet-mapping>
11. </web-app>
TestingApp.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class TestingApp extends HttpServlet
5. {
6. public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
7. {
8. ServletContext sc=getServletContext();
9. String nm=sc.getServletContextName();
10. String username=request.getParameter("username");
11. String password=request.getParameter("password");
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14. out.print("<html>");
15. out.print("<body>");
16. out.print("Username is "+username);
17. out.print("<br>");
18. out.print("Passwod is "+password);
19. out.print("<br>");
20. out.print("Display Name is "+nm);
21. out.print("</body>");
22. out.print("<html>");
RIX
AT
M

23. out.close();
24. }
25. }

Structure of Testing Application:-


Matrix Computers (Page 12 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Steps from Development to Deployment:-


Step 1: Create the following structure in your folder say D:\matrix
RIX
AT
M

Step 2: Write code for index.html and save/copy it into folder testingapp
Step 3: Write code for TestingApp.java servlet and save\copy it into src folder.
Step 4: Compile the TestingApp.java file (servlet) so that the package hierarchy is created in the WEB-
INF/classes folder.
javac –d D:\matrix\testingapp\WEB-INF\classes TestingApp.java
Note: - While compiling, make sure that either j2ee.jar or servlet.-api.jar file is in classpath.
The server-api.jar file will be present in the C:\Tomcat6.0\lib
Step 5: Write code for web.xml and save it in WEB-INF folder.
Step 6: Copy the testingapp from D:\matrix\testingapp and paste into C:\Tomcat6.0\webapps.
Step 7: Start the Tomcat Server.

Accessing Testing Application:


Matrix Computers (Page 13 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Step 1: Open browser (Internet Explorer) and write URL= http://localhost:8080/testingapp/ or


http://localhost:8080/testingapp/index.html

Here http stands for Http Protocol, localhost is server address, You can also put 127.0.0.1 (IP Address) instead of
localhost, 8080 is port number.

The following will be displayed in the browser:

Step 2: Fill up the form data and Submit form on server.


Write username like “Matrix”
Write Password like “Computers”.
Click on Submit Button. Your Browser will display like:
RIX
AT
M

Deploying using .war file


Step 1: Create war file of your application. Move to testingapp folder (D:\matrix\testingapp) and give the
following command. jar –cf testingapp.war *
Check that testingapp.war file is created or not.
Step 2: Copy the testingapp.war file into webapps folder of Tomcat server.
OR
Access Tomcat manager through the URL: http://localhost:8080/manager/html and deploy war file.
Matrix Computers (Page 14 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Load on Startup:
<servlet>
<servlet-name>.................</servlet-name>
<servlet-class>.................</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
The load-on-startup element is used to load the servlet automatically into memory when the web container
starts up. Loading a servlet means instantiating the servlet and calling its init method. You use this element to avoid
delay in the response for the first request to the servlet, caused by the servlet loading to memory.
The content of a load-on-startup value is either empty or an integer number. The value indicates the order of
loading into memory by the web container. For example, if there are two servlet elements and both contain load-on-
startup sub-element, the servlet with a lower number in the load-on-startup sub-element is loaded first. If the value of
the load-on-startup is empty or a negative number, it is up to the web container to decide when to load the servlet. If
two servlets have the same value for their load-on-startup sub-elements, the web container is free to choose which
servlet to load first.

Welcome Files:
index.html, index.jsp and index.htm are default welcome files for your application. You can change welcome
file using web.xml.
Code:
<web-app>
<welcome-file-list>
<welcome-file>myfile.html</welcome-file>
<welcome-file>yourfile.html</welcome-file>
</welcome-file-list>
</web-app>
If you are using the above code and myfile.html is available then welcome page will be myfile.html not index.html. If
myfile.html is not present the yourfile.html will be displayed as welcome page. If both files myfile.html and yourfile.html
are not available then welcome page will not be displayed. By default index.html will not be displayed in this case
otherwise if welcome tag is missing then server will display index.html file by default.
RIX
AT
M

Context parameters:
<web-app>
<context-param>
<param-name>address</param-name>
<param-value>Mansarovar</param-value>
</context-param>
</web-app>

The <context-param> tag should be child tag of <web-app> tag because it is for whole application. These are available
for all the servlets of your application.

Init Parameters:
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
<param-name>faculty</param-name>
<param-value>XYZ</param-value>
</init-param>
</servlet>

The <init-param> tag should be child tag of <servlet> tag because init parameters are servlet specific parameters.
These are available in defined servlet only (like in MyServlet only) not in other servlets.
Matrix Computers (Page 15 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Applications using Context Parameters and Init Parameters:-


init stands for initialization, param stands for parameter. We can retrieve a context or init parameter from
web.xml by using getInitParameter(String name) method present in both ServletContext and ServletConfig objects.
To get context and config object call getServletContext() and getServletConfig() methods directly because these are
inherited methods in your application.

ServletContext context=getServletContext();
and
ServletConfig config=getServletConfig();
String name= config.getInitParameter(“name”);//for init parameters
String course= context.getInitParameter(“course”);// for context/application parameters

Note:-<context-param> two times with same name, application won’t start.


1. Different name, Different value Ok.
2. Different name, Same value Ok.
3. Same name, Different value NOT Ok.
4. Same name, Same value NOT Ok.

Note:-<init-param> two times with same name application will work properly.
1. Different name, Different value Ok.
2. Different name, Same value Ok.
3. Same name ,Same value Ok.
4. Same name, Different Value Ok. The second init-param’s value will be considered.

IDE(Integrated Development Environment):-


An IDE is a software application that provides comprehensive facilities to computer programmers for software
development. An IDE normally consists of:
• a source code editor
• a compiler and/or an interpreter
• build automation tools
• a debugger
RIX
AT
M

Some Popular IDE’s are:-


• Eclipse by Eclipse Foundation Inc.
• Netbeans by Sun Microsystems
Working on Eclipse:
1. Download Eclipse Zip file from eclipse website. http://www.eclipse.org
2. Set JAVA_HOME environment variable with your jdk’s home directory.
3. Unzip the eclipse.zip, you will get a folder named eclipse.
4. Inside eclipse folder find out eclipse.exe.
5. Double click on eclipse.exe, This will open the eclipse platform with welcome screen.

How to Create A Java Project in Eclipse?


1. Select File→New→Project→select Java→Java Project→Next →Next→Finish.
2.You will get your project name in project Explorer(generally present at left side)
3. If src (source folder for .java) is present in project then create packages and classes in src.
4. To create a package Right click on src→New→Package→package name→Finish.
5. To create class Right click on src (creates class without package) or on package/subpackage→class→give class
name→Finish.
6. To Run Project Right click on Project→Run As→Java Application. or Right click on main class and Run As→Java
Application.
Matrix Computers (Page 16 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

RIX
AT
M

How to Create Advance Java (Java EE) Project?


1. Select File→New→Project→(select a wizard) web→Dynamic Web Project→Next→Project Name, Target
Runtime*→Next→Next→Finish.
2. *Target Runtime→New…Button (in middle of Dynamic Web Project)→Select Apache or any other
server→select version say Apache Tomcat 6.0→Next→Tomcat InstalltionDirectory→say C:\Program
Files\Apache Software Foundation\Tomcat 6.0→Finish.
3. click on window Menu→Show View→Navigator.
Navigator is replacement of Project Explorer.
4. In navigator Your Project is there. Project have:
src→Servlet .java files (with or without package)
WebContent→Inside this create HTML and JSP Pages
WebContent/WEB-INF→web.xml
WebContent/WEB_INF/lib→external Jar file or classes(JDBC Connector jar file)
Matrix Computers (Page 17 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

5. src→Right click→New→Other…→web→Servlet→Java Package, Servlet Name→Next→URL Mapping—


select predefined mapping→use --edit remove or add option→Finish.
6. If you are giving mapping at the time of creating servlet then no need to register your servlet in web.xml.
Eclipse will automatically register your servlet.
7. WebContent→Right Click→web→HTML→file name→Next→Finish.
8. Run the application →Right Click on your project→Run as→Run On Server→Chose an Existing or Manually
define a new Server→Next→Next→select update----checkbox→Finish

RIX
AT
M
Matrix Computers (Page 18 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

The Servlet Lifecycle:


The container is a run-time that manages the Servlets. In the case of servlets, the lifecycle events are specified
in the javax.servlet.Servlet interface of the Servlet API. Although the lifecycle management is a container’s
responsibility, as servlet developers, we should make sure that our servlet follow the lifecycle model and that they are
RIX
AT
M

not implemented in a way that contradicts this.


The Servlet interface methods relevant to the servlet lifecycle are init( ) , service ( ), and destroy ( ). The
lifecycle starts with the container calling the init( ) method, and ends with the container calling the destroy method.

The Lifecycle of a servlet consists of the following fundamental stages:


Matrix Computers (Page 19 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

1. Instantiation/Loading: The Web Container creates an instance of the servlet and loads it. When the
Web container is started it loads and initializes the Servlet. The Web container may
delay this stage until the Web container determines which servlet is needed to service
a request. Servlet container loads the Servlet class by using the normal Java class
loading option. Moreover, the servlet class may be loaded from a local file system, a
remote file system, or other network services. If the servlet containers fails to load the
class, it terminates this process. After loading container creates an instance of the
Servlet. If the Servlet does not inherits SingleThreadModel interface then only one
object of Servlet will be created and a seprate thread for each request is started on
this object.
2. Initialization: The Container calls the instance’s init( ) method, which accepts the ServletConfig
object reference as a parameter. This object allows the Servlet instance to access
name-value configured initialization parameters and other container specific details.
The Servlet container creates one ServletConfig object per Servlet declaration in the
deployment descriptor.
3. Service: If the Container has a request for the servlet it calls the servlet instance’s service( )
method.
4. Destroy: Before destroying the instance, the container calls the servlet instance’s destroy ( )
method. After this servlet instance is garbage collected.
5. Unavailable: The instance is marked as unavailable. The unavailable may be temporary or
permanent.

Java Servlet APIs:


The servlet API is specified in two Java extension packages.
1. javax.servlet
2. javax.servlet.http
The classes and interfaces in javax.servlet package are protocol independent. While the second package
javax.servlet.http contains classes and interfaces that are specific to HTTP protocol. Some of the classes/interfaces
in the javax.servlet.http extend those specified in the javax.servlet package.

Overview of the Java Servlet API:


RIX
AT
M

Purpose Class/Interface Meaning


1. Servlet javax.servlet.Servlet (Interface) The classes/interfaces in this category are
Implementation javax.servlet.GenericServlet (Abstract class) meant for implementing servlets. For instance,
javax.servlet.http.HttpServlet (Abstract class) the TestingApp extends the HttpServlet class.
javax.servlet.SingleThreadModel (Interface) To develop our own servlets, we would
implement one or more methods in these
classes/interfaces. When we deploy servlets,
the web container invokes these methods to
control their life cycle and to execute application
logic.
2. Servlet javax.servlet.ServletConfig (Interface) The ServletConfig interface belongs to this
Configuration category. The Servlet API provides various
means of accessing the ServletConfig object
associated with a Servlet. This object provides
access to certain initialization parameters that
can be configured while deploying the Servlet.
3. Servlet Javax.servlet.ServletContext (Interface) The interface javax.servlet.ServletContext
Context allows servlets in an application to share data. It
also provides the methods with which servlets
can access the host web container. Using the
ServletContext object, a servlet can log events,
obtain URL references to resources and set and
Matrix Computers (Page 20 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

store attributes that other servlets in the context


can access.
4. Servlet javax.servlet.servletException(Generic The Java Servlet API specifies two exceptions:
Exceptions Exception) 1. ServletException
javax.servlet.UnavailableException(Temp or 2. UnavailableException.
Permanent ) Typically, servlets throw these exceptions,
which the container then catches to perform
appropriate error handling.
5. Request and javax.servlet.ServletRequest (interface) These objects provide methods to access the
Responses javax.servlet.servletResponse (Interface) underlying input and output streams associated
javax.servlet.http.HttpServletRequest with the client connection. Using these objects,
(Interface) we can read data from the input and write data
javax.servlet.http.HttpServletResponse back to the client.
(Interface)
6. Servlet javax.servlet.RequestDispatcher(Interface) The servlet API also provides an interface
Collaboration javax.servlet.RequestDispatcher with which a
servlet can invoke another servlet, a JSP, or
even a static resource such as an HTML page.
This mechanism helps you to control flow of
logic across multiple servlets and JSP pages
programmatically.
7. Session javax.servlet.http.HttpSession (Interface) A. HTTP, which is the basic protocol for web
Tracking javax.servlet.http.Cookie (Class) application is Stateless. As a result, web
applications cannot recognize multiple requests
from the same HTTP Client as originating from
same place. The session provides this
abstraction. In simple term, a session lets you
group requests into a collected group. In
addition, session management also involves
associating data with each session. The servlet
API specifies the javax.servlet.HttpSession
interface to provide this abstraction.
RIX
AT
M

B. The javax.servlet.http.Cookie is used to


create cookies. Cookies are part of Session
Management/Tracking.
8. Filtering javax.servlet.Filter (Interface) The servlet API has a mechanism with which we
javax.servlet.FilterChain (Interface) can introduce code (called a filter) to participate
javax.servlet.FilterConfig (Interface) in the containers request / response process.
Filters are a new feature of the Java Servlet API
version 2.3. They do not generally create
requests/responses; rather, they modify or
adapt requests and responses to and from a
web resource, which could have static or
dynamic content.
9. Context javax.servlet.ServletContextListener A. Implement this interface to receive
Listeners:- javax.servlet.ServletContextEvent notifications about changes to the servlet
javax.servlet.ServletContextAttributeListener context of the web application
javax.servlet.ServletContextAttributeEvent B. Event class for notifications about changes to
the servlet context.
C. Implement this interface to receive
notifications of changes to the attribute list on
the servlet context
D. Event class for notifications about changes to
the attributes of the servlet context
Matrix Computers (Page 21 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Request javax.servlet.ServletRequestListener A. Implement this interface to receive


Listeners:- javax.servlet.ServletRequestEvent notifications about changes to the servlet
javax.servlet.ServletRequestAttributeListener request.
javax.servlet.ServletRequestAttributeEvent B. Event class for notifications about changes to
the servlet request.
C. Implement this interface to receive
notifications of changes to the attribute list on
the servlet request.
D. Event class for notifications about changes to
the attributes of the servlet request.
Http Session javax.servlet.http.HttpSessionListener A. Implement this interface to notify changes to
Listeners:- javax.servlet.http.HttpSessionEvent the list of active sessions.
javax.servlet.http.HttpSessionBindingListener B. Class to represent event notifications for
javax.servlet.http.HttpSessionBindingEvent changes to sessions.
C. This interface causes an object to be notified
when it is bound or unbound from a session.
D. Sent to an object that implements
HttpSessionBindingListener when the object is
bound or unbound from the session.
10. Other javax.servlet.http.HttpUtils A. Provides a collection of methods that are
Classes javax.servlet.ServletRequestWrapper useful in writing HTTP servlet.
javax.servlet.ServletResponseWrapper B. Provides implementation of the
javax.servlet.ServletInputStream ServletRequest interface to receive request
javax.servlet.ServletOutputStream from a servlet.
C. Provides implementation of the
ServletResponse interface to send response to
a servlet.
D. Provides an input stream for reading binary
data from a client request.
E. Provides an output stream for sending binary
data to the client.
RIX
AT
M

Web servers with Java servlet implementation, such as Tomcat, Weblogic, JBoss etc. use most of the
interfaces and classes in the above table. In fact apart from the various listener interfaces, there is only one class
(javax.servlet.http.HttpServlet) and one interface (javax.servlet.Filter) that are left for you to implement when building
web applications.
The container creates the rest of the runtime objects that are part of your application. Why is this so? A web
container is an application framework with a runtime environment. In the Framework, application objects are created
and invoked by the runtime. While invoking methods on the application objects, the container has to construct the
objects of the arguments. For example, in TestingApp servlet, the container creates and passes the HttpServletRequest
and HttpServletResponse objects as arguments to the service() method.
In the same fashion, the container creates all other objects (such as ServletContext, ServletConfig,
HttpSession and so on) that a servlet can access directly or indirectly.

1. Servlet Implementation API:


A. The Servlet Interface:-(public interface javax.servlet.Servlet).
This interface contains abstract methods that all Servlets must implement. In the OOPS paradigm, an
object can communicate with another object as long as the first object reference the second object with a
known interface. It need not know the name of the actual implementing class. In the case of the Servlet API,
the javax.servlet.Servlet is the interface that containers use to reference servlets. All servlets are sub classes
of javax.sevlet.Servlet interface directly or indirectly.
When you write a servlet, you must implement this interface directly or indirectly. You will most likely
always implement the interface indirectly by extending either the javax.servlet.GenericServlet or
Matrix Computers (Page 22 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

javax.servlet.httpServlet classes. When implementing the javax.servlet.Servlet interface, the following five
methods must be implemented:
• public void init(ServletConfig config)
• public void service(ServletRequest request, ServletResponse response)
• public void destroy( )
• public ServletConfig getServletConfig( )
• public string getServletInfo( )

• public void init(ServletConfig config) throws ServletException


Once the servlet has been instantiated, the web container calls the init( ) method. The purpose of this
method is to allow a servlet to perform any initialization required before being invoked against HTTP requests.
The container passes an object of type ServletConfig to the init( ) method. A servlet can access its configuration
data using the ServletConfig object.
The init( ) method throws a ServletExpection in the event that it does not catch normally. The Servlet
specification guarantees that the init( ) method will be called exactly once on any given instance of the servlet,
and the init( ) method will be allowed to complete (provide that it does not throw a ServletException) before
any requests are passed to the Servlet. Some of the typical tasks that can be implemented in the init( ) methods
are:
• Read configuration data from persistent resources such as configuration files (Configuration files like in
Tomcat: server.xml, tomcat-users.xml etc. are used to configure applications. In server.xml we can change
port number. In tomcat-users.xml we can change name and password of Tomcat users.).
• Read initialization parameters using the ServletConfig object from web.xml file.
• Initialization one-time activities such as registering a database driver, a Connection Pool, or a Logging service.

• public void service(ServletRequest request, ServletResponse


response) throws servletException, IOException
This is the entry point for executing the application logic in a servlet. The container calls this method
in response to incoming requests. Only after the servlet has been successfully initialized will the service( ) method
be called. The service method takes two arguments, implementing the javax.servlet.ServletRequest and
javax.servlet.ServletResponse interfaces respectively. The request object provides methods to access the
RIX
AT
M

original request data, and the response object provides methods with which the servlet can build a response.
This method will be called again & again for every request from different users.

• public void destroy( )


The container calls this method before removing a servlet instance out of service. This might accrue if
it needs to free some memory or if the web server is being shutdown. Before the container calls this method,
it will give the remaining service threads time to finish executing (subject to some timeout period), so that the
destroy ( ) method is not called while a service ( ) call is still underway. After the destroy method is called, the
container does not route requests to the servlet.
Activities that can be implemented in the destroy ( ) methods include: Performing cleanup tasks, such
as closing any open resources, closing a connection pool, or even informing another applications/ system that
the servlet will no longer be in service.

• public ServletConfig getServletConfig( )


This method should be implemented to return the ServletConfig that is passed to the servlet, during
the init( ) method.

• public String getServletInfo( )


This method should return a String object containing information about the Servlet (for example,
author, creation date, description and so on) This is available to the web container, should it wish to display,
for example, a list of servlets installed together with their descriptions.
Matrix Computers (Page 23 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Example 2 Program implementing Servlet interface:-


index.html
1. <html>
2. <head>
3. <title>MyServlet</title>
4. </head>
5. <body>
6. <form method=post action=callMyServlet>
7. Click on Submit Button to invoke Servlet.
8. <input type=submit value="Submit">
9. </form>
10. </body>
11. </html>
MyServlet.java
1. import java.io.IOException;
2. import javax.servlet.Servlet;
3. import javax.servlet.ServletConfig;
4. import javax.servlet.ServletException;
5. import javax.servlet.ServletRequest;
6. import javax.servlet.ServletResponse;
7. public class MyServlet implements Servlet
8. {
9. ServletConfig sc;
10. public void init(ServletConfig config) throws ServletException
11. {
12. sc = config;
13. System.out.print("Servlet Initialization");
14. }
15. public ServletConfig getServletConfig()
16. {
17. return sc;
18. }
RIX
AT
M

19. public String getServletInfo()


20. {
21. return "matrix computers";
22. }
23. public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException
24. {
25. System.out.print("Service Method");
26. }
27. public void destroy()
28. {
29. System.out.print("Destroy Method");
30. }
31. }
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>myservlet</servlet-name>
4. <servlet-class>MyServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>myservlet</servlet-name>
8. <url-pattern>/callMyServlet</url-pattern>
9. </servlet-mapping>
Matrix Computers (Page 24 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

10. </web-app>
Output:-
Output of this program will be shown in stdout_date file in C:\Program Files\Apache Software
Foundation\Tomcat 6.0\logs folder.
Note:- When you are implementing Servlet Interface implement all the methods of Servlet Interface.
Note:- If same servlet is register two times, application doesn’t start. means <servlet>tag two times with same
servlet-name not allowed.
Note:-Different URL Patterns for same servlet it will work properly. You can give same url-pattern to two different
servlets but it will run the second servlet.

B. The GenericServlet Class: (public abstract class javax.servlet.GenericServlet implements Servlet,


ServletConfig, Serializable)
The Servlet implementation class must be a subtype of the javax.servlet.Servlet interface. Therefore
the implementation class needs to implement all the (five) methods declared in the javax.servlet.Servlet
interface to perform the respective operations. However, most of the Servlets do not need the initializing and
destroying operations, but still we need to implement all the methods declared in the javax.servlet.Servlet
interface. To solve this problem, the Servlet API provides an adapter class, GenericServlet. The GenericServlet
class provides a basic implementation of all the methods of the Servlet interface (except service() method).
This is an abstract class, and all subclasses should implement the service( ) method.
The GenericServlet class also implements the ServletConfig interface. This allows the servlet
developer to call the ServletConfig methods directly without having to first obtain a ServletConfig object. Each
of these methods delegates the calls to the respective methods in the stored ServletConfig object.

The abstract class has following methods:-


• public void destroy():-This method is called by the Servlet container to indicate that the Servlet instance is
being taken out of service.
• public String getInitParameter(String):-This method is used to return the value of servlet initialization
parameter of the given name or null if named parameter is not available. This method calls
getInitParameter(String) method of ServletConfig class.
For Example:-
public class GenericServlet implements Servlet, ServletConfig
RIX
AT
M

{
private transient ServletConfig config;
public String getInitParameter(String name)
{
return config.getInitParameter(name);
}
}
• public Enumeration getInitParameterNames():- This method returns all the names of the servlet initialization
parameters as an enumeration of String objects. This method returns an empty enumeration if the Servlet does
not contain any initialization parameters.
• public ServletConfig getServletConfig():-This method returns the reference of the ServletConfig object.
Using this object we can read init-parameters from web.xml file which are servlet specific.
• public ServletContext getServletContext():-This method returns the reference of the ServletContext object.
Using this object we can read configuration parameters from web.xml file which are application specific.
• public String getServletInfo():-It returns the information about the Servlet in String format. The
implementation of this method given by GenericServlet returns an empty String.
• public void init(ServletConfig) throws ServletException:- The init (ServletConfig config) method stores
the ServletConfig object in a private transient instance variable (called config). You can use the
getServletConfig( ) method to access this object. However, if you choose to override this method, you should
include a call to super.init (config). Alternatively, you can override the overloaded no-argument init( ) method
in the GenericServlet class. If you override init(ServletConfig config) and not calling super.init(config) then
config object will not be initialized. Means you are unable to get config object through getServletConfig();
Matrix Computers (Page 25 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

• public void init() throws ServletException:- This is an alternative to init(ServletConfig). Instead of overriding
init(ServletConfig) it is easy to override init() method because we have to call super(config) in
init(ServletConfig) but in init() method there is no need to call super(config). init(ServletConfig) also calls init()
method after calling super().
• public void log(String message):- This method writes the name of the servlet and the message argument to
the web container’s log. Writes the specified message to a servlet log file. It first writes servlet's name which
is having this log(string msg)method. Tomcat home directory’s →logs directory, you will find files like
localhost.2010-04-06 in logs. Open the localhst.today’sdate.txt file to see the log message.
• public void log(String message, Throwable t):- This method includes a stack trace for the given Throwable
exception in addition to the servlet name and message. The actual implementation of the logging mechanism
is container-specific, although most of the containers use text files for logging purposes. This method writes a
message and a stack trace for a given Throwable exception to the servlet log file, by writing the servlet's name.
The log file may be having syntax like localhost.today’sdate.txt
• public abstract void service(ServletRequest,ServletResponse)throws ServletException, IOException:-
This is an abstract method which we have to override if implementing GenericServlet class.
• public String getServletName():- This method returns the name of the Servlet in String format which is written
in <servlet-name> tag of web.xml file (Deployment Descripter file).

For Example:
Overriding init(ServletConfig) method(wrongly):-
public class MyGeneric extends GenericServlet
{
public void init(ServletConfig config) throws ServletException
{
System.out.print("init method");
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
System.out.print("My Generic Servlet class");
ServletConfig config=getServletConfig();
// Here config object is assigned to null because getServletConfig() method will
RIX
AT
M

//return null.
}
}

Overriding init(ServletConfig) method(correctly):-


public class MyGeneric extends GenericServlet
{
public void init(ServletConfig config) throws ServletException
{
super.init(config);//calling super.init(config) to initialize config of super.
System.out.print("init method");
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
System.out.print("My Generic Servlet class");
ServletConfig config=getServletConfig();
// Here config object is assigned to ServletConfig object
}
}

Overriding init() method :-


public class MyGeneric extends GenericServlet
Matrix Computers (Page 26 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

{
public void init() throws ServletException
{
System.out.print("init method");
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
System.out.print("My Generic Servlet class");
ServletConfig config=getServletConfig();
// Here config object is assigned to ServletConfig object
}
}
If you are not overriding init(ServletConfig config) method. Then init(ServletConfig config) method
will be inherited into your servlet class. The inherited method init(ServletConfig config) have following
code:
pubic void init(ServletConfig config)
{
super.init(config);
init();
}
The above method have a calling statement to invoke init() method. The use of init() method (init()
with no arguments) is to simplify the initialization code without disturbing init(ServletConfig config)
method.

Example 3 Program using GenericServlet:


index.html
1. <html>
2. <head>
3. <title>MyServlet</title>
4. </head>
5. <body>
RIX
AT
M

6. <form method=post action=generic>


7. Click on Submit Button to invoke Servlet.
8. <input type=submit value="Submit">
9. </form>
10. </body>
11. </html>
MyGeneric.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import java.util.Enumeration;
5. import javax.servlet.ServletConfig;
6. import javax.servlet.ServletContext;
7. import javax.servlet.ServletException;
8. import javax.servlet.ServletRequest;
9. import javax.servlet.ServletResponse;
10. public class MyGeneric extends GenericServlet
11. {
12. public void init(ServletConfig config) throws ServletException
13. {
14. super.init(config);
15. }
16. // or
17. //public void init() throws ServletException
Matrix Computers (Page 27 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

18. //{
19. // System.out.print("init without parameters");
20. //}
21. public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
22. {
23. ServletContext context=getServletContext();
24. ServletConfig config=getServletConfig();
25. String name=getServletName();
26. String info=getServletInfo();//This method returns an empty string
27. String param=getInitParameter("user");
28. PrintWriter out=response.getWriter();
29. out.print(name);
30. out.print(info);
31. out.print(param);
32. Enumeration en=getInitParameterNames();
33. while(en.hasMoreElements())
34. {
35. out.print(en.nextElement());
36. }
37. log("You will get it in localhost.txt of Tomcat logs folder");
38. log("You get it in localhost.txt with an exception in logs folder of Tomcat", new Exception());
39. }
40. }
web.xml
1. <web-app>
2. <display-name>GenericServlets</display-name>
3. <servlet>
4. <display-name>MyGeneric</display-name>
5. <servlet-name>MyGeneric</servlet-name>
6. <servlet-class>com.matrix.MyGeneric</servlet-class>
7. <init-param>
RIX
AT
M

8. <param-name>user</param-name>
9. <param-value>Matrix</param-value>
10. </init-param>
11. </servlet>
12. <servlet-mapping>
13. <servlet-name>MyGeneric</servlet-name>
14. <url-pattern>/generic</url-pattern>
15. </servlet-mapping>
16. </web-app>

C. The HttpServlet Class:- (public abstract class javax.servlet.http.HttpServlet extends


GenericServlet)
The HttpServlet class extendes GenericServlet, and provides an HTTP specific implementation of the
servlet interface. This will most likely be the class that all of your servlets will extend. It is an abstract class with
no abstract methods. It does not override init, destroy, and other methods. However it implements the service()
method, which is an abstract method in GenericServlet. The other commonly used methods in this class are:
• public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
This is an implementation of the service( ) method in the GenericServlet. This method casts the request
and response objects to HttpServletRequest and HttpServletResponse and calls the following overloaded
service( ) method. Therefore, you should not override the above method.
Matrix Computers (Page 28 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

• protected void service (HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException
This overloaded method takes HTTP specific request and response object, and is invoked by the first
method above. HttpServlet implements this method to be a dispatcher of HTTP requests. The
javax.servlet.ServletRequest interface provides a getMethod( ) method that returns the type of the HTTP
method associated with the request. For instance, for GET request, this method returns ”GET” as a string. The
service() method uses this string to delegate the request to one of the methods doXXX( ). The
javax.servlet.http.HttpServlet provides default implementation of all these methods.
In general, you should avoid overriding this method as it affects the default behavior of the service( )
method. The only situation that requires you to override it is when you want to change the default behavior, or
when you want to include additional processing common to doXXX ( ) methods.
The sequence of method calls when the container receives a request for a servlet is :
1. The container calls the public service ( ) method.
2. The public service ( ) method calls the protected service ( ) method after casting the arguments to
HTTPServletRequest and HttpServletResponse respectively.
3. protected service ( ) method calls one of the doXXX ( ) methods, depending on the type of the HTTP
request method.

• protected void doGet (HttpServletRequest request, HttpServletResponse


response)
Called by the server (via the service method) to allow a servlet to handle a GET request. Overriding this method
to support a GET request also automatically supports an HTTP HEAD request. A HEAD request is a GET
request that returns no body in the response, only the request header fields. If the request is incorrectly
formatted, doGet returns an HTTP "Bad Request" message. When a form is using get method then the form
details both name and values are shown in URL of Browser. The get method is not useful when you are going
to submit a secure page. Suppose you inserted password is in ●●●●●● form in password filed but in URL you
can see your password like- /servlet11?username=matrix&password=computers.
• protected void doPost (HttpServletRequest request,
HttpServletResponse response)
RIX
AT
M

Called by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST
method allows the client to send data of unlimited length to the Web server a single time and is useful when
posting information such as credit card numbers If the HTTP POST request is incorrectly formatted, doPost
returns an HTTP "Bad Request" message.

Some other methods of HttpServlet class are following:


• protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
Called by the server (via the service method) to allow a servlet to handle a DELETE request
• protected void doHead(HttpServletRequest req, HttpServletResponse resp)
Receives an HTTP HEAD request from the protected service method and handles the request.
• protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
Called by the server (via the service method) to allow a servlet to handle a OPTIONS request.
• protected void doPut(HttpServletRequest req, HttpServletResponse resp)
Called by the server (via the service method) to allow a servlet to handle a PUT request.
• protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
Called by the server (via the service method) to allow a servlet to handle a TRACE request.
• protected long getLastModified(HttpServletRequest req)
Returns the time the HttpServletRequest object was last modified, in milliseconds since midnight January 1,
1970 GMT.

Example 4 doGet() Method demo.


index.html
Matrix Computers (Page 29 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

1. <html>
2. <body>
3. <form method=get action=servlet1>
4. Firstname <input type=text name=firstname value=""><br>
5. Lastname <input type=text name=lastname value=""><br>
6. E-mail Id <input type=text name=email value=""><br>
7. Mobile No <input type=text name=mobile value=""><br>
8. <input type=submit value=Submit>
9. </form>
10. </body>
11. </html>
Servlet11.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet1 extends HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. String firstname=request.getParameter("firstname");
14. String lastname=request.getParameter("lastname");
15. String email=request.getParameter("email");
16. String mobile=request.getParameter("mobile");
17. out.print("Welcome : ");
18. out.print(firstname);
19. out.print("<br>");
RIX
AT
M

20. out.print("Your Lastname is : ");


21. out.print(lastname);
22. out.print("<br>");
23. out.print("Your E-mail id is : ");
24. out.print(email);
25. out.print("<br>");
26. out.print("Your mobile number is : ");
27. out.print(mobile);
28. }
29. }

Output:-
Matrix Computers (Page 30 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

RIX
AT
M

Example 5 JDBC Demo, Servlets are like core java classes. Accessing database using JDBC in servlet is same as
accessing JDBC in simple core java application. The following web application is interacting with Database using JDBC:
register.html
1. <html>
2. <head>
3. <title>JDBC Demo</title>
4. </head>
5. <body>
6. <center>
7. <form method=post action=register>
8. <h2><font color=blue>Matrix Research and Computer Education</font></h2>
9. <h3>Welcome to Login Page</h3><br><br>
10. <table border=1 width=300 cellpadding=4 cellspacing=4>
11. <tr>
12. <td>Username</td>
13. <td><input type=text name=username size=30 maxlength=30></td>
14. </tr>
15. <tr>
16. <td>Password</td>
17. <td><input type=password name=password size=30 maxlength=30></td>
18. </tr>
Matrix Computers (Page 31 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

19. <tr>
20. <td>E-Mail</td>
21. <td><input type=text name=email size=30 maxlength=40></td>
22. </tr>
23. <tr>
24. <td></td>
25. <td>&nbsp;&nbsp;&nbsp;&nbsp;<input type=submit value=Register></td>
26. </tr>
27. </table>
28. <br>
29. </form>
30. <hr>
31. <br><a href=view.html>Click to View Details</a><br>
32. </center>
33. </body>
34. </html>
view.html
1. <html>
2. <head>
3. <title>View Student Details</title>
4. </head>
5. <body>
6. <center>
7. <form method="post" action="viewdetails">
8. <h2><font color="blue">Matrix Research and Computer Education</font></h2>
9. <h3>Welcome to View Page</h3><br>
10. <table>
11. <tr>
12. <td>Username</td>
13. <td><input type="text" name="username" size=30></td>
14. </tr>
15. <tr>
RIX
AT
M

16. <td></td>
17. <td><input type="submit" value="View Details"></td>
18. </tr>
19. </table>
20. </form>
21. <br><a href=register.html>Go to Home Page</a>
22. </center>
23. </body>
24. </html>
RegisterDetails.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.SQLException;
7. import java.sql.Statement;
8. import javax.servlet.ServletException;
9. import javax.servlet.http.HttpServlet;
10. import javax.servlet.http.HttpServletRequest;
11. import javax.servlet.http.HttpServletResponse;
12. public class RegisterDetails extends HttpServlet
13. {
14. protected void doPost(HttpServletRequest request, HttpServletResponse response)
Matrix Computers (Page 32 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

15. throws ServletException, IOException


16. {
17. String username= request.getParameter("username");
18. String password=request.getParameter("password");
19. String email=request.getParameter("email");
20. PrintWriter out=response.getWriter();
21. Connection con=null;
22. Statement stmt=null;
23. try
24. {
25. Class.forName("com.mysql.jdbc.Driver");
26. }
27. catch(ClassNotFoundException ex)
28. {
29. ex.printStackTrace();
30. }
31. try
32. {
33. con=DriverManager.getConnection("jdbc:mysql://localhost:3306/matrix","root","root");
34. stmt=con.createStatement();
35. String query="insert into register values('"+username+"','"+password+"','"+email+"')";
36. stmt.execute(query);
37. out.print("<h1>You are Registered Successfully</h1>");
38. out.print("<br><br>");
39. out.print("<h4><a href=view.html>Click here to View Details </a></h4><br>");
40. out.print("<h4><a href=register.html>Home Page</a></h4>");
41. }
42. catch(SQLException ex)
43. {
44. out.print("Please insert data correctly or you are already registered");
45. out.print("<a href=register.html>Home Page</a>");
46. ex.printStackTrace();
RIX
AT
M

47. }
48. finally
49. {
50. try
51. {
52.
53. stmt.close();
54. }
55. catch(SQLException ex)
56. {
57.
58. }
59. try
60. {
61. con.close();
62. }
63. catch(SQLException ex)
64. {
65.
66. }
67. }
68. }
69. }
ViewDetails.java
Matrix Computers (Page 33 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.ResultSet;
7. import java.sql.SQLException;
8. import java.sql.Statement;
9. import javax.servlet.ServletException;
10. import javax.servlet.http.HttpServlet;
11. import javax.servlet.http.HttpServletRequest;
12. import javax.servlet.http.HttpServletResponse;
13. public class ViewDetails extends HttpServlet
14. {
15. protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
16. {
17. int count=0;
18. String username=request.getParameter("username");
19. PrintWriter out=response.getWriter();
20. Connection con=null;
21. Statement stmt=null;
22. ResultSet rs=null;
23. try
24. {
25. Class.forName("com.mysql.jdbc.Driver");
26. }
27. catch(ClassNotFoundException ex)
28. {
29. ex.printStackTrace();
30. }
31. try
RIX
AT
M

32. {
33. con=DriverManager.getConnection("jdbc:mysql://localhost:3306/matrix","root","root");
34. stmt=con.createStatement();
35. String query="select * from register where username='"+username+"'";
36. rs=stmt.executeQuery(query);
37. while(rs.next())
38. {
39. username=rs.getString("username");
40. String password=rs.getString("password");
41. String email=rs.getString("email");
42. out.print("<center><h2> Your Username is:"+username);
43. out.print("<br>Your Password is: "+password);
44. out.print("<br>");
45. out.print("Your E-Mail is:"+email+"</h3>");
46. out.print("<br><br>");
47. count++;
48. out.print("<a href=view.html>Go Back</a>");
49. }
50. if(count==0)
51. {
52. out.print("<h2>No Record Found<br>");
53. out.print("<a href=view.html>Try Again.... </a></h2>");
54. }
55. }
Matrix Computers (Page 34 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

56. catch(SQLException ex)


57. {
58. out.print("<h3>Sorry</h3>");
59. out.print("<h3>Your username is not correct or <br> User Doesn't Exists</h3>");
60. out.print("<a href=view.html>Try Again.... </a></h2>");
61. ex.printStackTrace();
62. }
63. finally
64. {
65. try
66. {
67. rs.close();
68. stmt.close();
69. }
70. catch(SQLException ex)
71. {
72. ex.printStackTrace();
73. }
74. try
75. {
76. con.close();
77. }
78. catch(SQLException ex)
79. {
80. ex.printStackTrace();
81. }
82. }
83. }
84. }
web.xml
1. <web-app>
2. <servlet>
RIX
AT
M

3. <servlet-name>RegisterServlet</servlet-name>
4. <servlet-class>com.matrix.RegisterDetails</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>RegisterServlet</servlet-name>
8. <url-pattern>/register</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>view</servlet-name>
12. <servlet-class>com.matrix.ViewDetails</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>view</servlet-name>
16. <url-pattern>/viewdetails</url-pattern>
17. </servlet-mapping>
18. <welcome-file-list>
19. <welcome-file>register.html</welcome-file>
20. </welcome-file-list>
21. </web-app>
Query in database
Mysql:
create database matrix;
use matrix;
create table register(username varchar(30) unique key not null, password varchar(30), email varchar(30));
Matrix Computers (Page 35 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Oracle:
Driver name: oracle.jdbc.driver.OracleDriver
URL: jdbc:oracle:thin:@localhost:1521:orcl
Create database matrix or database that you are using in your program.
create table register(username varchar2(30), password varchar2(30), email varchar2(30));
OutPut:-

RIX
AT
M
Matrix Computers (Page 36 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Note:- In above program instead of overriding service() method we can also define doPost() method.

D. The SingleThreadModel Interface:- (public interface javax.servlet.singleThreadModel)


The Servlet API specifies a special maker interface called javax.servlet.SingleThreadModel. During
the lifetime of a servlet that does not implement this interface; the container may send multiple service requests
in different threads to a single instance. This means that implementation of the service( ) method should be
thread safe. However, what is the alternative if the service ( ) method of a servlet is not thread safe?
The java Servlet API specifies the SingleThreadModel interface for this purpose. Servlets can
implement the SingleThreadModel interface ( in addition to implementating the javax.servlet.Servlet interface
or extending one of its implementation classes) in order to inform the container that it should make sure that
only one thread is executing the servlet’s service( ) method at any given moment.
For SingleThreadModel servlets, Containers may follow one of the following approaches to ensure
that each servlet instance is invoked in a separate thread:

• One Instance per Request:-


In this approach, the container allocates separate instance for each request. Normally the container
maintains a pool of servlet instances to avoid frequent creation and garbage collection, which may drastically
RIX
AT
M

affect the performance. For each incoming request, the container allocates a Servlet instance from the pool,
and upon completion of the service, the container returns the instance to the pool.

• Request Serialization:-
In this approach, the container maintains a single instance of the servlet. However, since the container
cannot send multiple requests to the instance at the same time, the container serializes the requests. This
means that new requests will be kept waiting while the current request is being served.

• Fixed size Configurable Instance pool:-


In reality, a combination of these two approaches is more practical, so that the container could maintain
a reasonable number as instances in the pool, while still serializing requests if the number of requests exceeds
the number of instances in the pool.

Note that the SingleThreadModel is resource intensive, particularly if a large no. of concurrent requests
is expected for the servlet. The effect of the SingleThreadModel is that the container invokes the service ( )
method in a synchronized block. This is equivalent to using the synchronized keyword for the servlet’s service
( ) method. Accordingly, when there are hundreds or even thousands of concurrent requests to the web
container, the container may either serialize requests to the same instance of the servlet, or create that many
hampered due to serialization. In the later case, the container encounters more object allocation (which
includes more object creation overhead and memory usage).

However, in cases where only a few statements of the service ( ) method are not thread safe, you
should consider reducing the scope of synchronization of the service ( ) and explicitly synchronize such blocks
Matrix Computers (Page 37 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

using the synchronized keyword. Depending on how short such synchronization blocks are, this approach
could improve performance.

Note: - We should always consider redesigning our applications in order to avoid the
SingleThreadModel or thread synchronization. If we cannot avoid them, it is important to be aware of the
performance implications. With any thread synchronization code, you are potentially blocking a web container
thread
Example:- implementing SingleThreadModel interface

public class MyServlet implements SingleThreadModel


{
----------
----------
----------
}
This interface ensures that servlets handle only one request at a time. This interface has no
methods. As of Java Servlet API 2.4, it is a deprecated interface. It means it is not advisable to use this
interface.

2. Servlet Configuration API / Working with Initialization Parameters:-


In most cases, while developing Web applications (Servlets), some data elements required to process the
request are not known or may be availabel with the test data at the development phase. Moreover, the test data coded
in the Servlet at the deployment phase needs to be changed when it is configured in the production environement. For
example, suppose we have a Servlet that performs a login related operation. Here we obtained the database
connection and to do this, we used the database user name and password(scott and tiger in our case). However the
actual DB user name and password are availabel only at the time of deploying the application. In such situations,
instead of hard coding the data in the Servlet, we want to configure the data externally from the Servlet and then inject
it into the Servlet. To do this, the Servlet container supports the ability to store startup and configuration information for
a Servlet as initialization parameters (called init parameters and context init parameters). Init parameters are specific
to the Servlet configured in the deployment descriptor, but context init parameters are specific to all or multiple Servlets
configured in the deployment descriptor.
RIX
AT
M

The configuration information contains initialization parameters (set of name/value pairs), the name of the
servlet, and a javax.servlet.ServletContext object, this gives the servlet information about the container. The
initialization parameters and the name of a servlet can be specified in the deployment descriptor (web.xml). For
example:
<web-app>
<servlet>
<servlet-name>Admin</servlet-name>
<servlet-class>com.wrox.admin.AdminServlet</servlet-class>
<init-param>
<param-name>driverClass</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>jdbcURL</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:orcl</param-value>
</init-param>
</servlet>
</web-app>

A. The javax.servlet.ServletConfig Interface:- (public interface javax.servlet.ServletConfig)


This Interface specifies the following methods:
• public String getInitParameter(String name):-Returns a String containing the value of the named
initialization parameter, or null if the parameter does not exist.
Matrix Computers (Page 38 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

• public Enumeration getInitParameterNames( ) :-Returns the names of the servlet's initialization


parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization
parameters.
• public ServletContext getServletContext ( ) :-Returns a reference to the ServletContext in which the
caller is executing.
• public String getServletName( ) :-Returns the name of this servlet instance. The name may be provided
via server administration, assigned in the web application deployment descriptor, or for an unregistered
(and thus unnamed) servlet instance it will be the servlet's class name.

Obtaining a Reference to ServletConfig:-


In the java API, a servlet can obtain a reference to the javax.servlet.ServletConfig object in the
following ways:

a. During Servlet Initialization:-


The init( ) methods of the Servlet interface and the GenericServlet class have an argument of type
ServletConfig. During initialization of a servlet, the web container creates this argument and passes it to the
init( ) method. When you are overriding the init ( ) method, you can access the ServletConfig object.
However, when you are overriding the init( ) method in the GenericServlet class, you should explicitly
invoke super.init( ) as follows:

public init (ServletConfig config)


{
super. init(config);
----------------------
}
The call to super.init(config) ensures that the TestingApp Servlet class actually maintains a reference
to the ServletConfig object. The implementation of the GenericServlet class actually maintains a reference to
the ServletConfig object (as a private transient instance variable), and requires that super.init( ) be called in
subclass.

b. Using the getServletConfig( ) method:-


Servlets can also access the ServletConfig objects by calling the getServletConfig ( ) method. This
RIX
AT
M

method is specified in the Servlet Interface. Alternatively, servlets extending the GenericServlet, or its subclass
HttpServlet can also call the method of the ServletConfig interface directly. This is because the GenericServlet
also implements the ServletConfig Interface.

3. Servlet Context API / Working with Context Initialization Parameters


As explained in previous section, the Servlet container supports the ability to store startup and configuaration
information for a Servlet as initialization parameters (init parameters). We also learned how to configure these
parameters and get them into the Servlet. These parameters are configured specific to the Servlet configured in the
deployment descriptor but in some cases, we want to configure data that has to be retrieved into all or multiple Servlets
configured in the deployment descriptor . For example, suppose our Web application contains two Servlets, login and
registration, and we want the Driver class name and the JDBC URL of both Servlets to establish a connection. For this,
the context initialization parameters (context init paramenters) are provided under Servlet specification.
To configure a Servlet’s context paramenter, use the following tag in <web-app>
<context-param>
<param-name> parameter name </param-name>
<param-value> parameter value </param-value>
</context-param>
Context initialization parameters are available to the Servlet at any time, that is during initialization, client
servicing and destroying of the Servlet. For a web application, we can configure one or more context parameters, when
the parameter name should be unique.

A. The javax.servlet.ServletContext Interface:- (public interface


javax.servlet.ServletContext)
Matrix Computers (Page 39 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

This Interface specifies the following methods:


• public ServletContext getContext(String):- Returns a ServletContext object that corresponds to a specified
URL on the server.
• public String getContextPath():-Returns the folder name of our application.
• public int getMajorVersion():-Returns the major version of the Java Servlet API that this servlet container
supports.
• public int getMinorVersion():- Returns the minor version of the Servlet API that this servlet container
supports.
• public String getMimeType(String):- Returns the MIME type of the specified file, or null if the MIME type is
not known.
• public Set getResourcePaths(String):- Returns a directory-like listing of all the paths to resources within the
web application whose longest sub-path matches the supplied path argument.
• public URL getResource(String) throws MalformedURLException:- Returns a URL to the resource
that is mapped to a specified path.
• public InputStream getResourceAsStream(String):- Returns the resource located at the named path as
an InputStream object.
• public RequestDispatcher getRequestDispatcher(String):- Returns a RequestDispatcher object that acts
as a wrapper for the resource located at the given path.
• public RequestDispatcher getNamedDispatcher(String):- Returns a RequestDispatcher object that acts as
a wrapper for the named servlet.
• public Servlet getServlet(String) throws ServletException:- (Deprecated) This method was originally
defined to retrieve a servlet from a ServletContext. In this version, this method always returns null and remains
only to preserve binary compatibility. This method will be permanently removed in a future version of the Java
Servlet API.
• public Enumeration getServlets():- (Deprecated)This method was originally defined to return an
Enumeration of all the servlets known to this servlet context. In this version, this method always returns an
empty enumeration and remains only to preserve binary compatibility. This method will be permanently
removed in a future version of the Java Servlet API.
• public Enumeration getServletNames():- (Deprecated) This method was originally defined to return an
Enumeration of all the servlet names known to this context. In this version, this method always returns an
empty Enumeration and remains only to preserve binary compatibility. This method will be permanently
RIX
AT
M

removed in a future version of the Java Servlet API.


• public void log(String):- Writes the specified message to a servlet log file, usually an event log.
• public void log(String, Throwable):- Same as GenericServlet class.
• public String getRealPath(String):- Returns a String containing the real path for a given virtual path.
• public String getServerInfo():-Returns the name and version of the servlet container on which the servlet is
running.
• public String getInitParameter(String):- Same as ServletConfig interface.
• public Enumeration getInitParameterNames():-Same as ServletConfig interface.
• public Object getAttribute(String):- Returns the servlet container attribute with the given name, or null if
there is no attribute by that name.
• public Enumeration getAttributeNames():-Returns an Enumeration containing the attribute names available
within this servlet context.
• public void setAttribute(String, Object):- Binds an object to a given attribute name in this servlet context.
• public void removeAttribute(String):- Removes the attribute with the given name from the servlet context.
• public String getServletContextName():-Returns the name of this web application correponding to this
ServletContext as specified in the deployment descriptor for this web application by the display-name element.

Example 6:-
servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import java.util.Enumeration;
Matrix Computers (Page 40 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

5. import javax.servlet.RequestDispatcher;
6. import javax.servlet.ServletContext;
7. import javax.servlet.ServletException;
8. import javax.servlet.http.HttpServlet;
9. import javax.servlet.http.HttpServletRequest;
10. import javax.servlet.http.HttpServletResponse;
11. public class Servlet1 extends HttpServlet
12. {
13. protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
14. {
15. ServletContext context = getServletContext();
16. PrintWriter out = response.getWriter();
17.
18. context.setAttribute("name", "Matrix Reloaded");
19. context.setAttribute("password", "computers");
20.
21. Enumeration en = context.getAttributeNames();
22. while (en.hasMoreElements())
23. {
24. out.print((String) en.nextElement());
25. out.print("<br>");
26. }
27. out.print("<br>");
28. context.removeAttribute("name");
29. out.print("Attribute having reference name is removed");
30.
31. out.print("<br>");
32. String user = context.getInitParameter("user");
33. out.print("Init param value for user is:" + user);
34. out.print("<br>");
35. Enumeration en1 = context.getInitParameterNames();
RIX
AT
M

36. while (en1.hasMoreElements())


37. {
38. out.print("Init param names: " + en1.nextElement());
39. out.print("<br>");
40. }
41.
42. int majorversion = context.getMajorVersion();
43. int minorversion = context.getMinorVersion();
44. out.print("Major Version: " + majorversion);
45. out.print("<br>");
46. out.print("Minor Version : " + minorversion);
47. out.print("<br>");
48.
49. String mime = context.getMimeType("WEB-INF/web.xml");
50. out.print("MIME type pf web.xml is :" + mime);
51. out.print("<br>");
52. String displayname = context.getServletContextName();
53. out.print("display-name in web.xml is : " + displayname);
54. out.print("<br>");
55. String serverinfo = context.getServerInfo();
56. out.print("Server Information is:" + serverinfo);
57. out.print("<br>");
58. String contextpath = context.getContextPath();
59. out.print("Context path is:" + contextpath);
Matrix Computers (Page 41 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

60. out.print("<br>");
61.
62. String realpath = context.getRealPath("/WEB-INF/web.xml");
63. out.print("The Real Path of web.xml is:" + realpath);
64. out.print("<br>");
65.
66. RequestDispatcher rd = context.getRequestDispatcher("/servlet2");
67. // use forward(req,res) or include(req,res) with rd
68. context.log("You can see this log message in logs folder of TOmcat");
69. out.print("<br>");
70.
71. out.print("URL of web.xml is:-"+ context.getResource("WEB-INF/web.xml"));
72. }
73. }
web.xml
1. <web-app>
2. <display-name>servletContext APP</display-name>
3. <context-param>
4. <param-name>user</param-name>
5. <param-value>Matrix Research</param-value>
6. </context-param>
7. <context-param>
8. <param-name>location</param-name>
9. <param-value>Jaipur</param-value>
10. </context-param>
11. <servlet>
12. <servlet-name>servlet1</servlet-name>
13. <servlet-class>com.matrix.Servlet1</servlet-class>
14. </servlet>
15. <servlet-mapping>
16. <servlet-name>servlet1</servlet-name>
17. <url-pattern>/servlet1</url-pattern>
RIX
AT
M

18. </servlet-mapping>
19. </web-app>
Output:-
Matrix Computers (Page 42 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

RIX

4. Servlet Exceptions API:-


AT
M

This API defines two types of servlet exceptions:


• Javax.servlet.ServletException
• Javax.servlet.UnavailableException
The servlet can throw any of these exceptions to the container to indicate that due to some exceptions,
servlet can not continue its execution. The container will according mark that the servlet is either permanently
or temporarily unavailable.

A. javax.servlet.ServletException
Defines a general exception a servlet can throw when it encounters difficulty. The container sends the
HTPP-500 error to the client.

Constructors:-
• public ServletException ( )
Construct a new Servlet Exception
• public ServletException (String msg)
Constructs a new servlet exception with the specified message. The message can be written to the
server log and/or displayed for the user.
• public ServletException(String msg, Throwable rootcause)
Constructs a new servlet exception when the servlet needs to throw an exception and includes a
parameter corresponding to the “root cause” exception that interfered with its normal operation, and a
description message.
• public ServletException (Throwable rootcause)
Matrix Computers (Page 43 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Constructs a new servlet exception when the servlet needs to throw an exception and includes a
parameter corresponding to the “root cause” exception that interfered with its normal operation.

B. javax.servlet.UnavailableException
Defines an exception that a servlet or filter throws to indicate that it is permanently or temporarily
unavailable. A servlet or filter is temporarily unavailable if it cannot handle request momentarily due to some
system wide problem. For example, a third-tier server might not be accessible or there may be insufficient
memory or disk storage to handle requests . A system administrator may need to take corrective action.
A servlet or filter is permanently unavailable if during its execution an exception occurs which can not
be recovered. Servlet containers can safely treat both types of unavailable exceptions in the same way.
However, treating temporary unavailable effectively makes the servlet container more robust. Specifically, the
servlet container might block requests to the servlet or filter for a period of time suggested by the exception
rather than rejecting them until the servlet container restarts.

Constructors:-
• UnavailableException (String msg)
Constructs a new exception with a description message indicating that the servlet is permanently
unavailable. The container sends the HTTP-404 (permanent unavailable) error to the client.
• UnavailableException (String msg, int seconds)
Constructs a new exception with a descriptive message indicating that the servlet is temporarily
unavailable and giving an estimate of how long it will be unavailable. In some cases, the servlet cannot make
an estimate . For example, the servlet might know that a server it needs is not running but not be able to report
how long it will take to restore the functionality? This can be indicated with a -ve or zero value for the second
argument. The container sends the HTTP-503(Temporary Unavailable) error to the client.
HTTP-500 (for any other ServletException)

Example 7:- Life Cycle Servlet Application


The Example consists of a single servlet called LifeCycleServlet, which demonstrates the various states in the lifecycle
of a typical servlet, including unavailability.
index.html
1. <html>
RIX

2. <head>
AT
M

3. <title> Life Cycle Servlet </title>


4. </head>
5. <body>
6. <p><a href=life>Click to access life cycle of the Servlet</a></p>
7. </body>
8. </html>
LifeCycleServlet.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. import java.util.*;
5. public class LifeCycleServlet extends HttpServlet
6. {
7. Vector states;
8. Random random;
9. int waitInterval;
10. public static final int DEFAULT_WAIT_INTERVAL=10;
11. public LifeCycleServlet ( )
12. {
13. states=new Vector ( );
14. random=new Random ( );
15. waitInterval=DEFAULT_WAIT_INTERVAL;
16. states.add(createState("Instantiation"));
Matrix Computers (Page 44 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

17. }
18. public void init()throws ServletException
19. {
20. states.add(createState("Initialization"));
21. String waitIntervalString=getServletConfig().getInitParameter("waitInterval");
22. if (waitIntervalString!=null)
23. {
24. waitInterval=new Integer(waitIntervalString).intValue();
25. }
26. }
27. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
28. {
29. if(random.nextBoolean())
30. {
31. states.add(createState("Unavailable from doGet..."));
32. throw new UnavailableException("unavailable from doGet",waitInterval);
33. //not available for waitInterval seconds
34. //throw new UnavailableException("Unavailable from doGet")
35. //throw new ServletException("Unavailabe from doGet...")
36. }
37. states.add(createState("Service"));
38. response.setContentType("text/html");
39. PrintWriter out=response.getWriter();
40. //Send acknowledgment the browser
41. out.print("<html><head><title> LifeCycleServlet </title></head>");
42. out.print("<body>");
43. out.print("waitInterval:="+waitInterval);
44. out.print("<h1>LifeCycleSevlet: State Story</h1>");
45. out.print("<p><a href=\"life\"> Reload </a></p>");
46. for(int i=0;i<states.size();i++)
47. out.print("<p>"+ states.elementAt(i)+"</p>");
RIX
AT
M

48. out.print("</body></html>");
49. out.close();
50. }
51. public void destroy()
52. {
53. states.add(createState("Destroy"));
54. System.out.println("Flushing state history of LifeCycle servlet. ");
55. for(int i=0;i<states.size();i++)
56. System.out.println(states.elementAt(i).toString());
57. }
58. private String createState(String message)
59. {
60. return "[" +(new Date()).toString()+"]"+message;
61. }
62. }
web.xml
1. <web-app>
2. <display-name>Life Cycle Servlet</display-name>
3. <servlet>
4. <servlet-name>life</servlet-name>
5. <servlet-class>LifeCycleServlet</servlet-class>
6. <init-param>
7. <param-name>waitInterval</param-name>
8. <param-value>5</param-value>
Matrix Computers (Page 45 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

9. </init-param>
10. </servlet>
11. <servlet-mapping>
12. <servlet-name>life</servlet-name>
13. <url-pattern>/life</url-pattern>
14. </servlet-mapping>
15. <error-page>
16. <error-code>503</error-code>
17. <location>/error.html</location>
18. </error-page>
19. <error-page>
20. <error-code>500</error-code>
21. <location>/error1.html</location>
22. </error-page>
23. </web-app>
error.html
1. <html>
2. <meta http-equiv="pragma" content="no-cache">
3. <head>
4. <title> lifecycleservlet unavailable </title>
5. </head>
6. <body>
7. <h1>lifecycle servlet unavailable</h1>
8. <p>lifecycle servlet is temporarily unavailable(503)
9. click this <a href="http://localhost:8080\lifecycle\life">again</a></p>
10. </body>
11. </html>
error1.html
1. <html>
2. <meta http-equiv="pragma" content="no-cache">
3. <head>
4. <title> lifecycle servlet unavailable </title>
RIX
AT
M

5. </head>
6. <body>
7. <p>Any other lifecycle servlet Exception(500)</p>
8. </body>
9. </html>
Output:-
Matrix Computers (Page 46 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

RIX
AT
M

5. Request and Response API


The javax.servlet.HttpServletRequest and javax.servlet.HttpServletResponse interfaces are used for
accessing HTTP requests and responses. The important classes/interfaces in this category are:
• javax.servlet.ServletRequest
• javax.servlet.ServletResponse
• javax.servlet.http.HttpServletRequest
• javax.servlet.http.HttpServletResponse

A. The javax.servlet.ServletRequest Interface:-


This interface of Servlet API abstracts data from the client to the Servlet. The ServletRequest object
encapsulates the information requested by a client to the Servlet and provides data, such as the request parameters
and headers. The Servlet container creates this object, sets the request information into it, and passes it to the Servlet
as an argument of the service() method.
The ServletRequest object is active within the scope of the Servlet’s service method. The Web container
recycles these objects to avoid the performance overhead of request object creation. For example, when the
Matrix Computers (Page 47 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

processing of a request is complete, the Servlet container sets the request object to default and uses the same object
for other requests. However, it does not use the same request objects to serve more than one request at a time.
Apart from request parameters, web containers or Servlet/JSPs can attach attributes to requests. The Servlet
API specification specifies three different approaches for storing and retrieving attributes:
• Attaching attributes to request objects
• Storing attributes in Http Session object
• Servlet context.
The JSP specification provides an additional mechanism using page context to store and retrieve attributes.
Each of these approaches provides the notion of a scope for the attributes to exit: In the case of attributes attached to
the request objects, the lifetime of these attributes is that of the request itself.
In the servlet, an attribute is a named Java language object. While setting an attribute, you assign a name to
the attribute, and while retrieving the attribute, specify the same name. Names are String objects. The purpose of
attributes in the request scope is to allow the container or another servlet to send additional data to a servlet or JSP.
For the application developers, this is useful when using the Request Dispatcher object to forward request from one
servlet to another. The following methods can be used to manage attributes in the request context

Methods for Request Parameters:-


The following methods can be used to access the request parameters. In the case of HTTP request, these
methods can be used for both GET and POST requests.
• public String getCharacterEncoding():-This method returns the name of the character encoding used in the
body of this request.
• public void setCharacterEncoding(String) throws UnsupportedEncodingException:-
• public int getContentLength():-Returns the length, in bytes, of the request body and made available by the
input stream, or -1 if the length is not known.
• public String getContentType():-Returns the MIME type of the body of the request, or null if the type is not
known.
• public ServletInputStream getInputStream() throws IOException:- This method can be used to access the
body of the request using a ServletInputStream object.
• public String getParameter(String):- This will attempt to locate a parameter with the given name (Case-
Sensitive) in the request and return its value. If there are multiple values for a given parameters, then this
method returns the first value in the list. The method returns null if the key is not found in the request.
RIX
AT

• public Enumeration getParameterNames():-This method returns an enumeration of all the parameter names
M

for the request. If the request has no parameters, it returns an empty enumeration.
• public String[] getParameterValues(String):- If a parameter can return multiple values, such as a set of
check boxes, a multi selection-list, or even multiple controls with the same name, this method returns an array
containing the parameter values.
• public Map getParameterMap():-This method returns a java.util.Map containing all request parameters. In
this map, the name of the parameter is the key while its value is the map value. Both keys and values are
strings. Note that this map is immutable and you cannot change the contents of this map.
• public String getProtocol():-Returns the name and version of the protocol when a request is made. For
example, if we make a request by using HTTP1.1, this method returns HTTP/1.1.
• public String getScheme():-Returns the name of the scheme used to handle this request, such as HTTP,
HTTPS or FTP.
• public String getServerName():- Returns the name of the server receiving the request.
• public int getServerPort():-Returns the port number on which the server is running and receives this request.
• public BufferedReader getReader() throws IOException:- This method can be used to access the body of
the request using a buffered reader object.
• public String getRemoteAddr():- Returns the IP address of the client.
• public String getRemoteHost():- Returns the fully qualified name of the client sending the request.
• public void setAttribute(String, Object):-Stores an attribute to a specific client request.
• public void removeAttribute(String):-Removes an attribute to a specific client request.
• public Object getAttribute(String):-Returns the value of the named attribute as an Object form, or returns
null if no attribute of the given name exists.
Matrix Computers (Page 48 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

• public Enumeration getAttributeNames():-This method returns an enumeration of all the attributes


contained in the request. It returns an empty enumeration if there are no attributes in the request.
• public boolean isSecure():-Returns a boolean indicating whether this request was made using a secure
channel, such as HTTPS.
• public RequestDispatcher getRequestDispatcher(String):- Returns a RequestDispatcher object that acts
as a wrapper for the resource located at the given path.
• public String getRealPath(String):- Deprecated. As of Version 2.1 of the Java Servlet API, use
ServletContext.getRealPath(java.lang.String) instead.
• public int getRemotePort():-Returns the Internet Protocol (IP) source port of the client or last proxy that sent
the request.
• public String getLocalName():-Returns the host name of the Internet Protocol (IP) interface on which the
request was received.
• public int getLocalPort():-Returns the Internet Protocol (IP) port number of the interface on which the request
was received.

B. The javax.servlet.http.HttpServletRequest Interface (public interface


HttpServletRequest extends ServletRequest):-
The most commonly used methods in this interface are the methods for accessing request parameters. HTTP
allows you to submit parameters along with a request. In a GET request, these parameters are appended to the request
URL in the form of query String, Whereas in a POST request the parameters are sent within the body of the request.
In any case these parameters are represented as key –value pairs. HTTP does not require that the keys are unique,
so for some keys, there can be list of values. Examples include multiple selection list-boxes or checkbox groups. When
you build an HTML form for GET or POST requests, you specify certain controls using <input> tags. Each control has
a type, such as checkbox, text or submit and can also have a name and/or a value. The name attribute defines the key
by which the value returned to the server will be known. The value attribute has different effects on different controls.
Obviously, if we give more than one <input> tag the same name, we could have several key/value pairs with the same
key as part of our request.
Multiple controls can have the same name. The most common reason for having multiple controls with the
same name is to be able to build sets of radio buttons and check boxes, and multiple-selection select controls. The
radio button set will return the single selected value, and checkboxes or multiple selection select controls will return all
of selected values.
RIX
AT
M

Methods:-
• public String getPathInfo ( ) :-This method returns any extra path information associated with the request
URL. In general, you invoke a servlet using its alias or the class name. For instance, you can access a servlet
MyServlet using URL http://host:port/myApp/MyServlet where myAPP is the application context. However, you
can send additional path information to the servlet say as http://host:port/myApp/MyServlet/matrix. In this case
/matrix is the additional path information returns null if there is no additional path in the request.
• public String getPathTranslated ( ) :-The method translates the extra path information into a real path. For
instance, if the directory corresponding
to myApp application is c:\tomcat5.5\eabapps\myApp\matrix as the translated path. This method returns null
if there is no additional path in the request.
• public String getQueryString():-The method returns the query String associated with the request.
• public String getRequest URI( ):-This method returns URI path associated with the request. In the above
example, this method would
return/myApp/MyServlet/devesh i.e. the path starting with the server root. The query string is excluded.
• public String getRequestURL ( ) :-This method reconstructs the URL that the client used to make this
request. The returned string included the
protocol, Server name, Port and the Server path for this request. The query string is excluded. For instance,
in the above example, this method would return http://host:port/myAPP/MyServlet/matrix .
• public String getServletPath( ) :-This method returns the URI path associated with this Servlet. This excludes
any extra Path information and
query string. For Instance, in the above example, this method would return /myApp/MyServlet as the servlet
path.
Matrix Computers (Page 49 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

• public String getHeader(String name):-The method returns the value of the named header from the HTTP
request. This method returns null if the request does not include the specified header. The header ”host”
returns the name of the machine sending the request. The header “user-agent” returns the browser information.
• public Enumeration getHeaderNames( ) :-This method returns an enumeration of names of request headers.
• public String getMethod ( ) :-This method returns the type of the HTTP request such as GET, POST and so
on.

C. The javax.servlet.ServletResponse Interface (public interface ServeltResponse):-


This is the response counterpart of the ServletRequest object, and abstracts most of the methods necessary
for constructing responses from servlets.

Methods for setting ContentType and Length:-


• public void setContentType(String str):-This method sets content type of the response. If you are using
PrintWriter object to generate the response, before writing the response you should call setContentType() to
set the MIME type of the HTTP response.
• public void setContentLength(int size):-This method sets the content-length header. The client can make
use of this header to know the length of data being sent by the servlet before it starts reading data.

Methods for Output:-


• public ServletOutputStream getOutputStream ( ) :-This method returns a ServletOutputStream object that
can be used for writing binary data in the response. The ServletOutputStream class is a subclass of
java.io.OutputStream. On a given HttpServletResponse object, you should call this method only once. If you
try to call this method more then once, you will encounter an IllegalStateException.
• public PrintWriter getWriter ( ) :-This returns a PrintWriter object that can be used to send character data in
the response. PrintWriter automatically translates java’s internal Unicode characters into the correct encoding
so that they can be read on the client m/c.

Methods for Buffered Output:-


If you are sending a large amount of data in the response, you should consider setting the buffer size to smaller
values, so that the user can start receiving the data quickly. Buffering also allows you to abort the content generated
so far, and restart the generation.
RIX
AT
M

• public void setBufferSize(int size):- Sets the preferred buffer size for the body of the respons
• public int getBufferSize( ) :- Returns the actual buffer size used for the response.
• public void resetBuffer( ):-This method clears content of the underlying buffer without clearing the response
headers or the status code. If the response has already been committed, then method throws an Illegal State
Exception.
• public void flushBuffer( ) :- Forces any content in the buffer to be written to the client.
• public boolean isCommitted( ) :- Returns a boolean indicating if the response has been committed.
• public void reset ( ) :-This method clears content of the underlying buffer as well as the response headers.

D. The javax.servlet.http.HttpServletResponse Interface (public interface


HttpServletResponse extends ServletResponse):-
Some of the important methods are described below:
• public void addCookie(Cookie cookie):-The method adds specified cookie to the response header.
• public String encodeURL (String url):-This method encodes the URL if cookies are off on the client side. It
adds the session to the URL. e.g. “ /servlet;jsessionid=ABC123”
• public void sendError (int status):-Servlets can use this method to indicate standard HTTP status codes. As
seen in the case of LifeCycleservlet, you can specify error pages for different HTTP errors and servlet
exceptions. If there is a matching page for the specified status code, the container sends the specified page
to the client. If there is no page specified, the container sends its default error page indicating the status and
a corresponding message.
• public void sendError (int status, String msg):- Sends an error response to the client using the specified
status.
Matrix Computers (Page 50 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

• public void sendRedirect (String location):-This method sends a redirect response to the client. The client
receives the HTTP response code 302 indicating that temporarily the client is being redirected to the specified
location. If the specified location is relative, this method converts it into an absolute URL before redirecting.

Example 8:- Request and Response


index.html
1. <html>
2. <head>
3. <title>Request Response</title>
4. </head>
5. <body>
6. <center>
7. <form method=post action=request>
8. <table border=1>
9. <tr>
10. <td>Your Name</td>
11. <td><input type=text name=name maxlength=40></td>
12. </tr>
13. <tr>
14. <td>Father's Name</td>
15. <td><input type=text name=fname maxlength=40></td>
16. </tr>
17. <tr>
18. <td>Address</td>
19. <td><input type=text name=address size=40></td>
20. </tr>
21. <tr>
22. <td>MobileNumber</td>
23. <td><input type=text name=mobile size=40></td>
24. </tr>
25. <tr>
26. <td></td>
RIX
AT
M

27. <td><input type=submit value=SubmitDetail></td>


28. </tr>
29. </table>
30. </form>
31. </center>
32. </body>
33. </html>
RequestResponseServlet.java
1. import javax.servlet.ServletException;
2. import javax.servlet.http.*;
3. import java.io.IOException;
4. import java.io.PrintWriter;
5. public class RequestResponseServlet extends HttpServlet
6. {
7. public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
8. {
9. String yourName=request.getParameter("name");
10. String fathersName=request.getParameter("fname");
11. String address=request.getParameter("address");
12. String mobileNumber=request.getParameter("mobile");
13. response.setContentType("text/html");
14. PrintWriter out= response.getWriter();
Matrix Computers (Page 51 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

15. out.print("<center><h2>Your details are passed as parameter to servlet</h2>");


16. out.print("<br>");
17. out.print("<br>");
18. out.print("<br>");
19. out.print("<h3>Your Name is "+yourName);
20. out.print("<br>");
21. out.print("Father's Name is "+fathersName);
22. out.print("<br>");
23. out.print("Address is "+address);
24. out.print("<br>");
25. out.print("and Mobile Number is " +mobileNumber);
26. out.print("<br></h3></center>");
27. out.close();
28. }
29. }
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>requestservlet</servlet-name>
4. <servlet-class>RequestResponseServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>requestservlet</servlet-name>
8. <url-pattern>/request</url-pattern>
9. </servlet-mapping>
10. </web-app>
Output:-
RIX
AT
M
Matrix Computers (Page 52 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

6. Servlet Collaboration:-
In the typical servlet model, a servlet received an HTTP request, executes some application logic, and prepares
the response. This completes one request – response trip for the client. However, there are several scenarios in which
the basic model is not adequate:
1. A Servlet receives an HTTP request from a client, processes application logic, and a JSP drives the
response. In this case the servlet is not responsible for response generation. instead, the JSP page is responsible for
the dynamic content.
2. A Servlet receives an HTTP request from the client, processes application logic, partially and hands over
the request to another servlet. The second servlet completes the application logic and either prepares the response or
requests a JSP page to drive the response.
In both the scenarios, the servlet is not completely responsible for processing a request. Instead it delegates
the processing to another servlet (or JSP page, which is equivalent to a servlet at run time).
RIX
AT
M

Request Dispatching:-
Request dispatching allows a servlet or a JSP Page to dispatch a request to another servlet ( or a JSP, or even
a plain HTML page) which will then be responsible for any further processing and for generating the response. when
the web container receives a request, it constructs request and response objects and invokes one of the servlet’s
services methods with the request and response objects. This is a process of the web container dispatching a request
to a servlet. What if the servlet wants to dispatch the same request to another servlet after preliminary processing?
For this purpose, the first servlet should be able to obtain a reference to the second servlet. Using this reference
the first servlet can dispatch the request to the second servlet. in simple terms this is the request dispatching. The java
Servlet API has a special interface called javax.servlet.RequestDispatcher for this purpose.

The Request Dispatcher Interface (public interface javax.servlet.RequestDispatcher):-


This interface encapsulates a reference to another web resource at a specified path within the scope of the
same servlet context.

Obtaining a RequestDispatcher Object:-


There are three ways in which you can obtain a RequestDispatcher object for a resource:
1. public RequestDispatcher getRequestDispatcher(Stringpath) (Method of ServletContext):-
2. public RequestDispatcher getNamedDispatcher(String name) (Method of ServletContext):-
3. public RequestDispatcher getRequestDispatcher(String path) (Method of ServletRequest):-
The two getRequestDispatcher() methods accept a URL path(specified in <url-pattern> tag of web.xml)
referring a target resource (one on ServletRequest and one on ServletContext). However, the
getRequestDispatcher method on servlet context requires the absolute path (that is, the path name should
Matrix Computers (Page 53 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

begin with ’/’ otherwise it throws IllegalArgumentException). For example if you have a
servlet/mywebApp/servlet1, and want to get the requestDispatcher object for /mywebApp/servlet2, you should
specify the complete path relative to the root context. Here the root context is /mywebApp, and the absolute
path is /servlet2. The same method on servletRequest accepts both absolute and relative paths. In the above
example, you could now also use servlet2 as the path. If these methods locate a resource, it creates a
RequestDispatcher object that wraps the resource and returns the resultant object. If the resource cannot be
located by using the path, it creates a RequestDispatcher object to add the message “The requested resource
(<path>) is not available” in the output, and returns the resultant object.
The getNameDispatcher() method on the servlet context is a convenience method that accepts a name
associated with servlet. This is the same name that you specify in the deployment descriptor (web.xml) in the
<servlet-name> element. Note that the target object (except for static resources) should implement the same
type of Http request that the original servlet receives.

Methods in RequestDispacher:-
• public void forward(ServletRequest request, ServletResponse response)
Forwards the servlet's request object to another static or dynamic resource. Including Other Resources in the
Response. It is often useful to include another web resource (html, jsp, servlet, image) in the response returned
from a web component. To include another resource, invoke the include method of a RequestDispatcher
object: If the included resource is static, the include method enables programmatic server-side includes. If the
resource is a web component, the include() method sends the request to the included web component, then
Container executes the web component, and then include the result of the execution in the response from the
calling servlet. An included web component has access to the request object, but it is limited to access
response object: It can write to the body of the response and commit a response. It cannot set headers or call
any method (for example, setCookie) that affects the headers of the response.
RIX
AT
M

• public void include(ServletRequest request, ServletResponse response)


Includes the processing output of another static or dynamic resource. In a nutshell, this has the same effect as
a programmatic server-side include. Transferring Control to Another Web Component In some applications,
you want to process a request from one servlet and generate the response from another servlet. For example,
you might want to partially process a request and then transfer to another component depending on the nature
of the request. To transfer control to another web component, you invoke the forward method of a
RequestDispatcher. When a request is forwarded, the request URL is set to the path of the forwarded page.
The forward method should be used to give another resource responsibility for replying to the user. If you have
already accessed a ServletOutputStream or PrintWriter object within the servlet, you cannot use this method;
doing so throws an IllegalStateException.You can’t forward the request if you’ve already committed a
response. “committed a response” means sent the response to the client.
Matrix Computers (Page 54 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

With both the include and forward methods the control comes back to the source Servlet only after the target
Servlet’s service method execution has been completed. However in the case of the forward method, before the control
comes to the source Servlet, the response is already committed and ended (that is, we cannot add any more content
into the response).

Example 9 Request Dispatcher:-


index.html
1. <html>
2. <head>
3. <title>Insert title here</title>
4. </head>
5. <body>
6. <h1>Call Servlet1</h1>
7. <a href=servletone>Call Servlet1</a>
8. </body>
9. </html>
ServletOne.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.RequestDispatcher;
RIX
AT
M

4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class ServletOne extends HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. out.print("<h2>This is Servlet One <br> </h2>");
14. RequestDispatcher rd=request.getRequestDispatcher("/servlettwo");
15. rd.forward(request, response);
16. out.close();
17. }
18. }
ServletTwo.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.RequestDispatcher;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
Matrix Computers (Page 55 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

7. import javax.servlet.http.HttpServletResponse;
8. public class ServletTwo extends HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. out.print("<h2>This is Servlet Two</h2>");
14. out.print("<br>");
15. RequestDispatcher rd= request.getRequestDispatcher("/servletthree");
16. rd.include(request, response);
17. out.print("<h4>This is because of Request Disapatcher's include and forward
methods</h4><br> ");
18. out.print("<h4>ServletOne forwards request to servletTwo and ServletTwo includes output of
ServletThree</h4>");
19. }
20. }
ServletThree.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.HttpServlet;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. public class ServletThree extends HttpServlet
8. {
9. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
10. {
11. PrintWriter out=response.getWriter();
12. out.print("<h2> and <br> <br>This is Servlet Three</h2>");
13. }
RIX
AT
M

14. }
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>sone</servlet-name>
4. <servlet-class>ServletOne</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>sone</servlet-name>
8. <url-pattern>/servletone</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>stwo</servlet-name>
12. <servlet-class>ServletTwo</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>stwo</servlet-name>
16. <url-pattern>/servlettwo</url-pattern>
17. </servlet-mapping>
18. <servlet>
19. <servlet-name>sthree</servlet-name>
20. <servlet-class>ServletThree</servlet-class>
21. </servlet>
22. <servlet-mapping>
Matrix Computers (Page 56 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

23. <servlet-name>sthree</servlet-name>
24. <url-pattern>/servletthree</url-pattern>
25. </servlet-mapping>
26. </web-app>
Output:-

RIX
AT
M

Example:-10 Add Subtract Application:-An Example of Request Dispatching


index.html
1. <html>
2. <body>
3. <form action="entry">
4. <b>Operand 1 : <input type="text" name="op1"/>
5. <br>Operand 2 : <input type="text" name="op2"/>
6. <br><input type="submit" name="action" value="Add"/>
7. <input type="submit" name="action" value="Substract"/></b>
8. </form>
9. </body>
10. </html>

ValidationServlet.java
1. package com.matrix;
2. import javax.servlet.*;
3. import java.io.*;
Matrix Computers (Page 57 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

4. public class ValidationServlet extends GenericServlet


5. {
6. public void service (ServletRequest req, ServletResponse resp)
throws ServletException, IOException
7. {
8. try
9. {
10. req.setAttribute("operand1",new Integer(req.getParameter("op1")));
11. req.setAttribute("operand2",new Integer(req.getParameter("op2")));
12. }//closing brace of try block
13. catch(Exception e)
14. {
15. resp.setContentType("text/html");
16. PrintWriter out=resp.getWriter();
17. out.println("Operand1 and Operand2 value should be numbers<br/>");
18. RequestDispatcher rd=req.getRequestDispatcher("/index.html");
19. rd.include(req,resp);
20. return;
21. }//catch
22. String action=req.getParameter("action");
23. RequestDispatcher rd=null;
24. if (action.equals("Add"))
25. rd=req.getRequestDispatcher("/add");
26. else
27. rd=req.getRequestDispatcher("/sub");
26. rd.forward(req,resp);
27. }//service
28. }//class
AddServlet.java
1. package com.matrix;
2. import javax.servlet.*;
3. import java.io.*;
RIX
AT
M

4. public class AddServlet extends GenericServlet


5. {
6. public void service (ServletRequest req, ServletResponse res)
throws ServletException, IOException
7. {
8. int op1=((Integer)req.getAttribute("operand1")).intValue();
9. int op2=((Integer)req.getAttribute("operand2")).intValue();
10. int result=op1+op2;
11. req.setAttribute("operation", "Addition");
12. req.setAttribute("result", new Integer(result));
13. RequestDispatcher rd=req.getRequestDispatcher("/resp");
14. rd.forward(req,res);
15. }//service
16. }//class
SubServlet.java
1. package com.matrix;
2. import javax.servlet.*;
3. import java.io.*;
4. public class SubServlet extends GenericServlet
5. {
6. public void service (ServletRequest req, ServletResponse res)
throws ServletException, IOException
7. {
8. int op1=((Integer)req.getAttribute("operand1")).intValue();
Matrix Computers (Page 58 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

9. int op2=((Integer)req.getAttribute("operand2")).intValue();
10. int result=op1-op2;
11. req.setAttribute("operation", "Subtraction");
12. req.setAttribute("result", new Integer(result));
13. RequestDispatcher rd=req.getRequestDispatcher("/resp");
14. rd.forward(req,res);
15. }//service
16. }//class
ResponseServlet.java
1. package com.matrix;
2. import javax.servlet.*;
3. import java.io.*;
4. public class ResponseServlet extends GenericServlet
5. {
6. public void service (ServletRequest req, ServletResponse res)
throws ServletException, IOException
7. {
8. Integer result=(Integer) req.getAttribute("result");
9. RequestDispatcher rd=req.getRequestDispatcher("/index.html");
10. if (result==null)
11. {
12. rd.forward(req,res);
13. return;
14. /*return is required here since we know that after forward the control comes back
15. to the source servlet, and here we dont want to execute the remaning part
16. of this service if our request is forwarded */
17. }//if
18. res.setContentType("text/html");
19. PrintWriter out=res.getWriter();
20. String op=(String) req.getAttribute("operation");
21. out.println(op+" Result : <b>"+result.intValue()+"</b><br/>");
22. rd.include(req,res);
RIX
AT
M

23. }//service
24. }//class
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>es</servlet-name>
4. <servlet-class>com.matrix.ValidationServlet</servlet-class>
5. </servlet>
6. <servlet>
7. <servlet-name>as</servlet-name>
8. <servlet-class>com.matrix.AddServlet</servlet-class>
9. </servlet>
10. <servlet>
11. <servlet-name>ss</servlet-name>
12. <servlet-class>com.matrix.SubServlet</servlet-class>
13. </servlet>
14. <servlet>
15. <servlet-name>rs</servlet-name>
16. <servlet-class>com.matrix.ResponseServlet</servlet-class>
17. </servlet>
18. <servlet-mapping>
19. <servlet-name>es</servlet-name>
20. <url-pattern>/entry</url-pattern>
21. </servlet-mapping>
Matrix Computers (Page 59 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

22. <servlet-mapping>
23. <servlet-name>as</servlet-name>
24. <url-pattern>/add</url-pattern>
25. </servlet-mapping>
26. <servlet-mapping>
27. <servlet-name>ss</servlet-name>
28. <url-pattern>/sub</url-pattern>
29. </servlet-mapping>
30. <servlet-mapping>
31. <servlet-name>rs</servlet-name>
32. <url-pattern>/resp</url-pattern>
33. </servlet-mapping>
34. </web-app>

7. Session Management:
A servlet receives a request object, extracts parameters (if any) from it, processes any application logic (which
may depend on the request parameters), and finally generates the purpose. Extending this model, you could build
larger web applications by having several servlets, with each servlet performing a well-defined independent task.
The model is adequate so long as the application logic in each of these servlets is atomic-that is, so long as
the application logic depends only on the parameters in the request (and, if applicable, any persistent data such as
data stores in a relational database). For instance, in the Request Response application the servlet gets all the request
data from the request (from text fields), and displays in browser. We can also process these data.

Now consider a familiar web application: An on-line store:-


In a typical online store, the main application that drives the store is a shopping cart. An on-line store provides
you with a browseable interface to a catalog. You san select items in the catalog, and add them to a shopping cart.
Once you have added all the required items to the cart, you proceed to checkout, and place an order for the items in
the cart. However such an application is not as simple as it appears. Where is the shopping cart maintained? Since
the client is ‘thin’, it is the responsibility of the server to maintain the cart not only for you, but for all the other users that
may simultaneously be browsing the catalog and adding items to their respective shopping carts. In order for this
mechanism to work, the server should be able to individually distinguish each user and accordingly, maintain each
RIX
AT
M

shopping cart.
This is a typical requirement for web application where a ‘user activity’ happens across multiple requests and
responses, and the server is required to associate some form of uniqueness to each of the users.

This can be achieved using


➢ Session Tracking or
➢ Servlet context: Servlet in an application can use servlet context to exchange information or collaborate with
other servlets, access resources, log events etc.

Statelessness and Sessions:-


HTTP is a stateless protocol. A client opens a connection and requests some resource or information. The
server responds with the requested resource (if available)’ or sends an HTTP error status. After closing the connection,
the server does not remember any information about the client. So, the server considers the next request from the
same client as a fresh request, with no relation to the previous request. This is what makes HTTP a stateless protocol.
A protocol is stateful if response to a given request may depend not only on the current request, but also on
the outcome of previous requests.
But why is it important to be stateful? A stateful protocol helps you develop complex application logic across
multiple requests and responses. Let’s consider an online bank. When you request a page containing balances of all
your accounts, the server should be able to verify that you are a genuine account holder, and that you have established
your credentials with every request-In fact, each business transaction will be required to occur in a single request. This
is not suitable for long business transaction that ought to happen across multiple requests, such as the online bank, or
shopping cart.

For implementing flexible business transaction across multiple requests and responses, we need two facilities.
Matrix Computers (Page 60 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

• Session:The server should be able to identify that a series of requests are from a single client and responses,
we need single working session.
• State:The server should be able to remember information related to previous requests and other business
decisions that are made for requests. That is, the application should be able to associate state with each
session. In the case of the shopping cart application, possible state could include the user’s favorite item
categories, user profile, or even the shopping cart itself.

Approaches to Session Tracking:-


There are essentially four approaches to session tracking.
• URL rewriting
• Hidden form fields
• Cookies
• Sessions using the Secure Socket Layer(SSL)
Although above four approaches differ in implementation details, all these are base on one simple trick-that is
to exchange some form of a token between the client and the server.
Consider a client C and Server S. when C sends a request to S for the first time, S gives C a unique token.
This token could be a sample or as complex as we wish it to be: a single number, a user name, or a session ID string.
Whenever C visits S again, it also submits the token with the request, S can now recognize C from the token.
This is the essence of session tracking:

This simple technique of session tracking can be adopted in different ways, based on how such a token can
RIX
AT
M

be represented and exchanged. The tokens are exchanged in the above four approaches as described below:

URL Rewriting:-
URL rewriting implies adding session data to the URL path, which is then interpreted by the web container to
associate the request with a session. In URL rewriting , the session data required in the next request is appended to
the URL path. The required session data is retrieved by the web server as request parameters.
In other words: The token or identifier(session data) is embedded in each URL. In each dynamically generated
page, the server embeds an extra query parameter or extra path information, in each URL in the page. When the client
submits requests using such URLs, the token is retransmitted to the server. This approach is called URL rewriting, as
it involves rewriting URLs in the response content to embed the extra token.
Suppose a URL is like action=”servlet1” and now you want to pass username along with this URL then Rewrite
this URL like action=”servlet1?username=matrix”. URL rewriting requires that all pages in application be dynamically
generated. URL rewriting cannot be enforced for static HTML pages, because the unique URL path parameter is
dynamic and differs from user to user.
We can rewrite a URL in anchors also like <a href=”servlet1?username=matrix”>Call Servlet1</a>

Example:-In this example we are inserting username and password in index.html and sending request to Servlet1.
Servlet1 reads the username and password and generates output. Now a form generated by Servlet1’s rewritten URL
having username and password as query string is submitted to Servlet2. Servlet2 reads the rewritten URL information
using getParameter() method.

Example 11:-
index.html
Matrix Computers (Page 61 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

1. <html>
2. <body>
3. <form method=post action=servlet1>
4. Username<input type=text name=username value=""><br>
5. Password<input type=password name=password value=""><br>
6. <input type=submit value=Login>
7. </form>
8. </body>
9. </html>
Servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet1 extends HttpServlet
9. {
10. protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. String username=request.getParameter("username");
14. String password=request.getParameter("password");
15. out.print("Welcome : ");
16. out.print(username);
17. out.print("<form method=post action=servlet2?username="+username+"&
password="+password+">");
18. out.print("<input type=text name=email value=''>");
19. out.print("<input type=submit value=Submit>");
20. out.print("</form>");
RIX
AT
M

21. }
22. }
Servlet2.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet2 extends HttpServlet
9. {
10. protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. String username=request.getParameter("username");
14. String password=request.getParameter("password");
15. String user=request.getQueryString ();
16. out.print(user);
17. String email=request.getParameter("email");
18. out.print("Welcome : ");
19. out.print(username);
20. out.print("<br>Password inserted in index.html is :");
Matrix Computers (Page 62 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

21. out.print(password);
22. out.print("<br>E-mail is : ");
23. out.print(email);
24. }
25. }
Note:- 1. If you are using URL rewriting in a form then use method=post otherwise the URL will not work properly.
2. Don’t give any space anywhere in URL like: action=servlet2? username= “user1”& password=”matrix”.

Hidden Form Fields:-


Hidden form fields is a type of HTML form fields but is not displayed in the view. Similar to other fields, a hidden
form field can also be enclosed within a form. Hidden form fields data in a form are also included in the request while
submitting the form along with the other type of form fields.
Syntax:- <input type=text name=username value=Matrix>
This approach is similar to URL rewriting. Instead of rewriting each URL, the server embeds hidden fields in
each form. When the client submits a form, the additional hidden fields will also be sent in the request. The server can
use these parameters to establish and maintain a session.

Example 12:-
index.html
1. <form method=post action=servlet1>
2. Username<input type=text name=username value=""><br>
3. Password<input type=password name=password value=""><br>
4. <input type=submit value=Login>
5. </form>
Servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
RIX
AT
M

8. public class Servlet1 extends HttpServlet


9. {
10. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. String username=request.getParameter("username");
14. String password=request.getParameter("password");
15. out.print("Welcome : ");
16. out.print(username);
17. out.print("<form method=post action=servlet2>");
18. out.print("<input type=text name=email value=''>");
19. out.print("<input type=hidden name=username value="+username+">");
20. out.print("<input type=hidden name=password value="+password+">");
21. out.print("<input type=submit value=Submit>");
22. out.print("</form>");
23. }
24. }
Servlet2.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
Matrix Computers (Page 63 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet2 extends HttpServlet
9. {
10. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. String username=request.getParameter("username");
14. String password=request.getParameter("password");
15. String email=request.getParameter("email");
16. out.print("Welcome : ");
17. out.print(username);
18. out.print("<br>Password inserted in index.html is :");
19. out.print(password);
20. out.print("<br>E-mail is : ");
21. out.print(email);
22. }
23. }
Above program have one index.html for login purpose and username and password is entered by User. The
form inside index.html is submitting to Servlet1. Servlet1 is reads username and password and generates an another
form. In Servlet1’s form we are setting username and password as hidden fields and form submits to Servlet2. Now
Servlet2 is able to read the hidden fields.(username and password we given in index.html).

Drawbacks of Hidden Form Fields:-


Hidden form field works only when every page is dynamically generated means your page should have a form.
User can see the source code of your page and in Source Hidden fields are available. So it lacks the security and
privacy. To see source code of your page in Internet Explorer go to Menu → view→source.

Cookies:-
Cookies were invented by Netscape, and are one of the most refined forms of token that clients and servers
RIX
AT
M

can exchange. Unlike URL rewriting or using hidden form fields, cookies can be exchanged in request and response
headers, and therefore do not involve manipulating the generated response to contain a token.
Cookies are most commonly used means of tracking client sessions.

Definition: A Cookies is a small piece of textual information sent be the server to the client, stored on the client, and
returned by the client for all request to the server.
A Cookie contains one or more name- value pairs with certain additional attributes, which are exchanged in
the response and request headers. Web servers send a cookie by sending the set-Cookie response header.
The container can transparently set Cookies in the response headers, and extract Cookies from request
headers.
The Servlet API specification requires that the web containers implement session tracking using the cookie
mechanism. In this approach, the web container automatically sets a session tracking cookie with name jsessionid.
When the container receives client requests it checks for existence of this Cookie, and accordingly tracks sessions.
However, since servers can transparently set cookies, which are stored in the user’s computer and sent back to the
server, Cookies cause security concerns for many users. In order to answer for such concerns, browser allows you to
disable cookies. When Cookies are disabled, Servlet Containers use URL rewriting to track sessions.
Note: Although several sites require Cookies and provide limited or no functionality when Cookies are disabled,
it is a good practice to design web applications to support URL rewriting. Apart from Session Tracking Cookies, your
web application can explicitly set cookies in the response. Using the servlet API, you can add several Cookies in the
response and extract Cookies from request.

The Cookie Class:-


Constructor:
Matrix Computers (Page 64 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Cookie(String name, String value)


Useful Methods:
• void setMaxAge(int age):-//in seconds
• int getMaxAge():-//in seconds
• void setDomain(String domain):- Used to set the domain with which the cookie is associated.
• void getDomain():-Used to get the domain with which the cookie is associated.
• void setPath(String path):-
• String getPath():-
• void setComment(String):- Used to set a comment for the cookie.
• String getComment():- Returns the comment that describes the purpose of the cookie, or null if there are no
comments assosiated with the cookie.
• String getName():- Returns the name of the cookie.
• void setValue(String):- Set the value of a cookie. The value should not contain white space, brackets,
parenthesis, equal to signs, commas, double quotes, slashes, question marks, at signs, colons, or semicolons.
• String getValue():- Returns the value of the cookie.
• setSecure(boolean), getSecure(boolean) :- Used to set or get the secure flag of the cookie. Setting secure
attribute to true indicates that the cookie should only be sent by using a secure protocol, such as HTTPS or
SSL.

Example:-
Creating a Cookie and sending it to the browser so that it can be stored on the Client m/c.
Cookie c=new Cookie(“uid”,“dev”);
c.setMaxAge(60*60);
c.setDomain(“www.myserver.com”); //cookies will be sent back to the domain
c.setPath(“/”);// cookies will be sent for any URL for the above domain
response.addCookie(c);// cookie is added to the response header

Similarly you can retrieve cookies from requests using getCookies() method on the HTTPServletRequest
interface. Possible application for setting explicit Cookies include targeted marketing, site personalization, usage
tracking etc.
Cookies c[ ]=request.getCookies();
RIX
AT
M

We can iterate the array and retrieve the cookie name and value using getName() and getValue() methods.

Example 13 Cookie example:-


index.html
1. <html>
2. <body>
3. <form name=”form1” method=”get” action=”add”>
4. <b>Enter a value for mycookie</b>
5. <input type=”text” name=”data” size=25 value=””>
6. <input type=”submit” value=”submit”>
7. </form>
8. </body>
9. </html>
getcookie.html
1. <html>
2. <head>
3. <title>get cookie</title>
4. </head>
5. <body>
6. <center>
7. <h3><a href="getcookie">Click here to get cookies</a></h3>
8. </center>
9. </body>
10. </html>
Matrix Computers (Page 65 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

AddCookieServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.Cookie;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. import javax.servlet.http.HttpServlet;
8. public class AddCookieServlet extends HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. String data=request.getParameter("data");
13. Cookie cookie=new Cookie("MyCookie",data);
14. response.addCookie(cookie);
15. response.setContentType("text/html");
16. PrintWriter out=response.getWriter();
17. out.print("<html>");
18. out.print("<head><title>Adding Cookies</title></head>");
19. out.print("<body>");
20. out.print("<h3>MyCookie has been set to response");
21. out.print("<br>Cookie value is \t");
22. out.print(data);
23. out.print("</h3><br>");
24. out.print("<a href='getcookie.html'>Click here to go next</a>");
25. out.print("</body>");
26. out.print("</html>");
27. out.close();
28. }
29. }
GetCookieServlet.java
RIX
AT
M

1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.Cookie;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. import javax.servlet.http.HttpServlet;
8. public class GetCookieServlet extends HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. Cookie cookie[]=request.getCookies();
13. response.setContentType("text/html");
14. PrintWriter out=response.getWriter();
15. out.print("<html>");
16. out.print("<head><title>Getting Cookies</title></head>");
17. out.print("<body>");
18. out.print("<b>");
19. for(int i=0;i<cookie.length;i++)
20. {
21. String name=cookie[i].getName();
22. String value=cookie[i].getValue();
23. out.print("Name: "+name+" value: "+value);
Matrix Computers (Page 66 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

24. }
25. out.print("</body>");
26. out.print("</html>");
27. out.close();
28. }
29. }
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>AddCookieServlet</servlet-name>
4. <servlet-class>AddCookieServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>AddCookieServlet</servlet-name>
8. <url-pattern>/addcookie</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>GetCookieServlet</servlet-name>
12. <servlet-class>GetCookieServlet</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>GetCookieServlet</servlet-name>
16. <url-pattern>/getcookie</url-pattern>
17. </servlet-mapping>
18. </web-app>
Output:-
RIX
AT
M
Matrix Computers (Page 67 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Secure Socket Layer(SSL):-


SSL is an encryption technology that runs on top of TCP/IP and below application-level protocols such as
HTTP. SSL is the technology used in HTTPS protocol. SSL –enabled servers can authenticate SSL –enabled clients,
and use an encrypted connection between the clients and the sever. In the process of establishing an encrypted
connections, both the client and server generate what are called “Session Keys”, which are symmetric keys to establish
a session.
With Servlets, it is the web container’s responsibility to provide the basic facilities for creating and maintaining
RIX
AT
M

sessions. The servlet specification allows web containers to use URL rewriting, cookies, or SSL sessions for session
tracking. The actual technique used for establishing and tracking a given session depends on both the server’s and
clients capabilities to participate in sessions.
The server API also provides you with an interface, object of which let you manipulate session lifecycle, and
associate state with sessions. There are certain guidelines that make sure that session tracking is functional
irrespective of the technique used.

Session Tracking with the Java Servlet API:-


Web containers use either cookies or URL rewriting for establishing a sessions. While most web containers
rely on the cookies alone for establishing sessions, some use Cookies by default, and use URL rewriting when clients
reject cookies. The actual creation of session is transparent to the application programmer. That is you do not need
explicitly to create, set or get cookies, or rewrite URLs for session tracking, the only requirement is that you should
encode all URLs in the response.
The Servlet API for session tracking consists of the following:
• Methods on the HttpServletRequest interface for creating and accessing HttpSession objects.
• HttpSession interface to represent sessions. This interface includes method to associate state with session,
and to configure and invalidate sessions.
• Methods on HttpServletResponse interface to encode URLs such that the web container can use rewriting
when the client browsers rejects Cookies.

Session Creation and Tracking:-


The methods from the HttpServletRequest interface for creating and tracking HttpSession objects are
• public HttpSession getSession(boolean create)
Matrix Computers (Page 68 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

• public HttpSession getsession()


Each of these methods returns the HttpSesseion object associated with the current request. If there is no
session associated with the current request, the second method creates one. This could happen when the client refuses
to join a session, for instance when the user disables cookies in their browser. The first method takes an additional
boolean argument to indicate whether the container should attempt to create a new session if there is no session
associated with current request. If this argument is false, and there is no session associated with request, this method
returns null.
Form a servlet’s perspective, session creation/tracking involves calling one of these two methods to obtain an
HttpSession object. However, from the web containers perspective, there is more to it. Session Creation involves
establishing a token (based on a cookie , or the URL path parameter, or an SSL session key) that can be exchanged
between the client and the server , and associating such a token with an HttpSession object. The web container
receives the token as part of the request. When the getSession() method is called, the container retrieves the
HttpSession object based on this token.
In other words, session creation/tracking means that the web container is able to associate a request with a
client, and the HttpSession object represents this association. The web container maintains this object for the duration
of the client session, or configurable time period. Since there can be several clients sending the request to container,
the container maintains separate HttpSession object for each client. Consequently you can associate state with each
HttpSession object.

The HttpSession Interface:-


public interface HttpSession:-Note that, as with most of the other Servlet API interfaces, web containers provide a
suitable implementation internally, and what you see is an instance obtained via the getSession() method of the
HttpSessionRequest object.
The HttpSession interface has the following methods:
• long getCreationTime():-Returns the time when this session was created, measured in milliseconds since
midnight January 1, 1970 GMT.
• String getId():-Returns a string containing the unique identifier assigned to this session.
• long getLastAccessTime():-Returns the last time the client sent a request associated with this session, as
the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container
received the request.
• int getMaxInactiveInterval():- //in seconds Returns the maximum time interval, in seconds, that the servlet
RIX

container will keep this session open between client accesses.


AT
M

• void setMaxTimeInterval(int interval):-// in seconds Specifies the time, in seconds, between client requests
before the servlet container will invalidate this session.
• void invalidate():-Invalidates this session then unbinds any objects bound to it.
• boolean isNew():-Returns true if the client does not yet know about the session or if the client chooses not to
join the session.

Methods for associating attributes(state) with Session


• Object getAttribute(String name):- Returns the object bound with the specified name in this session, or null
if no object is bound under the name.
• Enumeration getAttributeNames():-Returns an Enumeration of String objects containing the names of all the
objects bound to this session.
• void setAttribute(String name, Object value):- Binds an object to this session, using the name specified.
• void removeAttribute(String name):- Removes the object bound with the specified name from this session.

Configuring Session Timeout through Descriptor


<session-config>
<session-timeout>30</session-timeout>
</session-config>
Note:- Here time is in minutes.

Example 14 Session Tracking:-


index.html
Matrix Computers (Page 69 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

1. <html>
2. <head>
3. <title>Session Tracking</title>
4. </head>
5. <body>
6. <center> <h3>For Session Management<a href="sessionmm">Click here</a></h3></center>
7. </body>
8. </html>
SessionManagement.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import java.util.Date;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. import javax.servlet.http.HttpSession;
8. public class SessionManagement extends javax.servlet.http.HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. String action=request.getParameter("action");
13. if(action!=null && action.equals("invalidate"))
14. {
15. //invalidate the session
16. HttpSession session=request.getSession();
17. session.invalidate();
18. response.setContentType("text/html");
19. PrintWriter out=response.getWriter();
20. out.print("<html>");
21. out.print("<head><title>Session Management</title></head>");
22. out.print("<body bgcolor=#99FF66>");
RIX
AT
M

23 out.print("<p>Your Session has Expired</p>");


24. String sessionURL=response.encodeURL("sessionmm");
25. out.print("<a HREF=\""+sessionURL+"?action=newSession\">" );
26. out.print("Create new Session");
27. out.print("</body></html>");
28. out.close();
29. }
30. else
31. {
32. HttpSession session=request.getSession();
33. response.setContentType("text/html");
34. PrintWriter out=response.getWriter();
35. out.print("<html>");
36. out.print("<head><title>Session Management</title></head>");
37. out.print("<body bgcolor=#FFFFFF>");
38. out.print("<center<h1>Session Management</h1></center>");
39. out.print("<br>Session Status:");
40. if(session.isNew())
41. {
42. out.print("New Session");
43. }
44. else
45. {
46. out.print("Old Session");
Matrix Computers (Page 70 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

47. }
48. out.print("<br><Session ID");
49. out.print(session.getId());
50. out.print("<br> Creation Time");
51. out.print(new Date(session.getCreationTime()));
52. out.print("<br>Last Accessed Time:");
53. out.print(new Date(session.getLastAccessedTime()));
54. out.print("<br>Maximum Inactive Interval in Seconds");
55. out.print(session.getMaxInactiveInterval());
56. String sessionURL=response.encodeURL("sessionmm");
57. out.print("<br><a href=\""+sessionURL+"?action=invalidate\">");
58. out.print("Invalidate the session</a>");
59. out.print("<br><a href=\""+sessionURL+"\"");
60. out.print("Reload This Page</a>");
61. out.print("</body></html>");
62. }
63. }
64. }
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>SessionManagement</servlet-name>
4. <servlet-class>SessionManagement</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>SessionManagement</servlet-name>
8. <url-pattern>/sessionmm</url-pattern>
9. </servlet-mapping>
10. <session-config>
11. <session-timeout>5</session-timeout>
12. </session-config>
13. </web-app>
RIX
AT
M

Output:-
Matrix Computers (Page 71 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

RIX
AT
M

Example 15:-Http Session attributes:-


Servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.RequestDispatcher;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. import javax.servlet.http.HttpSession;
10. public class Servlet1 extends HttpServlet
11. {
12. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
13. {
14. HttpSession session=request.getSession();
15. session.setAttribute("key", "Matrix Computers");
16. PrintWriter out=response.getWriter();
17. out.print("Attribute is added in session object<br>");
18. }
19. }
Servlet2.java
Matrix Computers (Page 72 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. import javax.servlet.http.HttpSession;
9. public class Servlet2 extends HttpServlet
10. {
11. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
12. {
13. HttpSession session=request.getSession();
14. String value=(String)session.getAttribute("key");
15. PrintWriter out=response.getWriter();
16. out.print("The Attributes value is:");
17. out.print(value);
18. out.print("<br>");
19. session.removeAttribute("key");
20. out.print("<br>");
21. out.print("Attribute Removed");
22. }
23. }

Attribute is available until your session in which you added your attribute is available. If you started a new
session suppose opened a new browser and retrieving the attribute then the attribute is not available because new
browser doesn’t have previous session.
Note1:-if you are setting attribute in context object then the attribute is available in whole application. If setting in
request then attribute is available until same request is available. If setting is session then the attribute is available till
session is alive.
Note2:-If you don’t know Attribute Name(key) then use following method.
RIX
AT
M

for context
Enumeration en=context.getAttributeNames();
for request
Enumeration en=request.getAttributeNames();
for session
Enumeration en=session.getAttributeNames();

getAttributeNames() method returns the names(keys) of added attributes in Enumeration. Retrieve keys and
then do operations on attributes like remove or get attributes.
process Enumeration:-
while(en.hasMoreElements())
{
en.nextElement();// this returns attribute’s names(keys).
}

Get Parameters:-
If you don’t know want to get parameters through their name then use getParameterNames() method. This
method returns an Enumeration having names of all the parameters coming through request. Now use Enumeration
to get the parameter names and values according names.
If there are more then one value in a parameter then use getParameterValues(“”) method. This method
returns array of values in form of String. The getParameter() method will give only one value.
See the following example you will find a checkbox having multiple values.
Matrix Computers (Page 73 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Example 16:-
index.html
1. <html>
2. <head>
3. <title>index</title>
4. </head>
5. <body>
6. <center>
7. <form action=register method=post>
8. Name<input type=text name=username value="" maxlength=30><br>
9. FName<input type=text name=fname value="" maxlength=30><br>
10. Email<input type=text name=email value="" maxlength="40"><br>
11. Gender<input type=radio name=gender value=male>
12. Male<input type=radio name=gender value=female>Female<br>
13. Subject:
14. C<input type=checkbox name=subject value="C">
15. C++<input type=checkbox name=subject value="C++">
16. Java<input type=checkbox name=subject value="Java">
17. VB<input type=checkbox name=subject value="VB"><br><br>
18. <input type=submit name="submit" value="Submit">
19. </form>
20. </center>
21. </body>
22. </html>
RegisterServlet:-
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import java.util.Enumeration;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
RIX
AT
M

8. import javax.servlet.http.HttpServletResponse;
9. public class RegisterServlet extends HttpServlet
10. {
11. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
12. {
13. PrintWriter out = response.getWriter();
14. Enumeration en = request.getParameterNames();
15. while (en.hasMoreElements())
16. {
17. String name = (String) en.nextElement();
18. String value = request.getParameter(name);
19. out.print(value);
20. out.print("<br>");
21. }
22. String subject[] = request.getParameterValues("subject");
23. for (int i = 0; i < subject.length; i++)
24. {
25. out.print(subject[i] + "<br>");
26. }
27. }
28. }
Matrix Computers (Page 74 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

8. Implementing Filters:-
Filters are the most recent addition to the java servlet technology. The servlet specification version 2.3
introduced filters as a flexible means of interacting with HTTP requests and responses before and after the web-
container invoke wed resources including servlets.
For instance, consider the basic need to monitor requests to a specific kind of static file (such as certain type
of images or documents) on the container, and log the requests to a specific database. In order to build this functionality,
what you need is a facility to plug in some logic during the HTTP request handling process.
Why are filters special? As of J2EE 1.3 filters provide the only mechanism by which we can plug in code to
participate in the container interception process. Although filters are limited to the web container (that is we can filter
HTTP requests, but we can’t filter request to EJBs, and so on), we can perform several useful tasks with the help of
the filter in the web container to invoke certain filter objects during the HTTP request-response process. In this manner
as web application developers, we can customize how HTTP requests are handled within a wed container.

What Is A Filter?
A filter is a servlet like container-managed object that can be declaratively inserted within the HTTP request-
response process.
Like a servlet, a filter object is instantiated and managed by the container and follows a lifecycle that is similar
to that of a servlet. A filter has four stages: instantiate, initialize, filter and destroy. These stages are similar to a servlet’
s instantiate, initialize, service and destroy.
Filters also follow a deployment process close to that of servlets. In fact, the API of a filter is very similar to
that of the servlet’s Servlet interface a filter also operates on HTTP requests to produce and manipulate further HTTP
requests and responses. So how is a filter different from a servlet?
In order to see the difference, let us consider how filters participate in the HTTP request –response process.
RIX
AT
M

In this figure, there is a chain of two filters participating in the response process. Each filter (from left to right)
can manipulate the request and response or implement some logic (including updating the HTTP session or the servlet
context) and request the HTTP container to invoke the next filter (if any) in the filter chain. Ultimately after invoking the
last filter, the container processes the actual web resource.
Alternatively, any filter in this chain can choose to abort the processing and report an error in the HTTP
response. The arrows between the filter and between the second filter and the web resources are the servlet request
and servlet response objects.
In this process, after each filter is processed the control is transferred to the following filter in the chain. Similarly
after the web resource has been processed, the container returns the thread of execution back to the last filter. This
step continues till the control is handed back to the first filter. In this manner, each filter gets an opportunity to participate
both before and after invoking the web resources.

Use of Filter:-
1. Validation of Http Request:- Each filter has access to the http request object and therefore can validate the
contents of HTTP requests. If a request is invalid (that is, it contains invalid parameters, required parameters are
missing, or values of the supplied parameters are invalid), the filter can abort processing and report HTTP errors
to the container. In this way, we can avoid implementing any validation logic within servlet or jsp pages. We can
also extend this idea to preprocess HTTP request parameters.
2. Logging HTTP Requests:- Based on the contents of HTTP requests, we can implement custom access
logging for all web resourses. Typically, logging is the work of the web server and it usually control how logging is
Matrix Computers (Page 75 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

done. Filters give us a handle to implement our own logging (in addition to that of server). With filter we can request
application specific logging. For instance, we can build logging based on specific business events –filters let us
scan requests to determine the events.
3. Authorization of HTTP Requests:- Authorization is the process of checking if the client can access a given
resource. Typically, web applications implement custom authorization code in every servlet and jsp page. Instead
we can implement custom authorization within a filter and include the filter for all HTTP requests. We can also rely
on web-container managed declarative authorization.
4. Customizing HTTP environment for servlet and JSP pages:- We can also use the filter mechanism to
modify the request and response objects (and thereby the HTTP session as well). For instance, we can add
additional data to the request object, or fill in missing default parameters. We can also replace the request and
response objects to provide additional behavior.
Note: All these tasks could also be performed within a servlet, although with some difficulty.

Filter API:-
The Filter API consists of the following interfaces and classes:
• javax.servlet.Filter
The interface that all filters must implement.
• javax.servlet.FilterConfig
An interface that provides access to filter initialization parameters and the servlet context. This interface is created
by the container and passed on to the filter instance during initialization.
• javax.servlet.FilterChain
An abstraction of a filter chain. This interface lets you invoke the next filter in the chain, or if the calling filter is the
last filter in the chain, the resource at the end of the chain.

The Filter Interface:-


• public interface javax.servlet.Filter
This interface from the javax.servlet package encapsulates the lifecycle methods of a filter. The life cycle
methods include init() and destroy(), which are invoked during initialization and destruction of a filter, and a
doFilter() method, which is invoked whenever there is a request/response pair to be filtered.

Methods of the Filter Interface:-


RIX
AT
M

• void init(FilterConfig config) throws ServletException


The container invokes this method before putting the filter into service. During the initialization the container
sends the configuration information (initialization parameter) to the filter via a FilterConfig object.
• void doFilter(ServletRequest request, SrevletResponse response, FilterChain chain)throws
IOException,ServletException
The Container invokes this method while processing a filter. Using the FilterChain object, each filter may
instruct the container to the process the rest of the filter chain. Notice that this method is similar to the Servlet’s
servie() method with the difference of third parameter.
• void destroy()
The container invokes this method before taking the filter out of service. This could happen either at container
shutdown, or when the application is undeployed.

All these methods are container-invoked methods used during filter lifecycle. The lifecycle of a filter consists
of the following steps.
1. Instantiation:-An container startup or sometime before a filter instance is required before invocation. For each web
application, the container maintains one instance per filter.
2. Initialization:-After instantiating the container calls init() method. During the call, the container passes on
initialization parameters to the filter instance.
3. Invoke Filter:-After init() method doFilter() method is invoked.
4. Destroy:-This method will be called at the last.

Both init() and destroy() methods can throw ServletException while the doFilter() method can also throw
IOException. When these methods throw a ServletException, the container cannot continue with the filter chain which
means that it cannot serve the web resouces to which the request maps. Therefore, in cases where you want the
Matrix Computers (Page 76 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

container to serve the resource irrespective of any exceptions, it is important to make sure that the filters consume
exceptions and log those cases appropriately.

The FilterConfig Interface:-


• public interface javax.servlet.FilterConfig
A FilterConfig object represents the configuration for the filter. This object allows to obtain the ServletContext
object and pass initialization values to filters.

Methods:-
• public String getFilterName():-Returns the filter-name of this filter as defined in the deployment descriptor.
• 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.
• publicServletContext getServletContext():-Returns a reference to the ServletContext in which the caller is
executing.

TheFilterChain Interface:-
• public interface javax.servlet.FilterChain
Interface provides the filter with a handle to invoke the rest of the filter chain or next resource. Each filter access
to a FilterChain object when its doFilter() method is invoked.

Methods:-
• public void doFilter(ServletRequest request, ServletResponse response)
When a filter invokes this method, the container invokes the next filter in the chain. If the invoking filter is the
last filter in the chain, the container invokes the requested web resource.

What if a filter does not want further processing? In this case the filter can simply not call the doFilter() method
on the FilterChain object. But why should a filter not want to continue with the chain? Consider, for instance a filter that
validates the incoming request. If the filter finds that the request is incomplete, invalid, or inappropriate, it may choose
to abort the chain. In this case, the filter itself can write appropriate content back to the response.
RIX
AT
M

Deployment Descriptor for Filters:-


Register the filter in web.xml under <web-app> root tag.
<web-app>
<filter>
<filter-name>myfilter</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myfilter</filter-name>
<url-pattern>/login</url-pattern>// this filter is assigned to servlet that have url-pattern login.
</filter-mapping>




</web-app>

Second way to register a filter:-


<web-app>
<filter>
<filter-name>myfilter</filter-name>
<filter-class>MyFilter</filter-class>
Matrix Computers (Page 77 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

</filter>
<filter-mapping>
<filter-name>myfilter</filter>
<servlet-name>login</servlet-name>// this filter is assigned to servlet having name
//loginservlet
</filter-mapping>


….
</web-app>

Assign a filter for all html request:-


<web-app>
<filter>
<filter-name>myfilter</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myfilter</filter-name>
<url-pattern>*.html</url-pattern> //This filter is for all requests having .html extension.
</filter-mapping>
--------------
</web-app>

There are three key points to note here:


1. The container relies on the order in which the mappings are declared in the descriptor to compose a filter
chain.
2. Each filter gets a chance to process before and after the actual resource is processed. This is due to the
nesting of doFilter() calls.
3. The process is completely declarative. You can enable or disable filters by including or removing filter-
mapping declarations in the deployment descriptor.
RIX
AT
M

Example 17 Filter Example:-


index.html
1. <html>
2. <head>
3. <title>Use of Filter</title>
4. </head>
5. <body>
6. <h1>Use of Filter</h1>
7. <br><h4><a href="demofilter">Click here to see the effect of Filter</a></h4>
8. </body>
9. </html>
MyFilter.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class MyFilter implements Filter
5. {
6. FilterConfig config;
7. public void init(FilterConfig config)
8. {
9. this.config=config;
10. }
11. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
Matrix Computers (Page 78 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

throws IOException, ServletException


12. {
13. PrintWriter out=response.getWriter();
14. out.print("<center><h3>This is request part of filter</h3></center><br>");
15. chain.doFilter(request, response);
16. out.print("<center><h3>This is response part of filter</h3></center>");
17. }
18. public void destroy () { }
19. }
MyServlet.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class MyServlet extends HttpServlet
5. {
6. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
7. {
8. response.setContentType("text/html");
9. PrintWriter out=response.getWriter();
10. out.print("<center><h3>This is MyServlet</h3></center><br>");
11. }
12. }
web.xml
1. <web-app>
2. <filter>
3. <filter-name>myfilter</filter-name>
4. <filter-class>MyFilter</filter-class>
5. </filter>
6. <filter-mapping>
7. <filter-name>myfilter</filter-name>
8. <url-pattern>/demofilter</url-pattern>
RIX
AT
M

9. </filter-mapping>
10. <servlet>
11. <servlet-name>myservlet</servlet-name>
12. <servlet-class>MyServlet</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>myservlet</servlet-name>
16. <url-pattern>/demofilter</url-pattern>
17. </servlet-mapping>
18. </web-app>
Note :- To call filters of second servlet which is called by request dispatcher we have to add a line in <servlet-mapping>
tag <dispatcher>INCLUDE</dispatcher>
Output:-
Matrix Computers (Page 79 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

RIX
AT
M

Init Parameters in Filter:-


Use <init-param> element (tag) under <filter> tag in the deployment descriptor(web.xml). You can then retrieve
the values of <init-param> using the following code under the doFilter method of a filter.
String name=filterconfig.getInitParameter(“name”);
And web.xml should be like this
<web-app>
<filter>
<filter-name>myfilter</filter-name>
<filter-class>MyFilter</filter-class>
<init-param>
<param-name>name</param-name>
<param-value>Matrix</param-value>
</init-param>
</filter>
Matrix Computers (Page 80 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Note:- Filter’s execution is divided into two parts, one is before chain.doFilter(Request, Response) method and one
is after chain.doFilter(Request, Response) method. First one called request execution and second one is called
response execution.

Listeners:-
RIX

A servlet can be designed as an event listener. This enables the servlet to be notified when some external
AT
M

event or changes occurred. There are a number of listener interfaces that you can implement for your servlet. All the
listener interface extends java.util.EventListener. Create a class by implementing corresponding interface to listen
particular event in your web application. For example: The listener classes for httpsession events are often used as a
way of tracking sessions within a Web application. for example, it is often useful to know whether a session became
invalid because the Web server timed out the session or because a Web Component within the application called the
invalidate() method.
Register your listener class in web.xml by using <listener> tag, child tag of <web-app>
<web-app>
<listener>
<listener-class>com.matrix.MyListener</listener-class>
</listener>
-------------
-------------
</web-app>
At the application level, the javax.servlet package provides two listener interfaces that support event
notifications for state changes in the ServletContext object.
1. ServletContextListener interface
2. ServletContextAttributeListener interface.

The ServletContextListener Interface:-


• public interface ServletContextListener extends java.util.EventListener
You can use the ServletContextListener interface to listen to the ServletContext life cycle events. Your listener
class must implement this interface to listen to ServletContext life cycle events.
Matrix Computers (Page 81 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Methods:-
• public void contextInitialized(ServletContextEvent sce) :- The contextInitialized method is called when the
web application is ready to service requests. The method is called automatically by the servlet container when
its own initialization process is finished.
• public void contextDestroyed(ServletContextEvent sce):-The contextDestroyed method is invoked when
the servlet context is about to be shut down. You can use this method to write code that needs to run when
the application shuts down, such as closing a database connection or writing to the log.

The ServletContextEvent Class:-


As you have seen, both methods of the ServletContextListener interface pass a ServletContextEvent class.
public class ServletContextEvent extends java.util.EventObject

The ServletContextEvent has only one method:


• public ServletContext getServletContext()
. This method returns the ServletContext that is changed.

Deployment Descriptor
Register listener class in web.xml. The <web-app> element must contain a <listener> element.
<web-app>
<listener>
<listener-class>AppLifeCycleEvent</listener-class>
</listener>
</web-app>
The <listener> element must come before the <servlet> part.

If you want, you can have more than one listener class. To do this, list all the listener classes in the deployment
descriptor, as follows:

<web-app>
<listener>
RIX
AT

<listener-class>AppLifeCycleEvent1</listener-class>
M

</listener>
<listener>
<listener-class>AppLifeCycleEvent2</listener-class>
</listener>
</web-app>
With a deployment descriptor like this, when Tomcat starts, it will call the contextInitialized method in the
AppLifeCycleEvent1 class and then call the same method in the AppLifeCycleEvent2 class.

Listening to ServletContextAttributeListener:-
In addition to a life cycle listener, you also can implement the ServletContextAttributeListener interface to be
notified when any attribute is added to the ServletContext or if any of the ServletContext's attributes are changed or
removed.
public interface ServletContextAttributeListener extends EventListener

It has three methods:-


• public void attributeAdded(ServletContextAttributeEvent scae)
• public void attributeRemoved(ServletContextAttributeEvent scae)
• public void attributeReplaced(ServletContextAttributeEvent scae)
The attributeAdded method is called when a new attribute is added to the ServletContext object. The attributeRemove
method is called when an attribute is removed from the ServletContext object, and the attributeReplaced method is
invoked when an attribute in the ServletContext object is replaced.
Matrix Computers (Page 82 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

ServletContextAttributeEvent class:-
• String getName():-Return the name of the attribute that changed on the ServletContext.
• Object getValue():-Returns the value of the attribute that has been added, removed, or replaced.

Example 18:-
index.html
1. <html><body>
2. <a href="s1">Click here to Listen Context</a>
3. </body>
Servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import javax.servlet.ServletContext;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet1 extends HttpServlet
9. {
10. protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException
11. {
12. ServletContext ctx=getServletContext();
13. ctx.setAttribute("application", "Context Attribute");
14. ctx.setAttribute("application", "Context Attribute Replaced");
15. ctx.getAttribute("application");
16. ctx.removeAttribute("application");
17. }
18. }
Context11.java
1. package com.matrix;
RIX
AT
M

2. import javax.servlet.ServletContextEvent;
3. import javax.servlet.ServletContextListener;
4. public class Context11 implements ServletContextListener
5. {
6. public void contextInitialized(ServletContextEvent sce)
7. {
8. System.out.println("context initialized");
9. }
10. public void contextDestroyed(ServletContextEvent sce)
11. {
12. System.out.println("Context Destroyed");
13. }
14. }
Attribute11.java
1. package com.matrix;
2. import javax.servlet.ServletContextAttributeEvent;
3. import javax.servlet.ServletContextAttributeListener;
4. public class Attribute11 implements ServletContextAttributeListener
5. {
6. public void attributeAdded(ServletContextAttributeEvent scae)
7. {
8. String name=scae.getName();
9. String value=(String)scae.getValue();
10. System.out.println("Attribute "+name+ " added and The Value is: "+value);
Matrix Computers (Page 83 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

11. }
12. public void attributeRemoved(ServletContextAttributeEvent scae)
13. {
14. String name=scae.getName();
15. System.out.println("Attribute "+name+" Removed");
16. }
17. public void attributeReplaced(ServletContextAttributeEvent scae)
18. {
19. String name=scae.getName();
20. System.out.println("Attribute "+ name+" Replaced.");
21. }
22. }
web.xml
1. <web-app>
2. <listener>
3. <listener-class>com.matrix.Context11</listener-class>
4. </listener>
5. <listener>
6. <listener-class>com.matrix.Attribute11</listener-class>
7. </listener>
8. <servlet>
9. <servlet-name>s1</servlet-name>
10. <servlet-class>com.matrix.Servlet1</servlet-class>
11. </servlet>
12. <servlet-mapping>
13. <servlet-name>s1</servlet-name>
14. <url-pattern>/s1</url-pattern>
15. </servlet-mapping>
16. </web-app>

Listening to HttpSession Events:-


The javax.servlet.http package provides two interfaces that you can implement to listen to HttpSession events:
RIX
AT
M

HttpSessionListener and HttpSessionAttributeListener. The first enables you to listen to a session's life cycle events,
that is, the event that gets triggered when an HttpSession object is created and the event that is raised when an
HttpSession object is destroyed. The second interface, HttpSessionAttributeListener, provides events that get raised
when an attribute is added to, removed from, or modified in the HttpSession object.
The two interfaces are explained next.

The HttpSessionListener Interface:-


The HttpSessionListener interface has two methods:
• public void sessionCreated(HttpSessionEvent se)
• public void sessionDestroyed(HttpSessionEvent se)
The sessionCreated method is automatically called when an HttpSession object is created. The
sessionDestroyed method is called when an HttpSession object is invalidated. Both methods will be passed in an
HttpSessionEvent class that you can use from inside the method.
The HttpSessionEvent class is derived from the java.util.EventObject class. The HttpSessionEvent class
defines one new method called getSesssion that you can use to obtain the HttpSession object that is changed.

An Example: User Counter


The following example is a counter that counts the number of different users currently "in session." It creates
an HttpSession object for a user the first time the user requests the servlet. If the user comes back to the same servlet,
no HttpSession object will be created the second time. Therefore, the counter is incremented only when an HttpSession
object is created.
An HttpSession object can also be destroyed, however. When this happens, the counter must be decremented. For
the counter to be accessible to all users, it is stored as an attribute in the ServletContext object.
Matrix Computers (Page 84 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Example 19 HttpSessionEvent:-
index.html
1. <html>
2. <head>
3. <title>User Counter</title>
4. </head>
5. <body>
6. <a href=usercounter>Click</a>
7. </body>
8. </html>
The SessionLifeCycleEventDemo Class
1. package com.matrix;
2. import javax.servlet.http.HttpSession;
3. import javax.servlet.http.HttpSessionListener;
4. import javax.servlet.http.HttpSessionEvent;
5. import javax.servlet.ServletContextListener;
6. import javax.servlet.ServletContext;
7. import javax.servlet.ServletContextEvent;
8. public class SessionLifeCycleEventDemo implements ServletContextListener, HttpSessionListener
9. {
10. ServletContext context;
11. int counter;
12. public void contextInitialized(ServletContextEvent sce)
13. {
14. context = sce.getServletContext();
15. context.setAttribute(("userCounter"), Integer.toString(counter));
16. }
17. public void contextDestroyed(ServletContextEvent sce)
18. {
19. }
20. public void sessionCreated(HttpSessionEvent hse)
RIX
AT
M

21. {
22. System.out.println("Session created.");
23. incrementUserCounter();
24. }
25. public void sessionDestroyed(HttpSessionEvent hse)
26. {
27. System.out.println("Session destroyed.");
28. decrementUserCounter();
29. }
30. synchronized void incrementUserCounter()
31. {
32. counter = Integer.parseInt((String)context.getAttribute("userCounter"));
33. counter++;
34. context.setAttribute(("userCounter"), Integer.toString(counter));
35. System.out.println("User Count: " + counter);
36. }
37. synchronized void decrementUserCounter()
38. {
39. int counter = Integer.parseInt((String)context.getAttribute("userCounter"));
40. counter--;
41. context.setAttribute(("userCounter"), Integer.toString(counter));
42. System.out.println("User Count: " + counter);
43. }
44. }
Matrix Computers (Page 85 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

UserCounterServlet.java
1. package com.matrix;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. import java.io.*;
5. public class UserCounterServlet extends HttpServlet
6. {
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
8. {
9. ServletContext context = getServletContext();
10. HttpSession session = request.getSession(true);
11. int userCounter = 0;
12. userCounter = Integer.parseInt((String)context.getAttribute("userCounter"));
13. response.setContentType("text/html");
14. PrintWriter out = response.getWriter();
15. out.println("<HTML>");
16. out.println("<HEAD>");
17. out.println("<TITLE>User Counter</TITLE>");
18. out.println("</HEAD>");
19. out.println("<BODY>");
20. out.println("There are " + userCounter + " users.");
21. out.println("</BODY>");
22. out.println("</HTML>");
23. }
24. }
web.xml
1. <web-app>
2. <listener>
3. <listener-class>com.matrix.SessionLifeCycleEventDemo</listener-class>
4. </listener>
5. <servlet>
RIX
AT
M

6. <servlet-name>UserCounter</servlet-name>
7. <servlet-class>com.matrix.UserCounterServlet</servlet-class>
8. </servlet>
9. <servlet-mapping>
10. <servlet-name>UserCounter</servlet-name>
11. <url-pattern>/usercounter</url-pattern>
12. </servlet-mapping>
13. </web-app>

The HttpSessionAttributeListener Interface:-


The second session event listener interface is HttpSessionAttributeListener. You can implement this interface
if you need to listen to events related to session attribute methods.
• public void attributeAdded(HttpSessionBindingEvent sbe)
• public void attributeRemoved(HttpSessionBindingEvent sbe)
• public void attributeReplaced(HttpSessionBindingEvent sbe)
The attributeAdded method is called when an attribute is added to an HttpSession object. The
attributeRemoved and attributeReplaced methods are called when an HttpSession attribute is removed or replaced,
respectively.
All the methods receive an HttpSessionBindingEvent object whose class is described next.
The HttpSessionBindingEvent is derived from the HttpSessionEvent class so it inherits the getSession method. In
addition, the HttpSessionBindingEvent class has two methods: getName and getValue. The signatures of the two
methods are as follows:
• public String getName()
Matrix Computers (Page 86 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

• public Object getValue()


The getName method returns the name of the attribute that is bound to an HttpSession or unbound from an
HttpSession. The getValue method returns the value of an HttpSession attribute that has been added, removed, or
replaced.

Example 20:-
index.html
1. <html><body>
2. <a href=servlet1>Click here for Session Listener</a>
3. </body></html>
Servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. import javax.servlet.http.HttpSession;
9. public class Servlet1 extends HttpServlet
10. {
11. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
12. {
13. PrintWriter out=response.getWriter();
14. HttpSession session=request.getSession();
15. session.setAttribute("name", "Matrix Research");
16. session.setAttribute("name", "Matrix Research and Computers");
17. String name=(String)session.getAttribute("name");
18. out.print("The Attribute is: "+name);
19. out.print("<br>");
20. session.removeAttribute("name");
RIX
AT
M

21. session.invalidate();
22. out.print("Check logs for session events");
23. }
24. }
Session11.java
1. package com.matrix;
2. import javax.servlet.http.HttpSessionEvent;
3. import javax.servlet.http.HttpSessionListener;
4. public class Session11 implements HttpSessionListener
5. {
6. public void sessionCreated(HttpSessionEvent arg)
7. {
8. System.out.println("Session Created");
9. }
10. public void sessionDestroyed(HttpSessionEvent arg)
11. {
12. System.out.println("Session Destroyed");
13. }
14. }
SessionAttrib11.java
1. package com.matrix;
2. import javax.servlet.http.HttpSessionAttributeListener;
3. import javax.servlet.http.HttpSessionBindingEvent;
Matrix Computers (Page 87 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

4. public class SessionAttrib11 implements HttpSessionAttributeListener


5. {
6. public void attributeAdded(HttpSessionBindingEvent arg0)
7. {
8. String name = arg0.getName();
9. String value = (String) arg0.getValue();
10. System.out.println("The name of added attribute is: " + name);
11. System.out.println("The value of added attribute is: " + value);
12. }
13. public void attributeReplaced(HttpSessionBindingEvent arg0)
14. {
15. String name = arg0.getName();
16. System.out.println("Attribute named: " + name + " Replaced");
17. }
18. public void attributeRemoved(HttpSessionBindingEvent arg0)
19. {
20. String name = arg0.getName();
21. System.out.println("Attribute named: " + name + " Removed");
22. }
23. }
web.xml
1. <web-app>
2. <listener>
3. <listener-class>com.matrix.Session11</listener-class>
4. </listener>
5. <listener>
6. <listener-class>com.matrix.SessionAttrib11</listener-class>
7. </listener>
8. <servlet>
9. <servlet-name>servlet1</servlet-name>
10. <servlet-class>com.matrix.Servlet1</servlet-class>
11. </servlet>
RIX
AT
M

12. <servlet-mapping>
13. <servlet-name>servlet1</servlet-name>
14. <url-pattern>/servlet1</url-pattern>
15. </servlet-mapping>
16. </web-app>

Example:- 21 Request Listener:-


index.html
1. <html>
2. <head>
3. <title>Request Listener</title>
4. </head>
5. <body>
6. <form method=post action=servlet1>
7. FirstName<input type=text name=firstname value=""><br>
8. Lastname<input type=text name=lastname value=""><br>
9. <input type=reset value="Reset">
10. <input type=submit value="Submit">
11. </form>
12. </body>
13. </html>
Servlet1.java
1. package com.matrix;
2. import java.io.IOException;
Matrix Computers (Page 88 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet1 extends HttpServlet
9. {
10. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. String firstname=request.getParameter("firstname");
13. String lastname=request.getParameter("lastname");
14. PrintWriter out=response.getWriter();
15. out.print(firstname);
16. out.print("<br>");
17. out.print(lastname);
18. out.print("<br>");
19. request.setAttribute("user", "Matrix Computers");
20. request.setAttribute("user", "Matrix Computers and Research");//Replacing the attribute
21. String user=(String)request.getAttribute("user");
22. out.print(user);
23. request.removeAttribute("user");
24. }
25. }
ListeningRequest.java
1. package com.matrix;
2. import javax.servlet.ServletRequestEvent;
3. import javax.servlet.ServletRequestListener;
4. public class ListeningRequest implements ServletRequestListener
5. {
6. public void requestInitialized(ServletRequestEvent arg0)
7. {
RIX
AT
M

8. System.out.println("Request Initialized");
9. }
10. public void requestDestroyed(ServletRequestEvent arg0)
11. {
12. System.out.println("Request Destroyed");
13. }
14. }
ListeningAttribute.java
1. package com.matrix;
2. import javax.servlet.ServletRequestAttributeEvent;
3. import javax.servlet.ServletRequestAttributeListener;
4. public class ListeningAttributes implements ServletRequestAttributeListener
5. {
6. public void attributeAdded(ServletRequestAttributeEvent arg0)
7. {
8. String name=arg0.getName();
9. String value=(String)arg0.getValue();
10. System.out.println("Attribute : "+name +" Added and The Value is : "+value);
11. }
12. public void attributeRemoved(ServletRequestAttributeEvent arg0)
13. {
14. String name=arg0.getName();
15. System.out.println("Attribute "+name+" Removed");
16. }
Matrix Computers (Page 89 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

17. public void attributeReplaced(ServletRequestAttributeEvent arg0)


18. {
19. String name=arg0.getName();
20. System.out.println("Attribute "+name+" Replaced");
21. }
22. }
web.xml
1. <web-app>
2. <listener>
3. <listener-class>com.matrix.ListeningRequest</listener-class>
4. </listener>
5. <listener>
6. <listener-class>com.matrix.ListeningAttributes</listener-class>
7. </listener>
8. <servlet>
9. <servlet-name>servlet1</servlet-name>
10. <servlet-class>com.matrix.Servlet1</servlet-class>
11. </servlet>
12. <servlet-mapping>
13. <servlet-name>servlet1</servlet-name>
14. <url-pattern>/servlet1</url-pattern>
15. </servlet-mapping>
16. </web-app>

RequestListener:-
For listening request related events, there are two interfaces in javax.servlet package.
1. javax.servlet.ServletRequestListener
2. javax.servlet.ServletRequestAttributeListener

To see the changes while we are sending request to a servlet or any static/web resource, there is an interface in
javax.servlet package.
RIX
AT
M

1. public interface ServletRequestListener extends EventListener:-Implement this interface to


receive notifications about changes to the servlet request.

Methods:-
• void requestInitialized(ServletRequestEvent sre):-Notification that the servlet request is about to go into scope.
• void requestDestroyed(ServletRequestEvent sre):-Notification that the servlet request is about to go out of
scope.
These two methods have an Event class as a parameter. The event class object initialized when an event happens.

public class ServletRequestEvent extends EventObject:-This is the event class for notifications
about changes to the servlet request of a web application.

Methods:-
• ServletContext getServletContext():-Return the ServletContext that changed.
• ServletRequest getServletRequest():-Return the ServletRequest that changed.

To listens about attributes added or removed in request object. The following interface in javax.servlet package for
listening attributes of request object:

2. public interface ServletRequestAttributeListener extends EventListener:-Implement this


interface to receive notifications of changes to the attribute list on the servlet request of a web application.
Matrix Computers (Page 90 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Methods:-
• void attributeAdded(ServletRequestAttributeEvent srae) :-Notification that a new attribute was added to the
servlet request.
• void attributeRemoved(ServletRequestAttributeEvent srae):-Notification that an existing attribute has been
removed from the servlet request.
• void attributeReplaced(ServletRequestAttributeEvent srae):-Notification that an attribute on the servlet request
has been replaced.

The three methods have an event class as parameter. Have a look:

public class ServletRequestAttributeEvent extends ServletRequestEvent:-This is the event


class for notifications about changes to the attributes of the servlet request of a web application.

Methods:-
• String getName():-Return the name of the attribute that changed on the ServletRequest.
• Object getValue():-Returns the value of the attribute that has been added removed or replaced.
RIX
AT
M

You might also like