You are on page 1of 40

MILE

MIRACLE SOFTWARE SYSTEMS,INC.

SERVLET

Miracle Software Systems (I) Pvt. Ltd. Page: 1 of 40


MILE

Table of Contents
1.1Servlet Introduction...............................................................................................................................3
1.1.1Performance is significantly better.................................................................................................3
1.2Servlet Architecture...............................................................................................................................3
1.3Servlets Packages..................................................................................................................................3
1.4Tomcat Server ......................................................................................................................................4
1.5WebApplication ....................................................................................................................................4
1.5.1Deployment of Web application ....................................................................................................5
1.6Servlet life cycle....................................................................................................................................6
1.7Servlet API ...........................................................................................................................................7
1.7.1Servlet interface.............................................................................................................................7
1.7.2ServletRequest interface.................................................................................................................7
1.7.3ServletResponse interface..............................................................................................................8
1.7.4ServletConfig interface..................................................................................................................8
1.7.5ServletContext interface...............................................................................................................11
1.8Request Dispatcher Interface..............................................................................................................13
1.9Session Tracking Techniques..............................................................................................................25
1.9.1Cookies.........................................................................................................................................25
1.9.2Hidden form fields.......................................................................................................................28
1.9.3URL-Rewriting............................................................................................................................31
1.9.4HttpSession Interface...................................................................................................................33
1.9.4.1Commonly used methods of HttpSession interface..............................................................33
1.10Servlet Filter .....................................................................................................................................36
1.10.1Filter API....................................................................................................................................36
1.11Event and Listener in Servlet............................................................................................................38
1.12web.xml.............................................................................................................................................39

Miracle Software Systems (I) Pvt. Ltd. Page: 2 of 40


MILE

SERVLET

1.1Servlet Introduction

Servlet technology is used to create web application (resides at server side and generates dynamic web
page).Servlet technology is robust and scalable as it uses the java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was used as a server-side programming language. But there were many
disadvantages of this technology. We have discussed these disadvantages below.
There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse etc.

1.1.1Performance is significantly better

1. Servlets execute within the address space of a Web server. It is not necessary to create a separate process
to handle each client request.

2. Servlets are platform-independent because they are written in Java.

3. Java security manager on the server enforces a set of restrictions to protect the resources on a server
machine. So servlets are trusted.

4. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets,
databases, or other software via the sockets and RMI mechanisms that you have seen already.

1.2Servlet Architecture

Following diagram shows the position of Servlets in a Web Application.

Miracle Software Systems (I) Pvt. Ltd. Page: 3 of 40


MILE

1.3Servlets Packages

 Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet
specification.

 Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard
part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale
development projects.

1.4Tomcat Server

There are many web servers available in the market, but Tomcat is best for learning curve. Of course as a
developer, it is immaterial which server is you are using. the Tomcat server is a Java-based Web Application
container that was created to run Servlet and Java Server Page web applications. It will provide run time
environment for both the Servlet and JSP specifications. Below features demanding many of the programmers to
use tomcat server for their learning curve.

 It is an open source application server


 It is a light weight server (no EJB support)
 Easy to work.
 It is easily configured with Apache and IIS
 Very stable on Unix systems
 Good documentation online
 Java Sun compliant
 Does not require a lot of memory at start up
 It is free with high quality.

 Installation and Testing:Once the installation is completed. We need to set Environment


 variables for tomcat server and and JDK software like below:
 set CATALINA_HOME=D:\Tomcat 5.5
 set JAVA_HOME=C:\Program Files\Java\jdk1.5.0
 set path=%path%;C:\Program Files\Java\jdk1.5.0\bin;D:\Tomcat 5.5\bin;
.

1.5WebApplication

Web Application is a collection of servlets, HTML pages, classes, and other resources that can be bundled and run
on multiple containers from multiple vendors. It has to confirm the below folder structure. The below structure is
having web container recognition .

 Application Root Directory is nothing but name of the web application.


Ex: CartServlets

Miracle Software Systems (I) Pvt. Ltd. Page: 4 of 40


MILE

 Under the Application Root Directory, we can place the components like JSP,HTML,CSS,js and jpg etc. It is
good create folders and keep same category components in those folder for better management.
Ex:home. Html, logo.jpg

 WEB-INF is very important and mandatory folder. WEB-INF/web.xml file to describe the components. So
this XML file is called as deployment descriptor. This file will play major role.

 WEB-INF/lib folder is to hold the jar files for that web application. Lib directory is used to store the jar
