Tomcat ServletFilter to reject request based on query parameter

This is useful if you have a web application developed by someone else. You want to restrict certain features, but you do not have access to the source code.

In this article I am giving the source code for a ServletFilter to reject all requests containing a specific query parameter that you can specify in the web.xml file.

The example works with Apache Tomcat 7.

First we need a JSP file in the application, so we can see it work:


<?xml version="1.0" encoding="ISO-8859-1" ?>  
<jsp:root xmlns:jsp="" version="2.0">  
    < contentType="text/html; charset=ISO-8859-1" 
        pageEncoding="ISO-8859-1" session="false"/>
    <jsp:output doctype-root-element="html"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
        omit-xml-declaration="true" />
<html xmlns="">  
    <p>You came through</p>

In the web.xml file you have to specify the filter. Notice how we are indicating the unwanted query parameter in the init-param element.


<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="" xmlns="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">  
      <filter-name>PDF Filter</filter-name>
      <filter-name>PDF Filter</filter-name>

Here is the filter code. The query-parameter value is picked up from the web.xml file in the init method.

In the doFilter method the parameters are compared one by one to the query-parameter value. If a match is found, HTTP error code 403 is sent in the response using the sendError method of the HttpServletResponse class. The HttpServletResponse.SC_FORBIDDEN value is 403.

package com.fourthex.web;

import java.util.Collections;  
import java.util.List;

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 QueryParamFilter implements Filter {

    private String queryParameter;

    public QueryParamFilter() {

    public void destroy() {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse)response;
        List<String> parameters = Collections.list(request.getParameterNames());
        for(String parameter: parameters) {
            if(parameter.equalsIgnoreCase(this.queryParameter)) {
                        , String.format("Does not allow query parameter: %s", this.queryParameter));
        chain.doFilter(request, response);

    public void init(FilterConfig config) throws ServletException {
        this.queryParameter = config.getInitParameter("query-parameter");


Here are a few screenshots of the filter in action:
Filter rejecting

Filter not rejecting