• Filter is a web component like a servlet.
• A servlet is responsible for core request processing.
• Before core request processing by a servlet, i.e., before calling the service () method, you may want to perform some tasks. This is referred to as POST PROCESSING tasks.
• Following are various pre-processing tasks that you can perform on an incoming request before a core request processing
o Logging
o Security checks include authentication and authorization.
o Verification Session Validity, etc.
• Following are various post-processing tasks that you can perform on outgoing responses after core requests processing:
o Data compression
o Data encryption or encoding
o URL: Rewriting etc.
• If you write code for pre-processing and post-processing tasks across all servlets, code will be generated duplicated and gives you a maintenance problem when you try to change that code.
• To avoid code duplication and maintenance issues, you must create pre-processing tasks. Post-processing tasks are coded in a central place called filter.
1. Write your own filter class by implementing the javax.servlet.Filter interface.
2. Your filter class has to override the following three lifecycle methods:
a. Public void init (FilterConfig fc)
b. Public void doFilter(ServletRequest req,ServletResponse res,FilterChain fc)
c. public void destroy()
3. Configure the file, web.xml, as follows:
<filter>
<filter-name>demoFilter</filter-name>
<filter-class>com.jtcindia.servlet.DemoFilter</filter-class>
<init-param>
<param-name>city</param-name>
<param-value>Noida</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>demoFilter</filter-name>
<url-pattern>/test</url-pattern>
</filter-mapping>
1. Write your own filter class by implementing javax.servlet. Filter interface.
2. Your filter class has to override the following three lifecycle methods:
a. Public void init (FilterConfig fc)
b. Public void doFiletr(ServletRequest req,ServletResponse res,FilterChain fc)
c. public void destroy()
3. Configure the filter information in the filter class only with the annotations as follows:
@WebFilter(filterName="demoFilter",urlPatterns={"/demo.jtc"},
initParams={@WebInitParam(name="city",value="NOIDA")})
public class implements Filter{
//method implementation}
File Required For Program
1. Index.html
2. DemoServlet.java
3. DemoFilter.java
4. Web.xml
1. Index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>JTC</h1>
<h2>Filter Demo</h2>
<form action="test" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Test Filter"/>
</td>
</table>
</form>
</body>
</html>
2. DemoServlet.java
package com.jtcindia.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends
HttpServlet {
@Override
public void init(ServletConfig config)
throws ServletException {
System.out.println("DemoServlet-init()**");
String
ci = config.getInitParameter("city");
System.out.println(ci);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException,
IOException {
System.out.println("DemoServlet
service() ** * ");
String nm = req.getParameter("name"); String em = req.getParameter("email"); String ip = req.getRemoteAddr(); String msg = "<h1>Hello!" + nm + "<br>"; msg = msg + "you Email Id is" + em + "<br>"; msg = msg + "You sre sending the requesting
from IP Address: "+ip;
PrintWriter out = res.getWriter(); out.println(msg);
}
public void destroy() {
System.out.println("***Destroyed()");
}
}
3. DemoFilter.java
package com.jtcindia.servlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class DemoFilter implements Filter {
public void destroy() {
System.out.println("destroy()");
}
public void doFilter(ServletRequest req,
ServletResponse res, FilterChain chain)
throws IOException, ServletException {
String
nm = req.getParameter("name");
String
em = req.getParameter("email");
String ip = req.getRemoteAddr();
System.out.println(nm);
System.out.println(em);
System.out.println(ip);
chain.doFilter(req, res);
System.out.println("DemoFilterdoFilter()-after");
Object
obj = req.getAttribute("MSG");
System.out.println(obj);
String msg = obj.toString();
System.out.println(msg);
}
public void init(FilterConfig config)
throws ServletException {
System.out.println("**DemoFilter..Init()");
String
ci = config.getInitParameter("city");
System.out.println(ci);
}
}
4. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/webapp_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Jtc23</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servletclass>com.jtcindia.servlet.DemoServlet</servletclass>
<init-param>
<param-name>city</param-name>
<param-value>Delhi</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<filter>
<filter-name>demoFilter</filter-name>
<filterclass>com.jtcindia.servlet.DemoFilter</filterclass>
<init-param>
<param-name>city</param-name>
<param-value>Noida</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>demoFilter</filter-name>
<url-pattern>/test</url-pattern>
</filter-mapping>
</web-app>
• All the filters configured will be initialised by the container at container start-up.
• At the time of initialising the filter at container start-up, the container will have the following tasks:
o A filter class will be loaded.
o A filter instance will be created by calling default constructor.
o The container will cast the instance into a javax.servlet. Filter type to ensure it is filtered.
o Container creates the FilterConfig object and initialises the FilterConfig object with the configuration parameters specified in web.xml or annotations.
o The FilterConfig object will be initialised with the ServletContext object.
o Container calls the init() method by passing the FilterConfig object as a parameter.
• At the time of destroying the filter at container shutdown, the container calls the destroy() method to release the resource initialised by the init() method.
• If you want to invoke one filter before multiple servlets, then you have to configure the filter with any one of the following ways:
<filter>
<filter-name>filterB</filter-name>
<filter-class>com.jtcindia.SessionValidationFilter</filter-class>
</filter>
Option 1:
<filter-mapping>
<filter-name>filterC</filter-name>
<url-pattern>/add.jtc</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>JtcSessionFilter</filter-name>
<servlet-name>removeServlet</servlet-name>
</filter-mapping>
Option 2:
<filter-mapping>
<filter-name>filterC</filter-name>
<url-pattern>/add.jtc</url-pattern>
<url-pattern>/remove.jtc</url-pattern>
</filter-mapping>
Option 3:
<filter-mapping>
<filter-name>JtcSessionFilter</filter-name>
<url-pattern>*.jtc</url-pattern>
</filter-mapping>