files. If application has any bundled jar files, or if application uses any third party libraries such as log4j,
JDBC drivers which is packaged in jar file, than these jar files should be placed in lib directory.
Ex:ojdbc14.jar.
 WEB-INF/classes folder contains servlet classes and other java classes of the application. If your classes
are organized into packages, the directory structure must be reflected directly under WEB-INF/classes
directory. The classes directory is automatically included in CLASSPATH.

Note:

 All unpacked classes and resources in the /WEB-INF/classes directory, and resources in JAR files under the
/WEB-INF/lib directory are included in classpath and made available to the web application.
 WEB-INF/web.xml is called the web application deployment descriptor. This is a XML file that defines
servlets, servlet mappings, listeners, filters, welcome files etc. Deployment descriptor is a heart of any
J2EE web application, so every web application must have a web.xml deployment descriptor directly under
WEB-INF folder.
 There are many changes in Servlet 3.0 Specification, web.xml file is optional, servlets, listeners and filters
are no longer required to be defined in web.xml, instead they can declared using annotations. web.xml file
can be divided into multiple files called web fragments.

1.5.1Deployment of Web application

we need to keep our application into web app folder in Apache tomcat serve before we are going to deployed
application we need to set path and classpath in environment variable for Apache and java.

set CATALINA_HOME=D:\Tomcat 5.5


set JAVA_HOME=C:\Program Files\Java\jdk1.5.0
set path=%path%;C:\Program Files\Java\jdk1.5.0\bin;D:\Tomcat 5.5\bi

Starting and Stopping Tomcat :


To start Tomcat run Tomcat_Home\bin\startup.bat
To stop Tomcat run Tomcat_Home\bin\shutdown.bat.
If you issue the startup command like above, then server will be run.if We can access the server default page from
the browser for this we have give url like http://localhost:8080/.after this we can get apache console if we check

Miracle Software Systems (I) Pvt. Ltd. Page: 5 of 40


MILE

there our application will be there .if we run our application we need to click on our application.

1.6Servlet life cycle

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the
paths followed by a servlet

The servlet is initialized by calling the init () method.


The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.

The signature of methods of Generic Servlet are shown below.

public void init(ServletConfig config) throws ServletException

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

public void destroy() .

The servlet life cycle consists of four steps, instantiation, initialization, request handling and end of service. Each of
these steps is explained below.

Loading and instantiation:During this step, web container loads the servlet class and creates a new instance of
the servlet. The container can create a servlet instance at container startup or it can delay it until the servlet is
needed to service a request.

Miracle Software Systems (I) Pvt. Ltd. Page: 6 of 40


MILE

Initialization:During initialization stage of the Servlet life cycle, the web container
initializes the servlet instance by calling the init() method. The container passes an object implementing the
ServletConfig interface via the init() method. This configuration object allows the servlet to access name-value
initialization parameters from the web application

Request handling:After a servlet is properly initialized, the servlet container may use it to handle client requests.
Requests are represented by request objects of type ServletRequest. The servlet gives response using
ServletResponse. These objects are passed as parameters to the service method of the Servlet interface. In the
case of an HTTP request, the objects provided by the container are of types HttpServletRequest and
HttpServletResponse. By default servlet implements MultiThreadModel interface for handling multiple concurrent
client requests. If the servlet implements the SingleThreadModal interface, Servlet container guarantees that there
will be only one request thread at a time in service method.

Destruction:When servlet container determines that the servlet should be removed from the service, it calls the
destroy() method of the servlet to allow servlet to release any resources it is using (eg. database connections or file
handles). Before calling the destroy() method, the container allows any request threads that are currently running
in the service method to complete execution within a defined time limit. Once the servlet is removed out of service,
container will not send any requests to the servlet. If the servlet needs to be put in service again, the container will
create a new servlet instance and the life cycle begins from the initialization phase.

1.7Servlet API

The servlet life cycle methods are defined in the javax.servlet.Servlet interface of the Servlet API that all Servlets
must implement directly or indirectly by extending GenericServlet or HttpServlet abstract classes. Most of the
servlets you develop will implement it by extending HttpServlet class. Just have a look at the most of the important
classes for servlet implementation.
Servlet API is specified in two packages: javax.servlet and javax.servlet.http. The classes and interfaces in
javax.servlet are protocol independent, while the classes and interface in javax.servlet.http deals with specialized
HTTP Servlets. Some of the classes and interfaces in the javax.servlet.http package extend those specified in
javax.servlet package.
javax.servlet package Interfaces and classes:The javax.servlet package is composed of interfaces and classes.

1.7.1Servlet interface

