Filter in servlet in java

Posted by Satyapriyanayak under Others category on | Points: 40 | Views : 703
Filter : - It is a program which executes on the time of providing request to a specific url. The filter resides in a webserver. Whenever the user provides the request to the associated URL then the request goes to the filter. The filter can modify the request or perform any task before passing the request to the destination.

Creation process of filter
1.create a class by inheriting javax.servlet.filter interface.
2.Override methods of filter interface. The methods are as follows:
public void init()
public void doFilter(servletRequest req,servletResponse res,filterchain chain)
public void destroy()
3.Perform the required task inside doFilter()
4.Transfer request and response to the destination by using doFilter() of filterchain.

Storing, compilation and deployment of filter
1.Store the filter file inside classes’ folder of the context.
2.Compile the filter file by using servlet-api.jar in classpath.
3.deploy the filter by using the required tags in web.xml file. The tags are as follows:

<filter-name>This contains mapping name for the filter</filter-name>
<filter-class> This contains class name for the filter </filter-class>

<filter-name> This contains mapping name for the filter </filter-name>
<url-pattern>/ This contains the url for whom the filter will execute </url-pattern>

Example: -

<h1><a href="./genserv">Visit Genserv</a></h1>
</html> file

//Using GenericServlet
import javax.servlet.*;
public class genserv extends GenericServlet

public void service(ServletRequest req,ServletResponse res)throws IOException,ServletException
PrintWriter out=res.getWriter();
out.println("<html><body bgcolor='blue'>");
out.println("<h1>First Servlet</h1>");
} file

//A filter file
import javax.servlet.*;
import javax.servlet.http.*;

public class Filtercounter implements Filter {

public void init(FilterConfig con){}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain)throws IOException, ServletException
try {
FileWriter fw=new FileWriter("E:/filter/fil.txt",true);

fw.write("page accessed");
chain.doFilter(request, response);
catch(Throwable t) {
public void destroy(){}


Web.xml settings

<?xml version="1.0" encoding="ISO-8859-1"?>






Compile both the files as below
javac -cp servlet-api.jar (for tomcat 6.0)
javac -cp servlet-api.jar (for tomcat 6.0)

Run the tomcat
Here test is the Context path, which we mentioned in the server.xml file, which is present in (E:\Program Files\Apache Software Foundation\Tomcat 6.0\conf) directory.
After giving the url a set a listing will come, here only one appears
As access.html,click it

Note:- You will notice in E:/filter/fil.txt file how many times the user will visit this Url(http://localhost:8081/test/genserv) that number of times page access will be written to that file.

Comments or Responses

Login to post response