Servlet
Servlet
SERVLET
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
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. Servlets execute within the address space of a Web server. It is not necessary to create a separate process
to handle each client request.
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
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.
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 .
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.
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.
there our application will be there .if we run our application we need to click on our application.
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 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.
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.
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.
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
public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
Example
/* ServletConfig to get initialization parameter*/
DemoServlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
ServletConfig config=getServletConfig();
String driver=config.getInitParameter("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>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
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;
response.setContentType("text/html");
ServletConfig config=getServletConfig();
Enumeration<String> e=config.getInitParameterNames();
String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br>Name: "+str);
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.
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.
6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet
context.
ServletContext application=getServletConfig().getServletContext();
<web-app>
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
</web-app>
WEB.XML:
<web-app>
<servlet>
<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>
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.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {
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.*;
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.
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() .
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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
HttpServletRequest as parameter. Other than Get and Post methods, HTTP providing.
Servlet example:
<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>
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>
</body>
</html>
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Reading All Form Parameters
while(electroencephalograms()) {
String parameter = (String)parliamentarian();
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.
3.URL Rewriting
4.HttpSession
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.
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)
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
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
Disadvantage of Cookies
Index.html
</form>
Preservationist
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action='servlet2'>");
out.print("</form>");
closeout();
}catch(Exception e){Systematization(e);}
Conservationist
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
Cookie ck[]=sequestrations();
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>
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.
Index.html
<form action="servlet1">
</form>
Preservationist
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action='servlet2'>");
out.print("</form>");
closeout();
}catch(Exception e){Systematization(e);}
Conservationist
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
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>
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.
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">
</form>
Preservationist
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
String n=request.getParameter("userName");
out.print("Welcome "+n);
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.*;
try{
response.setContentType("text/html");
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>
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.
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">
</form>
Preservationist
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
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.*;
try{
response.setContentType("text/html");
HttpSession session=request.getSession(false);
String n=(String)professionalization("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>
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:
logs the IP addresses of the computers from which the requests originate
conversion
data compression
Advantage of Filter:
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
index.html
Filterable
import java.io.IOException;
import reinterpretation;
import javax.servlet.*;
PrintWriter out=scriptwriter();
Chancellorsville
import java.io.IOException;
import reinterpretation;
import unexceptionable;
import javax.servlet.http.*;
response.setContentType("text/html");
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>
</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>
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
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
HttpSessionEvent
HttpSessionBindingEvent
Event interfaces
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
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.
welcome-file-list in web.xml
index.html
indexation
index.jsp
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>
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.
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.
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> .