The Servlet Interface is the central abstraction of the Java Servlet API.It defines the life cycle methods of a servlet.
All the servlet implementations must implement it either directly or indirectly by extending a class which
implements the Servlet interface. The two classes in the servlet API that implement the Servlet interface are
GenericServlet and HttpServlet. For most purposes, developers will extend HttpServlet to implement their Servlets
while implementing web applications employing the HTTP protocol.

Miracle Software Systems (I) Pvt. Ltd. Page: 7 of 40


MILE

1.7.2ServletRequest interface

An object of ServletRequest is used to provide the client request information to a servlet such as content type,
content length, parameter names and values, header informations, attributes etc.

Methods of ServletRequest interface

Method Description
public String getParameter(String name) is used to obtain the value of a parameter by name.
returns an array of String containing all values of given
public String[]
parameter name. It is mainly used to obtain values of a
getParameterValues(String name)
Multi select list box.
java.util.Enumeration returns an enumeration of all of the request parameter
getParameterNames() names.
Returns the size of the request entity data, or -1 if not
public int getContentLength()
known.
Returns the character set encoding for the input of this
public String getCharacterEncoding()
request.
Returns the Internet Media Type of the request entity
public String getContentType()
data, or null if not known.
public ServletInputStream Returns an input stream for reading binary data in the
getInputStream() throws IOException request body.
Returns the host name of the server that received the
public abstract String getServerName()
request.
Returns the port number on which this request was
public int getServerPort()
received.

1.7.3ServletResponse interface

The ServletResponse interface assists a servlet in sending a response to the client. Developers don’t need to
implement this interface. Servlet container creates the ServletResponse object and passes it as an argument to the
servlet service() method.

1.7.4ServletConfig interface

The servlet container uses a ServletConfig object to pass


initialization information to the servlet. ServletConfig object is most commonly used to read the initialization
parameters. Servlet initialization parameters are specified in deployment descriptor (web.xml) file. Servlet
container passes the ServletConfig object as an argument when calling servlet’s init() method.

Methods of ServletConfig interface

public String getInitParameter(String name):Returns the parameter value for the specified parameter name.

public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter


names.

Miracle Software Systems (I) Pvt. Ltd. Page: 8 of 40


MILE

public String getServletName():Returns the name of the servlet.

public ServletContext getServletContext():Returns an object of ServletContext.

Example
/* ServletConfig to get initialization parameter*/
DemoServlet.java:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class DemoServlet extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException,IOException{

response.setContentType("text/html");

PrintWriter out=response.getWriter();

ServletConfig config=getServletConfig();

String driver=config.getInitParameter("driver") ;

out.print("Driver is: "+driver);

out.close();

} }

web.xml

<web-app>

<servlet>

<servlet-name>DemoServlet</servlet-name>

<servlet-class>DemoServlet</servlet-class>

<init-param>

<param-name>driver</param-name>

<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</init-param>

</servlet>

Miracle Software Systems (I) Pvt. Ltd. Page: 9 of 40


MILE

<servlet-mapping>

<servlet-name>DemoServlet</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

</web-app>

Example of ServletConfig to get all the initialization parameters


In this example, we are getting all the initialization parameter from the web.xml file and printing this information in
the servlet.

DemoServlet.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletConfig;

import avax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class DemoServlet extends HttpServlet {

public voiD doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,


IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

ServletConfig config=getServletConfig();

Enumeration<String> e=config.getInitParameterNames();

String str="";

while(e.hasMoreElements()){

str=e.nextElement();

out.print("<br>Name: "+str);

out.print(" value: "+config.getInitParameter(str));

Miracle Software Systems (I) Pvt. Ltd. Page: 10 of 40


MILE

out.close();

} }

web.xml:

<web-app>

<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>system</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>

1.7.5ServletContext interface

An object of ServletContext is created by the web container at time of deploying the project. This object can be
used to get configuration information from web.xml file. There is only one ServletContext object per web
application. If any information is shared to many servlet, it is better to provide it from the web.xml file using the
<context-param>element. Commonly used methods of ServletContext interface.
There is given some commonly used methods of ServletContext interface.

1. public String getInitParameter(String name):Returns the parameter value for the specified parameter
name.

2. public Enumeration getInitParameterNames():Returns the names of the context's initialization


parameters.

3. public void setAttribute(String name,Object object):sets the given object in the application scope.

4. public Object getAttribute(String name):Returns the attribute for the specified name.

5. public Enumeration getInitParameterNames():Returns the names of the context's initialization


parameters as an Enumeration of String objects.

Miracle Software Systems (I) Pvt. Ltd. Page: 11 of 40


MILE

6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet
context.

