Java/Servlets/Filter

Материал из Java эксперт
Перейти к: навигация, поиск

Another Filter Demo

Block Filter

 
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class BlockFilter implements Filter {
  private FilterConfig config;
  /** Creates new BlockFilter */
  public BlockFilter() {
  }
  public void init(FilterConfig filterConfig) throws ServletException {
    this.config = filterConfig;
  }
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = null;
    boolean authenticated = false;
    PrintWriter out = null;
    if (request instanceof HttpServletRequest) {
      req = (HttpServletRequest) request;
      String user = req.getParameter("user");
      authenticated = authenticateUser(user);
    }
    if (authenticated) {
      chain.doFilter(request, response);
    } else {
      response.setContentType("text/html");
      out = response.getWriter();
      out
          .println("<html><head><title>Authentication Response</title></head><body>");
      out.println("<h2>Sorry your authentication attempt failed</h2>");
      out.println("</body></html>");
      out.close();
    }
  }// doFilter
  public void destroy() {
    /*
     * called before the Filter instance is removed from service by the web
     * container
     */
  }
  private boolean authenticateUser(String userName) {
    //authenticate the user using JNDI and a database, for instance
    return false;
  }
}





Cache Filter

 
/*
 ************************************************************************************
 * Copyright (C) 2001-2006 Openbravo S.L.
 * Licensed under the Apache Software License version 2.0
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to  in writing,  software  distributed
 * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
 * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
 * specific language governing permissions and limitations under the License.
 ************************************************************************************
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class CacheFilter implements Filter {
  private String[][] replyHeaders = { {} };
  public void init(FilterConfig config) {
    Enumeration<?> names = config.getInitParameterNames();
    ArrayList<String[]> tmp = new ArrayList<String[]>();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      String value = config.getInitParameter(name);
      String[] pair = { name, value };
      tmp.add(pair);
    }
    replyHeaders = new String[tmp.size()][2];
    tmp.toArray(replyHeaders);
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    for (int n = 0; n < replyHeaders.length; n++) {
      String name = replyHeaders[n][0];
      String value = replyHeaders[n][1];
      httpResponse.addHeader(name, value);
    }
    chain.doFilter(request, response);
  }
  public void destroy() {
  }
}





Checker Filter

 
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CheckFilter implements Filter {
  private FilterConfig config;
  public CheckFilter() {
  }
  public void init(FilterConfig filterConfig) throws ServletException {
    this.config = filterConfig;
  }
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    Enumeration params = request.getParameterNames();
    boolean rejected = false;
    while (params.hasMoreElements()) {
      if (isEmpty(request.getParameter((String) params.nextElement()))) {
        reject(request, response);
        rejected = true;
      }
    }
    if (!rejected)
      chain.doFilter(request, response);
  }// doFilter
  private boolean isEmpty(String param) {
    if (param == null || param.length() < 1) {
      return true;
    }
    return false;
  }
  private void reject(ServletRequest request, ServletResponse response)
      throws IOException, ServletException {
    request.setAttribute("errorMsg",
            "Please make sure to provide a valid value for all of the text fields.");
    Enumeration params = request.getParameterNames();
    String paramN = null;
    while (params.hasMoreElements()) {
      paramN = (String) params.nextElement();
      request.setAttribute(paramN, request.getParameter(paramN));
    }
    RequestDispatcher dispatcher = request
        .getRequestDispatcher("/form.jsp");
    dispatcher.forward(request, response);
  }
  public void destroy() {
    /*
     * called before the Filter instance is removed from service by the web
     * container
     */
  }
}





Compression Filter

 
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Implementation of <code>javax.servlet.Filter</code> used to compress
 * the ServletResponse if it is bigger than a threshold.
 *
 * @author Amy Roh
 * @author Dmitri Valdin
 * @version $Revision: 1.2 $, $Date: 2004/03/18 16:40:33 $
 */
