Professional Documents
Culture Documents
Servlet-Notes Compress
Servlet-Notes Compress
Problems in CGI:
There are many problems in CGI technology:
1. If number of client increased, response time very less.
2. For each request, it starts a process. Web server is limited to start process.
3. It uses plateform dependent language e.g. C,C++,perl.
HTTP (Hyper Text Transfer Protocol):
Http is the protocol that allows web servers and browsers to exchange data over the web.
It is a stateless TCP/IP based protocol used for Communicating on the World Wide Web. HTTP defines the manner in
which web clients communicate with web servers. Today, the most common version of this is HTTP/1.0.HTTP also
called a connectionless protocol.
A protocol is said to be stateless if it has no memory of prior connections and cannot distinguish one client’s request
from that of another. The stateless nature of HTTP is both its strength and weakness. The strength is that its stateless
nature keeps the protocol simple and straightforward. The disadvantage is in the overhead required to create a new
connection with each request and the inability to track a single user. That is, using HTTP, a client opens a connection
with the server, and sends requests, receives a response and closes the connection. Each request requires its own
connection.
Now let us take a close look how HTTP helps to communicate between a web server and a web browser.
There are generally four stages of a simple web transaction:
1. The client opens a connection to the server:
First, the client opens a TCP/IP connection to the server. By default, the connection on the server is made to
port 80, unless or otherwise specified.
4. Connection is closed
Either the server or the client may close the connection. The server generally terminates the connection after
The response has been sent. Similarly, a browser often closes the connection once the complete response has
Been received.
• TRACE
HTTP Request
Description
Method
GET Asks to get the resource at the requested URL.
Asks the server to accept the body info attached. It like a GET with extra info sent with
POST
the request.
Asks for only the header part of whatever a GET would return. Just like GET but with no
HEAD
body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
DELETE Says to delete the resource at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond
There are many differences between the Get and Post request. Let's see these differences:
GET POST
1) In case of Get request, only limited amount of data can In case of post request, large amount of data can be
be sent because data is sent in header. sent because data is sent in body.
2) Get request is not secured because data is exposed in Post request is secured because data is not exposed in
URL bar. URL bar.
3) Get request can be bookmarked Post request cannot be bookmarked
4) Get request is idempotent Post request is non-idempotent
5) Get request is more efficient and used than Post Post request is less efficient and used.
Content Type:
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type.It is a HTTP header that
provides the description about what are you sending to the browser.There are many content types:
• text/html
• text/plain
• application/msword
• application/vnd.ms-excel
• application/jar
• application/pdf
• application/octet-stream
• application/x-zip
• images/jpeg
• vedio/quicktime etc.
What is a Servlet :-
1. A servlet is simply a java program that runs on the server.
2. Servlets are designed to accept a response from a client (usually a web browser), process that request,
and return a response to the client.
3. A good analogy for a servlet is a non-visual applet that runs on a server.
4. A Servlet can be thought of as a server side applet. Servlets are loaded and executed by a web server in
the same manner in which applets are loaded and executed by a web browser. Thus, we can say that
Servlet is a server side software component, written in Java that dynamically extends the functionality of
a server.
5. With Servlet, Web developers can create fast and efficient server-side applications in Java instead of
using CGI and Perl.
6. A servlet’s work is done “behind the scene” on the server.
7. The results of the Servlet are returned to the client usually in the form of HTML.
Advantage of Servlet:
1. Better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so no need to worry about memory leak, garbage collection etc.
A Servlet is part of a Java web application. A Servlet container may run multiple web applications at the same time, each
having multiple servlets running inside. Here is an illustration of that:
A Java web application can contain other components than servlets. It can also contain Java Server Pages (JSP), Java
Server Faces (JSF) and Web Services. This tutorial is about Java Servlets only, though.
Once the servlet has been activated via the service () method, the servlet processes the request, and generates a response.
The response is then sent back to the browser.
Life Cycle of a Servlet (Servlet Life Cycle):
A servlet follows a certain life cycle. The servlet life cycle is managed by the servlet container. The life cycle contains the
following steps:
1. Load Servlet Class.
2. Create Instance of Servlet.
3. Call the servlets init () method.
4. Call the servlets service () method.
The init method is called by the servlet container after the servlet class has been instantiated. The servlet
container calls this method exactly once to indicate to the servlet that the servlet is being placed into service.
The init method must complete successfully before the servlet can receive any requests.
You can override this method to write initialization code that needs to run only once, such as loading a database
driver, initializing values, and so on. In other cases, you normally leave this method blank.
The init method is important also because the servlet container passes a ServletConfig
object, which contains the configuration values stated in the web.xml file for this
application.
2)Create a Servlet:
//DemoServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
}
}
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar
files:
Jar file Server
1) servlet-api.jar Apache Tomacat
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
1. set classpath
2. paste the jar file in JRE/lib/ext folder
Put the java file in any folder. After compiling the java file paste the class file of servlet in WEB-INF/classes
folder.
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
5)Start Server:
To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment variables.
Go to My Computer properties
Click on advanced tab then environment variables
Click on the new tab of user variable
Write JAVA_HOME in variable name and paste the path of jdk folder in variable value
Ok
Ok
Ok
Servlet API: - Two packages are available:-
1. javax.servlet :-
2. javax.servlet.http :-
Servlet Interface:-
Servlet interface is the central abstraction of the java servlet technology.
Every servlet you write must implements this interface either directly or indirectly (By subclassing the
GenericServlet ot HttpServlet class).
It is collection of empty method signatures.
Servlet
|
GenericServlet HttpServlet
| |
(Protocol independent) MyServlet MyServlet (Http Specific)
Examples:-
package ServletBasic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
}
public ServletConfig getServletConfig() {
return null;
}
public String getServletInfo() {
return null;
}
public void init(ServletConfig arg0) throws ServletException {
}
<web-app >
<servlet>
<servlet-name>ServletDemo</servlet-name>
<servlet-class>ServletBasic.ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo</servlet-name>
<url-pattern>/ServletDemo</url-pattern>
</servlet-mapping>
</web-app>
ServletConfig Interface:-
An object of ServletConfig is created by the web container for each servlet.
This object can be used to get configuration information from web.xml file.
Methods of ServletConfig interface:
1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names.
3. public String getServletName():Returns the name of the servlet.
package ServletBasic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class PreserveServletConfigInfo implements Servlet {
ServletConfig config;
package ServletBasic;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.*;
ServletContext Interface :-
It is the environment where the servlet runs.
All servlets belong to one servlet context. It can only be called at context initialization time.
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.
A servlet can also bind an object attribute into context by name
ServletContext context= config.getServletContext();
context.setAttribute("password", "121212");
Any object bound into context is available to any other servlet that is the part of the same application
package ServletBasic;
import javax.servlet.*;
import java.util.Enumeration;
import java.io.IOException;
ServletConfig servletConfig;
<servlet>
<servlet-name>ContextDemoServlet</servlet-name>
<servlet-class> ServletBasic.ContextDemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextDemoServlet</servlet-name>
<url-pattern>/ContextDemoServlet</url-pattern>
</servlet-mapping>
Sharing Information Among Servlets :-
AttributeSetterServlet
package ServletBasic;
import javax.servlet.*;
import java.io.IOException;
<servlet>
<servlet-name>AttributeSetterServlet</servlet-name>
<servlet-class> ServletBasic.AttributeSetterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AttributeSetterServlet</servlet-name>
<url-pattern>/AttributeSetterServlet</url-pattern>
</servlet-mapping>
DisplayAttributesServlet
package ServletBasic;
import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;
<servlet>
<servlet-name>ResponseDemoServlet</servlet-name>
<servlet-class> ServletBasic.ResponseDemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ResponseDemoServlet</servlet-name>
<url-pattern>/ResponseDemoServlet</url-pattern>
</servlet-mapping>
Output :-
Attribute name : javax.servlet.context.tempdir
Attribute value : C:\123data\JavaProjects\JavaWebBook\work\localhost_8080
Attribute name : password
Attribute value : dingdong
Attribute name : sun.servlet.workdir
Attribute value : C:\123data\JavaProjects\JavaWebBook\work\localhost_8080
ServletRequest Interface:-
Whenever the web container receives a request from the web browser, it creates a servlet request and
identifies which servlet needs to be invoked based on the URL mapping, calls the service method of the
servlet and passes the servlet request object as parameter.
ServletRequest interface encapsulates the communication from the client to the server.
9. public int getServerPort():Returns the port number on which this request was received.
ServletResponse Interface:
This interface represents the response from the servlet to a web client.
SingleThreadModel:-
Servlet in java application can be accessed by multiple users at a same
time. SingleThreadModel is deprecated. Although it is not good thing to use
SingleThreadModel in servlet, we can use it to restrict access of more than
one user at a same time. SingleThreadModel is useful in case you required to
process one request at one time, no other can access that process when
servlet is in use.
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
}
GenericServlet :-
It is an abstract class and implements Servlet interface, ServletConfig interface and Serializable interface.
Writing servlet by extending GenericServlet is easy comparison to creating a servlet by implementing the
Servlet interface. Because in the case of Servlet Interface we have to provide all the methods
implementation. Even if we use or not.
In GenericServlet service method is abstract . so when we extend this class to create a servlet then we must
provide the implementation of this method.
We write our code in this method.
Example :-
import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
HttpServlet Class :-
This class extends the GenericServlet.
It is specific to the http protocol.
It is the most used class in the servlet.
It is present in the javax.servlet.http package.
It contains the methods such as doGet(),doPost(),doDelete(),doHeader() etc.
Methods are:-
• doGet()
• doPost()
• doDelete()
• doHeader()
• doPut()
• service()
• protected service() method receives HTTP requests from the public service method and dispatches them to
the do...() methods defined in this class.
doGet()
o This method is used for handling the get request. It is called by the service methods.
o This supports the HTTP HEAD request.
o HEAD request is a GET request.
o It returns no body.
o It returns the request header fields.
o In these methods values passing from form to the server get added to the URL.
o It allows limited data to be passed
doPost ()
When the user clicks the Submit button to submit the form, the browser sends an HTTP request to the
server using the POST method. The web server then passes this request to the servlet and the doPost method of the
servlet is invoked. Using the POST method in a form, the parameter name/value pairs of the form are sent in the
request body.
For example, if you use the below form as an example and enter Ankit as the value for firstName and Jain as the
value for lastName, you will get the following result in the request body:
<html>
<head>
<title> Ankit First HTTP Servlet DEMO </title>
</head>
<body>
<FORM ACTION="Register" METHOD="POST">
<INPUT TYPE=TEXT Name="firstName">
<INPUT TYPE=TEXT Name="lastName">
<INPUT TYPE=SUBMIT>
</FORM>
</body>
</html>
sendRedirect() method:
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource,
it may be servlet, jsp or html file. It can accept relative URL. This method can work inside and outside the server
as it uses the URL bar of the browser.
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.sendRedirect("http://www.google.com");
pw.close();
}}
RequestDispatcher Interface:
The RequestDispacher 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.
Methods of RequestDispatcher:
Program of RequestDispatcher:
index.html
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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>
Attribute in Servlet:
An attribute is an object that can be set,get or removed from one of the following scopes:
1. request scope
2. session scope
3. application scope
1. public void setAttribute(String name,Object object):sets the given object in the application scope.
2. public Object getAttribute(String name):Returns the attribute for the specified name.
3. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters as an Enumeration of String objects.
4. public void removeAttribute(String name):Removes the attribute with the given name from the servlet
context.
DemoServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
context.setAttribute("company","IBM");
}catch(Exception e){out.println(e);}
}}
DemoServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet2 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
String n=(String)context.getAttribute("company");
out.println("Welcome to "+n);
out.close();
}catch(Exception e){out.println(e);}
}}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>DemoServlet1</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>DemoServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
The servletconfig object refers to the single servlet whereas servletcontext object refers to the whole web
application.
Cookies in Session Tracking:
Session Tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
1) Cookies:
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.
javax.servlet.http.Cookie class:
Constructor:
Cookie(String name, String value): Constructs a cookie with a specified name and value.
1. public void setMaxAge(int expiry):Sets the maximum age of the cookie in seconds.
2. public String getName():Returns the name of the cookie. The name cannot be changed after creation.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies
from the browser.
Advantage of Cookies:
Disadvantage of Cookies:
index.html
FirstServlet.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);
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getName());
out.close();
}catch(Exception e){System.out.println(e);}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</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>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.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);
out.print("<form action='servlet2'>");
out.print("<input type='hidden' name="uname" value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</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>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
3)URL Rewriting:
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send
parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
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 getParameter() method to obtain a parameter value.
Advantage of URL Rewriting:
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</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>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
4)HttpSession 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:
1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time, and last
accessed time.
How to get HttpSession object?
The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. public HttpSession getSession():Returns the current session associated with this request, or if the request
does not have a session, creates one.
2. public HttpSession getSession(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.
4. 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>
FirstServlet.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);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</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>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Filter:
A filter is an object that is used to performed filtering tasks such as conversion,log
maintain,compression,encryption and decryption,input validation etc.A filter is invoked at the preprocessing and
postprocessing of a request.
Uses of Filter:
Advantage of Filter:
1. Filter is pluggable.
Filter API
Like servlet filter have its own API.The javax.servlet package contains the three interfaces of Filter API
1. Filter
2. FilterChain
3. FilterConfig
1) Filter interface
For creating any filter, you must implement the Filter interface.Filter interface provides the life cycle methods for a
filter.
1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
2. public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain):
doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It
is used to perform filtering tasks.
3. public void destroy():This is invoked only once when filter is taken out of the service.
2) FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the chain.This object is passed in the
doFilter method of Filter interface.The FilterChain interface contains only one method:
3) FilterConfig interface
For creating any filter, you must implement the Filter interface.Filter interface provides the life cycle methods for a
filter.
1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
2. public String getInitParameter(String parameterName): Returns the parameter value for the specified
parameter name.
3. public java.util.Enumeration getInitParameterNames(): Returns an enumeration containing all the
parameter names.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
MyFilter.java
import java.io.*;
import javax.servlet.*;
PrintWriter out=res.getWriter();
chain.doFilter(req, res);
out.print("<br/>filter invoked..");
}
public void destroy() {}
}
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("Welcome servlet");
out.close();
}catch(Exception e){System.out.println(e);}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</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>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
MyFilter.java
import java.io.*;
import javax.servlet.*;
PrintWriter out=res.getWriter();
}
public void destroy() {}
}
MyFilter.java
import java.io.*;
import javax.servlet.*;
PrintWriter out=res.getWriter();
chain.doFilter(request,response);
}
public void destroy() {}
}
MyFilter.java
import java.io.*;
import javax.servlet.*;
PrintWriter out=res.getWriter();
long before=System.currentTimeMillis();
chain.doFilter(request,response);
long after=System.currentTimeMillis();
out.print("<br/>Total response time "+(after-before)+" miliseconds");
out.close();
}
public void destroy() {}
}
Simple.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Simple")
public class Simple extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("<html><body>");
out.print("<h3>Hello Servlet</h3>");
out.print("</body></html>");
}
}