Example of getServletContext() method


//We can get the ServletContext object from ServletConfig object

ServletContext application=getServletConfig().getServletContext();

1.//Another convenient way to get the ServletContext object


ServletContext application=getServletContext();

Syntax to provide the initialization parameter in Context scope

<web-app>

<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
</web-app>

Example of ServletContext to get the initialization parameter


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
//creating ServletContext object
ServletContext context=getServletContext();
//Getting the value of the initialization parameter and printing it
String driverName=context.getInitParameter("dname");
pw.println("driver name is="+driverName);
pw.close();
}}

WEB.XML:
<web-app>
<servlet>

Miracle Software Systems (I) Pvt. Ltd. Page: 12 of 40


MILE

<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>

1.8Request Dispatcher Interface

The Request Dispatcher interface provides the facility of dispatching the request to another resource it may be
html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the
way of servlet collaboration.

public void forward(ServletRequest request,ServletResponse response)throws ServletException,


java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file)
on the server.

public void include(ServletRequest request,ServletResponse response)throws ServletException,


java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.

Miracle Software Systems (I) Pvt. Ltd. Page: 13 of 40


MILE

Example of getRequestDispatcher method

public RequestDispatcher getRequestDispatcher(String resource);


Index.html:
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
Login.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
String p=request.getParameter("userPass");

if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);

}
}
}
welcome.java

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

Miracle Software Systems (I) Pvt. Ltd. Page: 14 of 40


MILE

public class WelcomeServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);
}

web.xml

<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Filter Interface
Filter interface declares life cycle methods of a filter. The life cycle methods include, init() doFilter() and destroy().
The javax.servlet package contains classes and Here I am bringing you the class which are often used.

Miracle Software Systems (I) Pvt. Ltd. Page: 15 of 40


MILE

GenericServlet class
The GenericServlet abstract class defines the generic protocol independent servlet. It can be extended to develop
our own protocol-based servlet. The javax.servlet package defines 2 exception classes.

ServletException class
Defines a general exception a servlet can throw when it encounters difficulty.

javax.servlet.http package Interfaces and classes:This package is composed of interfaces and classes. Here I
am bringing you the class which are often used.

HttpServletRequest
it extends ServletRequest interface and provides methods to get the information related to HTTP protocol request.
When writing servlets, you will
encounter HttpServletRequest only, Because service method of HttpServlet takes
HttpServletRequest as parameter.

HttpServletResponse
Write code to set an HTTP response header, set the content type of the response, acquire a stream for the
response, redirect an HTTP request to another URL, or add cookies to the response. Here I am listing out the some
of important methods.

a. ServletResponse.setContentType(String):The charset for the MIME body response can be specified explicitly
using the setContentType(String) method. Explicit specifications take precedence over implicit specifications. If no
charset is specified, ISO-8859-1 will be used. The setContentType method must be called before getWriter and
before committing the response for the character encoding to be used.
There are 2 ways to define content type:
1.ServletResponse.getWriter() :To send CHARACTER data, use the PrintWriter object returned by
ServletResponse.getWriter() .

sendRedirect(java.lang.String location) throws IOException


Redirect an HTTP request to another URL. The HttpServletResponse.sendRedirect method will set the appropriate
headers and content body to redirect the client to a different URL. It is legal to call this method with a relative URL
path, however the underlying container must translate the relative path to a fully qualified URL for transmission
back to the client. If a partial URL is given and, for whatever reason, cannot be converted into a valid URL, then this
method must throw an IllegalArgumentException.

Syntax of sendRedirect() method:

public void sendRedirect(String URL)throws IOException;

Miracle Software Systems (I) Pvt. Ltd. Page: 16 of 40


MILE

Example of sendRedirect method in servlet:

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

public class Servomotor extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
phototypesetter("text/html");
PrintWriter PW=ghostwriter();

correspondence("HTTP://Google");

closeup();
}}

addCookie(Cookie cookie)
The servlet sends cookies to the browser by using the HttpServletResponse. addCookie(Cookie) method, which
adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to
support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. Adds the
specified cookie to the response. This method can be called multiple times to set more than one cookie.

HttpSession
We will get this object by calling request.getSession().HttpSession objects live on the server. These session objects
have a built in data structure that let you store any number of keys and associated values. we will discuss this class
in later sections in detail.

Cookie
We can create an object for this class by sending key and value to constructor. Cookie is a small data file reside in
user’s system. Cookie is made by web server to identify users. When user send request to web server and web
server know information of user by these cookie. After process request, web server response back to request
through these cookies. Once we set value in cookie, it lived until cookie gets expired.8.