public class CompressionFilter implements Filter{
    /**
     * The filter configuration object we are associated with.  If this value
     * is null, this filter instance is not currently configured.
     */
    private FilterConfig config = null;
    /**
     * Minimal reasonable threshold
     */
    private int minThreshold = 128;

    /**
     * The threshold number to compress
     */
    protected int compressionThreshold;
    /**
     * Debug level for this filter
     */
    private int debug = 0;
    /**
     * Place this filter into service.
     *
     * @param filterConfig The filter configuration object
     */
    public void init(FilterConfig filterConfig) {
        config = filterConfig;
        if (filterConfig != null) {
            String value = filterConfig.getInitParameter("debug");
            if (value!=null) {
                debug = Integer.parseInt(value);
            } else {
                debug = 0;
            }
            String str = filterConfig.getInitParameter("compressionThreshold");
            if (str!=null) {
                compressionThreshold = Integer.parseInt(str);
                if (compressionThreshold != 0 && compressionThreshold < minThreshold) {
                    if (debug > 0) {
                        System.out.println("compressionThreshold should be either 0 - no compression or >= " + minThreshold);
                        System.out.println("compressionThreshold set to " + minThreshold);
                    }
                    compressionThreshold = minThreshold;
                }
            } else {
                compressionThreshold = 0;
            }
        } else {
            compressionThreshold = 0;
        }
    }
    /**
    * Take this filter out of service.
    */
    public void destroy() {
        this.config = null;
    }
    /**
     * The <code>doFilter</code> method of the Filter is called by the container
     * each time a request/response pair is passed through the chain due
     * to a client request for a resource at the end of the chain.
     * The FilterChain passed into this method allows the Filter to pass on the
     * request and response to the next entity in the chain.<p>
     * This method first examines the request to check whether the client support
     * compression. <br>
     * It simply just pass the request and response if there is no support for
     * compression.<br>
     * If the compression support is available, it creates a
     * CompressionServletResponseWrapper object which compresses the content and
     * modifies the header if the content length is big enough.
     * It then invokes the next entity in the chain using the FilterChain object
     * (<code>chain.doFilter()</code>), <br>
     **/
    public void doFilter ( ServletRequest request, ServletResponse response,
                        FilterChain chain ) throws IOException, ServletException {
        if (debug > 0) {
            System.out.println("@doFilter");
        }
        if (compressionThreshold == 0) {
            if (debug > 0) {
                System.out.println("doFilter gets called, but compressionTreshold is set to 0 - no compression");
            }
            chain.doFilter(request, response);
            return;
        }
        boolean supportCompression = false;
        if (request instanceof HttpServletRequest) {
            if (debug > 1) {
                System.out.println("requestURI = " + ((HttpServletRequest)request).getRequestURI());
            }
            // Are we allowed to compress ?
            String s = (String) ((HttpServletRequest)request).getParameter("gzip");
            if ("false".equals(s)) {
                if (debug > 0) {
                    System.out.println("got parameter gzip=false --> don"t compress, just chain filter");
                }
                chain.doFilter(request, response);
                return;
            }
            Enumeration e =
                ((HttpServletRequest)request).getHeaders("Accept-Encoding");
            while (e.hasMoreElements()) {
                String name = (String)e.nextElement();
                if (name.indexOf("gzip") != -1) {
                    if (debug > 0) {
                        System.out.println("supports compression");
                    }
                    supportCompression = true;
                } else {
                    if (debug > 0) {
                        System.out.println("no support for compresion");
                    }
                }
            }
        }
        if (!supportCompression) {
            if (debug > 0) {
                System.out.println("doFilter gets called wo compression");
            }
            chain.doFilter(request, response);
            return;
        } else {
            if (response instanceof HttpServletResponse) {
                CompressionServletResponseWrapper wrappedResponse =
                    new CompressionServletResponseWrapper((HttpServletResponse)response);
                wrappedResponse.setDebugLevel(debug);
                wrappedResponse.setCompressionThreshold(compressionThreshold);
                if (debug > 0) {
                    System.out.println("doFilter gets called with compression");
                }
                try {
                    chain.doFilter(request, wrappedResponse);
                } finally {
                    wrappedResponse.finishResponse();
                }
                return;
            }
        }
    }
    /**
     * Set filter config
     * This function is equivalent to init. Required by Weblogic 6.1
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        init(filterConfig);
    }
    /**
     * Return filter config
     * Required by Weblogic 6.1
     */
    public FilterConfig getFilterConfig() {
        return config;
    }
}
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
/**
 * Very Simple test servlet to test compression filter
 * @author Amy Roh
 * @version $Revision: 1.2 $, $Date: 2004/03/18 16:40:33 $
 */
public class CompressionFilterTestServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("text/plain");
        Enumeration e = ((HttpServletRequest)request).getHeaders("Accept-Encoding");
        while (e.hasMoreElements()) {
            String name = (String)e.nextElement();
            out.println(name);
            if (name.indexOf("gzip") != -1) {
                out.println("gzip supported -- able to compress");
            }
            else {
                out.println("gzip not supported");
            }
        }

