Complete Java Filter Example

Aim
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.

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

Versions used in this example
Sofware/Component
Image
Windows XP SP2
N/A
Glassfish
N/A
JDK 1.5.0
N/A
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.

FilterExample
_|_web_bin
_|__|_index.html
_|__|_WEB-INF
_|__|__|_web.xml
_|__|__|_classes
_|__|_filtered
_|__|__|_index.html
_|_web_src
_|__|_myfilter
_|__|__|_MyFilter.java

Create and deploy the Service
  1. First let's write the filter and save it as MyFilter.java 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;
     2. 
     3. import java.io.IOException;
     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;
     9. 
    10. import java.util.logging.*;
    11. 
    12. import java.io.CharArrayWriter;
    13. import java.io.PrintWriter;
    14. 
    15. public class MyFilter implements javax.servlet.Filter {
    16.     private String redirectPage;
    17.     private ServletContext servletContext;
    18.     private Logger log;
    19.     
    20.     public MyFilter(){
    21.         super();
    22.     }
    23.     
    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.     }
    29. 
    30.     public void doFilter(   ServletRequest req, 
    31.                             ServletResponse res, 
    32.                             FilterChain filterChain)
    33.         throws IOException, ServletException {
    34. 
    35.         HttpServletRequest httpReq    = (HttpServletRequest)req;
    36.         HttpServletResponse    httpRes   = (HttpServletResponse)res;
    37.         
    38.         HttpSession session = httpReq.getSession();
    39. 
    40.         if(httpReq.getParameterValues("redirectme")!=null){
    41.             httpRes.sendRedirect(redirectPage);
    42.         }        
    43.         else{
    44.             PrintWriter out = httpRes.getWriter();
    45.             CharResponseWrapper wrapper = new CharResponseWrapper(httpRes);
    46. 
    47.             filterChain.doFilter(httpReq, wrapper);
    48.             
    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.     }
    63. 
    64.     public void destroy(){
    65.     }
    66. 
    67. }
    68. 
    69. class CharResponseWrapper extends HttpServletResponseWrapper {
    70.     private CharArrayWriter output;
    71. 
    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\MyFilter.java -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"?>
     2. 
     3. <web-app>
     4. 
     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>http://www.google.com</param-value>
    12.         </init-param>
    13.     </filter>
    14. 
    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>
    20. 
    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
    http://localhost:8080/myfilter/index.html.
    No change as the html is just served up.

  2. Now navigate to
    http://localhost:8080/myfilter/filtered/index.html.
    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
    http://localhost:8080/myfilter/filtered/index.html?redirectme=foo.
    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

5 comments:

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
Training

Dot Net Interview Questions