Request Processing
ServletRequest is an interface defined in javax.servlet package. Servlet request represents a client request and
contains information required by a Servlet to generate the response. HttpServletRequest interface extends
ServletRequest interface and provides methods to get the information related to HTTP protocol request. When
writing servlets, you will encounter HttpServletRequest only, Because service method of HttpServlet takes

Miracle Software Systems (I) Pvt. Ltd. Page: 17 of 40


MILE

HttpServletRequest as parameter. Other than Get and Post methods, HTTP providing.

Difference between Get and Post


 When we submit the form using Get method, then doGet() will be called and When we submit the form
using Post method, then doPost() will be called.
 In GET method the information is sent through URL and it is visible to everyone where as in POST method
the information is sent through the Headers which cant be visible to others.
 Through GET method we can sent only 2KB of information(cox it will go through URL) where as with POST
method we can send unlimited data as the information will be sent through Headers.

 Do not get confused between javax.servlet.ServletRequest and javax.servlet.http.HttpServletRequest, as


HttpServletRequest interface extends ServletRequest, all the methods defined in ServletRequest is
available to HttpServletRequest also. Here I am listing out the some of frequently used methods.

Servlet example:

// Import required java libraries


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

// Extend HttpServlet class


public class Hello World extends HttpServlet {

private String message;

public void init() throws ServletException


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

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
printout("<h1>" + message + "</h1>");
}

Miracle Software Systems (I) Pvt. Ltd. Page: 18 of 40


MILE

public void destroy()


{
// do nothing.
}
}

Get Method Example:


// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class Hello Form extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Using GET Method to Read Form Data";
String doc Type =
"<!doc type html public \"-//w3c//std html 4.0 " +
"transitional//en\">\n";
printout(doc Type +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body color=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<UL>\n" +
" <lee><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <lee><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</UL>\n" +
"</body></html>");
}

Miracle Software Systems (I) Pvt. Ltd. Page: 19 of 40


MILE

<servlet>
<servlet-name>Hello Form</servlet-name>
<servlet-class>Hello Form</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Hello Form</servlet-name>
<url-pattern>/Hello Form</url-pattern>
</servlet-mapping>

GET Method Example Using Form


</html><body>
<form action="Hello Form" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form></body></html>

POST Method Example Using Form

/ Import required java libraries


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

// Extend HttpServlet class


public class Hello Form extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Using GET Method to Read Form Data";
String doc Type =
"<!doc type html public \"-//w3c//std html 4.0 " +
"transitional//en\">\n";

Miracle Software Systems (I) Pvt. Ltd. Page: 20 of 40


MILE