        out.println("Compression Filter Test Servlet");
        out.close();
    }
}





Filtering page to UTF-8

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UTF8 extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    try {
      BufferedReader reader = req.getReader();
      res.setContentType("text/html; charset=UTF-8");
      PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);
      // Read and write 4K chars at a time
      // (Far more efficient than reading and writing a line at a time)
      char[] buf = new char[4 * 1024]; // 4Kchar buffer
      int len;
      while ((len = reader.read(buf, 0, buf.length)) != -1) {
        out.write(buf, 0, len);
      }
      out.flush();
    } catch (Exception e) {
      getServletContext().log(e, "Problem filtering page to UTF-8");
    }
  }
}





Filter message string for characters that are sensitive in HTML

 
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
 * HTML filter utility.
 *
 * @author Craig R. McClanahan
 * @author Tim Tye
 * @version $Revision: 467217 $ $Date: 2006-10-24 05:14:34 +0200 (mar., 24 oct. 2006) $
 */
public final class HTMLFilter {

    /**
     * Filter the specified message string for characters that are sensitive
     * in HTML.  This avoids potential attacks caused by including JavaScript
     * codes in the request URL that is often reported in error messages.
     *
     * @param message The message string to be filtered
     */
    public static String filter(String message) {
        if (message == null)
            return (null);
        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
            case "<":
                result.append("&lt;");
                break;
            case ">":
                result.append("&gt;");
                break;
            case "&":
                result.append("&amp;");
                break;
            case """:
                result.append("&quot;");
                break;
            default:
                result.append(content[i]);
            }
        }
        return (result.toString());
    }

}





Filter that performs filtering based on comparing the appropriate request

 
/*
 * Copyright 2004 Matthew Moodie.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.apress.admin.filters;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import org.apache.regexp.RE;
import org.apache.regexp.RESyntaxException;
import javax.servlet.http.HttpServletRequest;
/**
 * Implementation of a filter that performs filtering based on comparing the
 * appropriate request property against a set of regular
 * expressions configured for this filter.
 * <p>
 * This filter is configured by setting the <code>allow</code> and/or
 * <code>deny</code> filter initialization parameters to a comma-delimited 
 * list of regular expressions (in the syntax supported by the jakarta-regexp 
 * library) in <code>web.xml</code> to which the appropriate request property 
 * will be compared.  Evaluation proceeds as follows:
 * <ul>
 * <li>The filter extracts the request property to be filtered.
 * <li>If there are any deny expressions configured, the property will
 *     be compared to each such expression.  If a match is found, this
 *     request will be forwarded to a blocked page (configured with the
 *     <code>blockPage</code> filter initialization parameter in 
 *     <code>web.xml</code>).</li>
 * <li>If there are any allow expressions configured, the property will
 *     be compared to each such expression.  If a match is found, this
 *     request will be allowed to pass through to the next filter in the
 *     current pipeline.</li>
 * <li>If one or more deny expressions was specified but no allow expressions,
 *     allow this request to pass through (because none of the deny
 *     expressions matched it).
 * <li>The request will be forwarded to a blocked page (configured with the
 *     <code>blockPage</code> filter initialization parameter in 
 *     <code>web.xml</code>).</li>
 * </ul>
 * <p>
 * This filter is based on, and is a modification of, the request 
 * interception mechanism provided by Tomcat"s remote request 
 * filter valves. Instead of returning a forbidden HTTP response,
 * it forwards the request to a custom blocked page.
 * 
 * In particular, it uses code from <code>org.apache.catalina.valves.RequestFilterValve</code>
 * to process a list of allowed and denied IP addresses and remote hosts, as well
 * as code to check the user"s details against this list. The difference in this
 * filter is that it doesn"t have implementing classes to differentiate between
 * IP addresses and remote hosts. It simply checks them all at once.
 *
 * @author Matthew Moodie
 * @version $Revision: 1.0 $ $Date: 2004/08/04 23:07:00 $
 */
public class RequestFilter implements Filter {
    // ----------------------------------------------------- Instance Variables

    /**
     * The comma-delimited set of <code>allow</code> expressions.
     */
    protected String allowedList = null;
    /**
     * The set of <code>allow</code> regular expressions we will evaluate.
     */
    protected RE allows[] = new RE[0];
    /**
     * The set of <code>deny</code> regular expressions we will evaluate.
     */
    protected RE denies[] = new RE[0];
    /**
     * The comma-delimited set of <code>deny</code> expressions.
     */
    protected String deniedList = null;
    /* The configuration associated with this filter */
    private FilterConfig config =  null;
    /* The page informing users that their request has been blocked */
    private String blockPage = "";
    /* The remote host and IP address of the client */
    private String host = null;
    private String ip = null; 
    /**
     * Initializes the filter at server startup.
     * Initialization consists of setting the list of allowed
     * and disallowed remote hosts and IP addresses.
     * @param _config The configuration associated with this filter
     *
     * @exception ServletException if there was a problem initializing this filter
     */
    public void init(FilterConfig _config)
      throws ServletException {
        this.config = _config;
        /* Get the initialization parameters as a string */
        allowedList = _config.getInitParameter("allow");
        deniedList = _config.getInitParameter("deny");
  blockPage = _config.getInitParameter("blockPage");
        /* Turn the lists into regular expression lists */
        allows = precalculate(allowedList);
        denies = precalculate(deniedList);
    }
    /**
     * Processes a request and blocks it as appropriate.
     * This method takes the list of allowed and disallowed
     * remote hosts and IP addresses and checks if the client"s
     * details match them.
     *
     * Some of the code in this method comes from <code>org.apache.catalina.valves.RequestFilterValve</code>.
     *
     * @param _req The request
     * @param _res The response
     * @param _chain The filter chain that this filter belongs to
     *
     * @exception IOException if there is a problem with the filter
     *  chain or the forward
     * @exception ServletException if there is a problem with the filter
     *  chain or the forward
     */
    public void doFilter(ServletRequest _req, ServletResponse _res,
        FilterChain _chain) throws IOException, ServletException {
        /* Get the type */
        if (_req instanceof HttpServletRequest) {
            host = _req.getRemoteHost();
            ip = _req.getRemoteAddr();
        }
        // Check the deny patterns, if any
        for (int i = 0; i < denies.length; i++) {
            if (denies[i].match(host) || denies[i].match(ip)) {
                if (_req instanceof HttpServletRequest) {
              config.getServletContext().getRequestDispatcher(blockPage).forward(_req, _res);
              return;
                }
            }
        }
        if(!(_res.isCommitted())){
            // Check the allow patterns, if any
            for (int i = 0; i < allows.length; i++) {
                if (allows[i].match(host) || allows[i].match(ip)) {
        _chain.doFilter(_req, _res);
        return;
                }
            }
        }
        if(!(_res.isCommitted())){
            // Allow if denies specified but not allows
            if ((denies.length > 0) && (allows.length == 0)) {
                _chain.doFilter(_req, _res);
                return;
            }
        }
       if(!(_res.isCommitted())){
           // Deny this request
           if (_req instanceof HttpServletRequest) {
        config.getServletContext().getRequestDispatcher(blockPage).forward(_req, _res);
           } 
       }
    }
  
    /**
     * Return an array of regular expression objects initialized from the
     * specified argument, which must be <code>null</code> or a comma-delimited
     * list of regular expression patterns.
     *
     * This method comes from <code>org.apache.catalina.valves.RequestFilterValve</code>.
     *
     * @param list The comma-separated list of patterns
     *
     * @exception IllegalArgumentException if one of the patterns has
     *  invalid syntax
     */
    protected RE[] precalculate(String list) {
        if (list == null)
            return (new RE[0]);
        list = list.trim();
        if (list.length() < 1)
            return (new RE[0]);
        list += ",";
        ArrayList reList = new ArrayList();
        while (list.length() > 0) {
            int comma = list.indexOf(",");
            if (comma < 0)
                break;
            String pattern = list.substring(0, comma).trim();
            try {
                reList.add(new RE(pattern));
            } catch (RESyntaxException e) {
                IllegalArgumentException iae = new IllegalArgumentException("Illegal pattern: " +  pattern);
                throw iae;
            }
            list = list.substring(comma + 1);
        }
        RE reArray[] = new RE[reList.size()];
        return ((RE[]) reList.toArray(reArray));
    }
    /**
     * Called when the filter is taken out of service at server shutdown.
     *
     */
    public void destroy() {
        config = null;
    }
}





Filter that wraps an HttpServletRequest to override "isUserInRole".

 
/*
 * $Id: SecurityWrappingFilter.java 637430 2008-03-15 15:38:35Z apetrelli $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
 * Filter that wraps an HttpServletRequest to override "isUserInRole".
 *
 * @version $Rev: 637430 $ $Date: 2008-03-15 16:38:35 +0100 (Sat, 15 Mar 2008) $
 */
public class SecurityWrappingFilter implements Filter {
    /**
     * The role that the current user is supposed to use.
     */
    public static final String GOOD_ROLE = "goodrole";
    /** {@inheritDoc} */
    public void init(FilterConfig filterConfig) throws ServletException {
        // No operation
    }
    /** {@inheritDoc} */
    public void doFilter(ServletRequest servletRequest,
            ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest wrappedRequest = new SecurityWrapperHttpServletRequest(
                (HttpServletRequest) servletRequest);
        filterChain.doFilter(wrappedRequest, servletResponse);
    }
    /** {@inheritDoc} */
    public void destroy() {
        // No operation
    }
    /**
     * Request wrapper that overrides "isUserInRole" method.
     *
     * @version $Rev: 637430 $ $Date: 2008-03-15 16:38:35 +0100 (Sat, 15 Mar 2008) $
     */
    private static class SecurityWrapperHttpServletRequest extends
            HttpServletRequestWrapper {
        /**
         * Constructor.
         *
         * @param request The HTTP servlet request.
         */
        public SecurityWrapperHttpServletRequest(HttpServletRequest request) {
            super(request);
        }
        /** {@inheritDoc} */
        @Override
        public boolean isUserInRole(String role) {
            return GOOD_ROLE.equals(role);
        }
    }
}





Filter Using Parameter

 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public final class FilterParameter implements Filter 
{
  private FilterConfig filterConfig = null;
  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException 
  {
    System.out.println("The message is: " + filterConfig.getInitParameter("message"));
    chain.doFilter(request, response);
  }
  public void destroy() { }
  public void init(FilterConfig filterConfig) {
    this.filterConfig = filterConfig;
  }
}





HTML filter utility

 
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
 * HTML filter utility.
 *
 * @author Craig R. McClanahan
 * @author Tim Tye
 * @version $Revision: 1.2 $ $Date: 2004/03/18 16:40:34 $
 */
public final class HTMLFilter {

    /**
     * Filter the specified message string for characters that are sensitive
     * in HTML.  This avoids potential attacks caused by including JavaScript
     * codes in the request URL that is often reported in error messages.
     *
     * @param message The message string to be filtered
     */
    public static String filter(String message) {
        if (message == null)
            return (null);
        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
            case "<":
                result.append("&lt;");
                break;
            case ">":
                result.append("&gt;");
                break;
            case "&":
                result.append("&amp;");
                break;
            case """:
                result.append("&quot;");
                break;
            default:
                result.append(content[i]);
            }
        }
        return (result.toString());
    }

}





