Complete Java Filter Example

The aim of this tutorial is to create a simple yet fully functional Java Filter. This filter will redirect a request based on a URL parameter and modify the "body" text in a response. This filter can be deployed in any java container. Please leave any question or comments at the end and I will endeavour to answer them.

This article assumes that you have Glassfish or Tomcat or an equivalent java container installed and configured.

Versions used in this example
Windows XP SP2
JDK 1.5.0
Links to these files can be found here

For the purposes of this tutorial the files are stored in the structure below. The FilterExample directory is the working directory.


Create and deploy the Service
  1. First let's write the filter and save it as in the web_src/myfilter directory. As you can see we inspect the request for a parameter named "redirect." If we find it we redirect the page to google. This is configured throught the init-parameters for the filter and is in the web.xml file. The response is modified by appending "hello There" just before the closing body tag.
     1. package myfilter;
     3. import;
     4. import javax.servlet.*;
     5. import javax.servlet.http.HttpServletRequest;
     6. import javax.servlet.http.HttpServletResponse;
     7. import javax.servlet.http.HttpServletResponseWrapper;
     8. import javax.servlet.http.HttpSession;
    10. import java.util.logging.*;
    12. import;
    13. import;
    15. public class MyFilter implements javax.servlet.Filter {
    16.     private String redirectPage;
    17.     private ServletContext servletContext;
    18.     private Logger log;
    20.     public MyFilter(){
    21.         super();
    22.     }
    24.     public void init(FilterConfig filterConfig) throws ServletException {
    25.         servletContext = filterConfig.getServletContext();
    26.         redirectPage = filterConfig.getInitParameter("Redirect-Page");
    27.         log = Logger.getLogger(MyFilter.class.getName());
    28.     }
    30.     public void doFilter(   ServletRequest req, 
    31.                             ServletResponse res, 
    32.                             FilterChain filterChain)
    33.         throws IOException, ServletException {
    35.         HttpServletRequest httpReq    = (HttpServletRequest)req;
    36.         HttpServletResponse    httpRes   = (HttpServletResponse)res;
    38.         HttpSession session = httpReq.getSession();
    40.         if(httpReq.getParameterValues("redirectme")!=null){
    41.             httpRes.sendRedirect(redirectPage);
    42.         }        
    43.         else{
    44.             PrintWriter out = httpRes.getWriter();
    45.             CharResponseWrapper wrapper = new CharResponseWrapper(httpRes);
    47.             filterChain.doFilter(httpReq, wrapper);
    49.             if(wrapper.getContentType() != null && wrapper.getContentType().indexOf("text/html")!=-1) {
    50.                 CharArrayWriter caw = new CharArrayWriter();
    51.                 caw.write(wrapper.toString().substring(0, wrapper.toString().indexOf("</body>")-1));
    52.                 caw.write("<p>\nHello There</p>");
    53.                 caw.write("\n</body></html>");
    54.                 httpRes.setContentLength(caw.toString().length());
    55.                 out.write(caw.toString());
    56.             }
    57.             else{
    58.                 out.write(wrapper.toString());
    59.             }
    60.             out.close();
    61.         }
    62.     }
    64.     public void destroy(){
    65.     }
    67. }
    69. class CharResponseWrapper extends HttpServletResponseWrapper {
    70.     private CharArrayWriter output;
    72.     public String toString() {
    73.         return output.toString();
    74.     }
    75.     public CharResponseWrapper(HttpServletResponse response) {
    76.         super(response);
    77.         output = new CharArrayWriter();
    78.     }
    79.     public PrintWriter getWriter() {
    80.         return new PrintWriter(output);
    81.     }
    82. }
    Hide line numbers

  2. Now cd into the web_src directory and compile the source. Replace the path to Glassfish's lib directory with your local path. This could be lib in tomcat or any servlet container.

    ..FilterExample\web_src>javac myfilter\ -d ..\web_bin\WEB-INF\classes -extdirs d:\downloads\glassfish\lib

  3. Now create the web.xml file which will have our filter mapping and an init parameter. Save this under the WEB-INF directory under web_bin.
     1. <?xml version="1.0" encoding="ISO-8859-1"?>
     3. <web-app>
     5.    <!-- Define servlet-mapped and path-mapped example filters -->
     6.     <filter>
     7.         <filter-name>My Filter</filter-name>
     8.         <filter-class>myfilter.MyFilter</filter-class>
     9.         <init-param>
    10.             <param-name>Redirect-Page</param-name>
    11.             <param-value></param-value>
    12.         </init-param>
    13.     </filter>
    15.     <!-- Define filter mappings for the defined filters -->
    16.     <filter-mapping>
    17.         <filter-name>My Filter</filter-name>
    18.         <url-pattern>/filtered/*</url-pattern>
    19.     </filter-mapping>
    21. </web-app>
    Hide line numbers
    As you can see the filter will intercept any url starting with "/filter/*"

  4. now create a simple index.html file and save one copy in the web_bin directory and one in the web_bin/filtered directory.
     1. <html>
     2. <head></head>
     3. <body>
     4. <h1>Test</h1>
     5. </body>
     6. </html>
    Hide line numbers

  5. Now create the war file. Cd into the web_bin directory and jar it all up.

    ..FilterExample\web_bin>jar -cvf myfilter.war *

  6. Finally deploy this war file in the servlet container of your choice. Glassfish in this example.

Testing the filter
  1. First navigate to
    No change as the html is just served up.

  2. Now navigate to
    This url matches the url pattern in the web.xml file and the filter gets called. You will notice that "Hello There" appended to the html.

  3. Now navigate to
    This time the filter catches the redirectme using getParameterValues and redirect the browser to google.

To add headers to a Request please visit Adding HTTP Headers To Requests in Filters and Servlets.
To stop responses committing and redirecting errors visit Modifying and Redirecting Filter Responses


Anonymous said...

thanks a lot.Simple and understanding for a beginner

Sayo said...

Please can you help me with this question? I am a java beginner and I wrote two programs that does the same thing in different format. The first program is BMI in kg/m2 and the second one is BMI in lbs/inches2. My question is that how can I put a frame round these two programs that will enable users to choose which one they want to use instead of having two separate programs?
Thank you for your help.

Anonymous said...

Thank you for doing this. Helped me solve an important problem.

Lamessa Garba said...

How can for example we write a filter program to filter the words (good morning, good evening) from the chatting application? And also how can we give the URL pattern of filter and servlet?

Naviya Nair said...

Very interesting and good Explanation
ASP NET Training
ASP NET Training
ASP NET Online Training
C-Sharp Training
Dot Net Training in Chennai
Online .Net Training

MVC Training
WCF Training
Web-API Training
LINQ Training
Entity Framework

Dot Net Interview Questions