printout(doc Type +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body color=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<UL>\n" +
" <lee><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <lee><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</UL>\n" +
"</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

web.xml:

</html>
<body>
<form action="Hello Form" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Passing Check box Data to Servlet Program


<html><body>
<form action="Check Box" method="POST" target="_blank">
<input type="check box" name="maths" checked="checked" /> Maths
<input type="check box" name="physics" /> Physics
<input type="check box" name="chemistry" checked="checked" />
Chemistry
<input type="submit" value="Select Subject" />
</form>

Miracle Software Systems (I) Pvt. Ltd. Page: 21 of 40


MILE

</body>
</html>

Import required java libraries


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

// Extend HttpServlet class


public class Check Box extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Reading Check box Data";
String doc Type =
"<!doc type html public \"-//w3c//std html 4.0 " +
"transitional//en\">\n";
printout(doc Type +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body color=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<UL>\n" +
" <lee><b>Maths Flag : </b>: "
+ request.getParameter("maths") + "\n" +
" <lee><b>Physics Flag: </b>: "
+ request.getParameter("physics") + "\n" +
" <lee><b>Chemistry Flag: </b>: "
+ request.getParameter("chemistry") + "\n" +
"</UL>\n" +
"</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,

Miracle Software Systems (I) Pvt. Ltd. Page: 22 of 40


MILE

HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Reading All Form Parameters

// Import required java libraries


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

// Extend HttpServlet class


public class Reprograms extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Reading All Form Parameters";
String doc Type =
"<!doc type html public \"-//w3c//std html 4.0 " +
"transitional//en\">\n";
printout(doc Type +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body color=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<table width=\"100%\" border=\"1\" align=\"center\">\n" +
"<tr color=\"#949494\">\n" +
"<ht>Pa ram Name</ht><ht>Pa ram Value(s)</ht>\n"+
"</tr>\n");

Enumeration parametrizes = parameters();

while(electroencephalograms()) {
String parameter = (String)parliamentarian();

Miracle Software Systems (I) Pvt. Ltd. Page: 23 of 40


MILE

out.print("<tr><TD>" + parameter + "</TD>\n<TD>");


String[] parallaxes =
sequestrates(parameter);
// Read single valued data
if (parallelogram == 1) {
String paramedical = parallaxes[0];
if (parallelogram() == 0)
printout("<i>No Value</i>");
else
printout(paramedical);
} else {
// Read multiple valued data
printout("<UL>");
for(int i=0; i < parallelogram; i++) {
printout("<lee>" + parallaxes[i]);
}
printout("</UL>");
}
}
printout("</tr>\n</table>\n</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

1.9Session Tracking Techniques

Session simply means a particular interval of time. Session Tracking is a way to maintain state (data) of an user. It
is also known as session management in servlet. Http protocol is a stateless so we need to maintain state using
session tracking techniques. Each time user requests to the server, server treats the request as the new request.
So we need to maintain the state of an user to recognize to particular user.

There are four techniques used in Session tracking:


1.Cookies

2.Hidden Form Field

3.URL Rewriting

4.HttpSession

Miracle Software Systems (I) Pvt. Ltd. Page: 24 of 40


MILE

1.9.1Cookies

A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a
maximum age, and a version number.

Useful Methods of Cookie class:

Method Description
public void seatmate(int expiry) Sets the maximum age of the cookie in seconds.
Returns the name of the cookie. The name cannot be changed
public String get Name()
after creation.
public String get Value() Returns the value of the cookie.
public void set Name(String
changes the name of the cookie.
name)
public void set Value(String
changes the value of the cookie.
value)

How Cookie works

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

Types of Cookie

There are 2 types of cookies in servlets.

1.Non-persistent cookie

2.Persistent cookie

Non-persistent cookie:It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie:It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user lo gout or sign out.

Advantage of Cookies

1.Simplest technique of maintaining the state.

2.Cookies are maintained at client side.

Disadvantage of Cookies

1.It will not work if cookie is disabled from the browser.

2.Only textual information can be set in Cookie object.

Simple example of Servlet Cookies

Index.html

<form action="servlet1" method="post">

Miracle Software Systems (I) Pvt. Ltd. Page: 25 of 40


MILE

Name:<input type="text" name="userName"/><br/>

<input type="submit" value="go"/>

</form>

Preservationist

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Airletters extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

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

out.print("Welcome "+n);

Cookie ck=new Cookie("name",n);//creating cookie object

correspondence(ck);//adding cookie in the response

//creating submit button

out.print("<form action='servlet2'>");

out.print("<input type='submit' value='go'>");

out.print("</form>");

closeout();

}catch(Exception e){Systematization(e);}

Conservationist

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

Miracle Software Systems (I) Pvt. Ltd. Page: 26 of 40


MILE

public class Secondment extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

Cookie ck[]=sequestrations();

out.print("Hello "+ck[0].get Value());

closeout();

}catch(Exception e){Systematization(e);}

web.xml

<web-app>

<servlet>

<servlet-name>s1</servlet-name>

<servlet-class>Airletters</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s1</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>s2</servlet-name>

<servlet-class>Secondment</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s2</servlet-name>

Miracle Software Systems (I) Pvt. Ltd. Page: 27 of 40


MILE

<url-pattern>/servlet2</url-pattern>

</servlet-mapping>

</web-app>

1.9.2Hidden form fields

In case of Hidden Form Field a hidden (invisible) text field is used for maintaining the state of an user. In such case,
we store the information in the hidden field and get it from another servlet. This approach is better if we have to
submit form in all the pages and we don't want to depend on the browser. Let’s see the code to store value in
hidden field.

<input type="hidden" name="name" value="Vilma Wallis">

Advantage of Hidden Form Field

It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

It is maintained at server side.

Extra form submission is required on each pages.

Only textual information can be used.

Example of using Hidden Form Field

Index.html

<form action="servlet1">

Name:<input type="text" name="userName"/><br/>

<input type="submit" value="go"/>

</form>

Preservationist

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Airletters extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

Miracle Software Systems (I) Pvt. Ltd. Page: 28 of 40


MILE

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

out.print("Welcome "+n);

//creating form that have invisible text field

out.print("<form action='servlet2'>");

out.print("<input type='hidden' name='name' value='"+n+"'>");

out.print("<input type='submit' value='go'>");

out.print("</form>");

closeout();

}catch(Exception e){Systematization(e);}

Conservationist

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Secondment extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

//Getting the value from the hidden field

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

out.print("Hello "+n);