IP Filter

 
import java.io.IOException;
import java.util.StringTokenizer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class IPFilter implements Filter {
  private FilterConfig config;
  public final static String IP_RANGE = "192.168";
  public IPFilter() {
  }
  public void init(FilterConfig filterConfig) throws ServletException {
    this.config = filterConfig;
  }
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    String ip = request.getRemoteAddr();
    HttpServletResponse httpResp = null;
    if (response instanceof HttpServletResponse)
      httpResp = (HttpServletResponse) response;
    StringTokenizer toke = new StringTokenizer(ip, ".");
    int dots = 0;
    String byte1 = "";
    String byte2 = "";
    String client = "";
    while (toke.hasMoreTokens()) {
      ++dots;
      //if we"ve reached the second dot, break and check out the indx
      // value
      if (dots == 1) {
        byte1 = toke.nextToken();
      } else {
        byte2 = toke.nextToken();
        break;
      }
    }//while
    //Piece together half of the client IP address so it can be compared
    // with
    //the forbidden range represented by IPFilter.IP_RANGE
    client = byte1 + "." + byte2;
    if (IP_RANGE.equals(client)) {
      httpResp.sendError(HttpServletResponse.SC_FORBIDDEN,
          "That means goodbye forever!");
    } else {
      chain.doFilter(request, response);
    }
  }// doFilter
  public void destroy() {
    /*
     * called before the Filter instance is removed from service by the web
     * container
     */
  }
}





Jsp Using Chained Filter

Parameter Filter

 
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
public class ParamSnoop implements Filter {
    
    private FilterConfig config;
    
    /** Creates new ParamSnoop */
    public ParamSnoop() {
    }
    
    public void  init(FilterConfig filterConfig)  throws ServletException{
    
        this.config = filterConfig;
    
    }
    
    public void  doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws java.io.IOException, ServletException {
    
      
        Map paramMap = request.getParameterMap();
        ServletContext context = config.getServletContext();
        /* use the ServletContext.log method to log 
        param names/values */
         context.log("doFilter called in: " + config.getFilterName() +  
          " on " + (new java.util.Date()));
        context.log("Snooping the parameters in request: " + 
            ((HttpServletRequest) request).getRequestURI());
            
         Iterator iter = paramMap.entrySet().iterator();
          while (iter.hasNext()){
             
             Map.Entry me = (Map.Entry) iter.next();
             context.log((String)me.getKey() + ": " + ((String[]) me.getValue())[0]);
          }
        chain.doFilter(request,response); 
    
    }
    
    public void destroy(){
        /*called before the Filter instance is removed 
        from service by the web container*/
    }
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
public class ParamSnoop implements Filter {
    
    private FilterConfig config;
    
    /** Creates new ParamSnoop */
    public ParamSnoop() {
    }
    