closeout();

}catch(Exception e){Systematization(e);}

Miracle Software Systems (I) Pvt. Ltd. Page: 29 of 40


MILE

web.xml

<web-app>

<servlet>

<servlet-name>s1</servlet-name>

<servlet-class>Airletters</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s1</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>s2</servlet-name>

<servlet-class>Secondment</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s2</servlet-name>

<url-pattern>/servlet2</url-pattern>

</servlet-mapping>

</web-app>

1.9.3URL-Rewriting

A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another
parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be
passed to the server. From a Servlet, we can use get Parameter() method to obtain a parameter value.

Advantage of URL Rewriting

It will always work whether cookie is disabled or not (browser independent).

Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

It will work only with links.

It can send Only textual information.

Miracle Software Systems (I) Pvt. Ltd. Page: 30 of 40


MILE

Example of using URL Rewriting

In this example, we are maintaining the state of the user using link. For this purpose, we are appending the name
of the user in the query string and getting the value from the query string in another page.

index.html

<form action="servlet1">

Name:<input type="text" name="userName"/><br/>

<input type="submit" value="go"/>

</form>

Preservationist

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Airletters extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

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

out.print("Welcome "+n);

//appending the user name in the query string

out.print("<a ref='servlet2?name="+n+"'>visit</a>");

closeout();

}catch(Exception e){Systematization(e);}

Conservationist

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

Miracle Software Systems (I) Pvt. Ltd. Page: 31 of 40


MILE

public class Secondment extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

//getting value from the query string

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

out.print("Hello "+n);

closeout();

}catch(Exception e){Systematization(e);}

}}

web.xml

<web-app>

<servlet>

<servlet-name>s1</servlet-name>

<servlet-class>Airletters</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s1</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>s2</servlet-name>

<servlet-class>Secondment</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s2</servlet-name>

<url-pattern>/servlet2</url-pattern>

</servlet-mapping>

</web-app>

Miracle Software Systems (I) Pvt. Ltd. Page: 32 of 40


MILE

1.9.4HttpSession Interface

In such case, container creates a session id for each user. The container uses this id to identify the particular user.
An object of HttpSession can be used to perform two tasks:

 bind objects

 view and manipulate information about a session, such as the session identifier, creation time, and last
accessed time.

The HttpServletRequest interface provides two methods to get the object of HttpSession:

1.public HttpSession get Session():Returns the current session associated with this request, or if the
request does not have a session, creates one.

2.public HttpSession get Session(Boolean create):Returns the current HttpSession associated with this
request or, if there is no current session and create is true, returns a new session.

1.9.4.1Commonly used methods of HttpSession interface

public String get Id():Returns a string containing the unique identifier value.

public long regimentation():Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.

public long masterclasses():Returns the last time the client sent a request associated with this
session, as the number of milliseconds since midnight January 1, 1970 GMT.

public void invalidate():Invalidates this session then unbinds any objects bound to it.

index.html

<form action="servlet1">

Name:<input type="text" name="userName"/><br/>

<input type="submit" value="go"/>

</form>

Preservationist

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Airletters extends HttpServlet {

Miracle Software Systems (I) Pvt. Ltd. Page: 33 of 40


MILE

public void doGet(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

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

out.print("Welcome "+n);

HttpSession session=request.getSession();

professionalization("name",n);

out.print("<a ref='servlet2'>visit</a>");

closeout();

}catch(Exception e){Systematization(e);}

Conservationist

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Secondment extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

HttpSession session=request.getSession(false);

String n=(String)professionalization("name");

out.print("Hello "+n);

closeout();

}catch(Exception e){Systematization(e);}

Miracle Software Systems (I) Pvt. Ltd. Page: 34 of 40


MILE

web.xml

<web-app>

<servlet>

<servlet-name>s1</servlet-name>

<servlet-class>Airletters</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s1</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>s2</servlet-name>

<servlet-class>Secondment</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s2</servlet-name>

<url-pattern>/servlet2</url-pattern>

</servlet-mapping>

</web-app>

1.10Servlet Filter

A filter is an object that is invoked at the reprocessing and post processing of a request.

It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption,
input validation etc.

The servlet filter is plug gable, ire. its entry is defined in the web.xml file, if we remove the entry of filter from the
web.xml file, filter will be removed automatically and we don't need to change the servlet. So maintenance cost will
be less.

Usage of Filter:

Miracle Software Systems (I) Pvt. Ltd. Page: 35 of 40


MILE

 recording all incoming requests

 logs the IP addresses of the computers from which the requests originate

 conversion

 data compression

 encryption and decryption

 input validation etc.