    public void  init(FilterConfig filterConfig)  throws ServletException{
    
        this.config = filterConfig;
    
    }
    
    public void  doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws java.io.IOException, ServletException {
    
      
        Map paramMap = request.getParameterMap();
        ServletContext context = config.getServletContext();
        /* use the ServletContext.log method to log 
        param names/values */
         context.log("doFilter called in: " + config.getFilterName() +  
          " on " + (new java.util.Date()));
        context.log("Snooping the parameters in request: " + 
            ((HttpServletRequest) request).getRequestURI());
            
         Iterator iter = paramMap.entrySet().iterator();
          while (iter.hasNext()){
             
             Map.Entry me = (Map.Entry) iter.next();
             context.log((String)me.getKey() + ": " + ((String[]) me.getValue())[0]);
          }
        chain.doFilter(request,response); 
    
    }
    
    public void destroy(){
        /*called before the Filter instance is removed 
        from service by the web container*/
    }
}





Request Filter

 

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class RequestFilter implements Filter {
  private FilterConfig config;
  /** Creates new RequestFilter */
  public RequestFilter() {
  }
  public void init(FilterConfig filterConfig) throws ServletException {
    this.config = filterConfig;
  }
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws java.io.IOException, ServletException {
    ReqWrapper wrapper = null;
    ServletContext context = null;
    if (request instanceof HttpServletRequest)
      wrapper = new ReqWrapper((HttpServletRequest) request);
    /*
     * use the ServletContext.log method to log param names/values
     */
    if (wrapper != null) {
      context = config.getServletContext();
      context.log("Query: " + wrapper.getQueryString());
    }
    //continue the request, response to next filter or servlet
    //destination
    if (wrapper != null)
      chain.doFilter(wrapper, response);
    else
      chain.doFilter(request, response);
  }
  public void destroy() {
    /*
     * called before the Filter instance is removed from service by the web
     * container
     */
  }
}





Response Filter

Restricting Filter

Send filter

 
package com.jexp;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class SendFilter implements Filter {
  private final static String PDF_DIR = "d:\\book\\jexp";
  private final static String PDF_CONTENT_TYPE = "application/pdf";
  private FilterConfig config;
  /** Creates new SessionFilter */
  public SendFilter() {
  }
  public void init(FilterConfig filterConfig) throws ServletException {
    System.out.println("Instance created of " + getClass().getName());
    this.config = filterConfig;
  }
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws java.io.IOException, ServletException {
    //get the file name from the "file" parameter
    String fileName = request.getParameter("file");
    if (fileName == null || fileName.equals(""))
      throw new ServletException(
          "Invalid or non-existent file parameter in SendPdf component.");
    if (fileName.indexOf(".pdf") == -1)
      fileName = fileName + ".pdf";
    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    HttpServletResponse httpResp = null;
    try {
      httpResp = (HttpServletResponse) response;
      stream = httpResp.getOutputStream();
      File pdf = new File(PDF_DIR + "/" + fileName);
      //set response headers
      httpResp.setContentType(PDF_CONTENT_TYPE);
      httpResp.addHeader("Content-Disposition", "attachment; filename="
          + fileName);
      httpResp.setContentLength((int) pdf.length());
      FileInputStream input = new FileInputStream(pdf);
      buf = new BufferedInputStream(input);
      int readBytes = 0;
      //read from the file; write to the ServletOutputStream
      while ((readBytes = buf.read()) != -1)
        stream.write(readBytes);
    } catch (Exception ioe) {
      //  throw new ServletException(ioe.getMessage());
      System.out.println(ioe.getMessage());
    } finally {
      if (buf != null)
        buf.close();
      if (stream != null) {
        stream.flush();
        //stream.close();
      }
    }//end finally
    chain.doFilter(request, httpResp);
  }
  public void destroy() {
    /*
     * called before the Filter instance is removed from service by the web
     * container
     */
  }
}





Servlets CSV Filter Demo

Servlets Post Filter Demo

Servlets SortFilter Demo