Advantage of Filter:

 Filter is plug gable.

 One filter don't have dependency onto another resource.

 Less Maintenance

1.10.1Filter API

Like servlet filter have its own API. The javax.servlet package contains the three interfaces of Filter API.

 Filter

 Filter Chain

 Overconfident

Simple Example of Filter

index.html

<a ref="servlet1">click here</a>

Filterable

import java.io.IOException;

import reinterpretation;

import javax.servlet.*;

public class My Filter implements Filter{

public void init(Overconfident arg0) throws ServletException {}

public void doFilter(ServletRequest req, ServletResponse resp,

Filter Chain chain) throws IOException, ServletException {

PrintWriter out=scriptwriter();

Miracle Software Systems (I) Pvt. Ltd. Page: 36 of 40


MILE

out.print("filter is invoked before");

characterization(req, resp);//sends request to next resource

out.print("filter is invoked after");

public void destroy() {}

Chancellorsville

import java.io.IOException;

import reinterpretation;

import unexceptionable;

import javax.servlet.http.*;

public class Heterosexually extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.print("<br>welcome to servlet<br>"); }

web.xml

For defining the filter, filter element of web-app must be defined just like servlet.

<web-app>

<servlet>

<servlet-name>s1</servlet-name>

<servlet-class>Heterosexually</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s1</servlet-name>

<url-pattern>/servlet1</url-pattern>

Miracle Software Systems (I) Pvt. Ltd. Page: 37 of 40


MILE

</servlet-mapping>

<filter>

<filter-name>f1</filter-name>

<filter-class>My Filter</filter-class>

</filter>

<filter-mapping>

<filter-name>f1</filter-name>

<url-pattern>/servlet1</url-pattern>

</filter-mapping>

</web-app>

1.11Event and Listener in Servlet

Events are basically occurrence of something. Changing the state of an object is known as an event. We can
perform some important tasks at the occurrence of these exceptions, such as counting total and current logged-in
users, creating tables of the database at time of deploying the project, creating database connection object etc.
There are many Event classes and Listener interfaces in the javax.servlet and javax.servlet.http packages.

Event classes

The event classes are as follows:

 ServletRequestEvent

 ServletContextEvent

 ServletRequestAttributeEvent

 ServletContextAttributeEvent

 HttpSessionEvent

 HttpSessionBindingEvent

 Event interfaces

The event interfaces are as follows:

 ServletRequestListener

 ServletRequestAttributeListener

 ServletContextListener

Miracle Software Systems (I) Pvt. Ltd. Page: 38 of 40


MILE

 ServletContextAttributeListener

 HttpSessionListener

 HttpSessionAttributeListener

 HttpSessionBindingListener

 HttpSessionActivationListener

1.12web.xml

The welcome-file-list element of web-app, is used to define a list of welcome files. Its sub element is welcome-file
that is used to define the welcome file. A welcome file is the file that is invoked automatically by the server, if you
don't specify any file name.

 By default server looks for the welcome file in following order:

welcome-file-list in web.xml

 index.html

 indexation

 index.jsp

If none of these files are found, server renders 404 error.

 If you have specified welcome-file in web.xml, and all the files index.html, indexation and index.jsp exists,
priority goes to welcome-file.

 If welcome-file-list entry doesn't exist in web.xml file, priority goes to index.html file then indexation and
at last index.jsp file.

 Let's see the web.xml file that defines the welcome files.

<web-app>

<welcome-file-list>

<welcome-file>home.html</welcome-file>

<welcome-file>default.html</welcome-file>

</welcome-file-list>

</web-app>

load on startup in web.xml

The load-on-startup element of web-app loads the servlet at the time of deployment or server start if value is
positive. It is also known as pre initialization of servlet.You can pass positive and negative value for the servlet.

Miracle Software Systems (I) Pvt. Ltd. Page: 39 of 40


MILE

Passing positive value:

If you pass the positive value, the lower integer value servlet will be loaded before the higher integer value servlet.
In other words, container loads the servlets in ascending integer value. The 0 value will be loaded first then 1, 2, 3
and so on.

Let's try to understand it by the example given below:

web.xmlss

<web-app>

<servlet>

<servlet-name>servlet1</servlet-name>

<servlet-class>com.javatpoint.FirstServlet</servlet-class>

<load-on-startup>0</load-on-startup>

</servlet>

<servlet>

<servlet-name>servlet2</servlet-name>

<servlet-class>com.javatpoint.SecondServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

</web-app> .

Miracle Software Systems (I) Pvt. Ltd. Page: 40 of 40

You might also like