import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;

// This is a simple filter that removes extra spaces before and after
// all items in a request.

public class TrimFilter implements Filter {

  // Since this is an interface, we must implement bothe the init
  // and destroy methods.
  public void init(FilterConfig config) {}
  public void destroy() {}

  public void doFilter(ServletRequest request, 
                       ServletResponse response,
                       FilterChain chain) 
                       throws ServletException, IOException {
 
    // To make this general purpose, we just get all of the
    // parameters passed.

    Enumeration parameters = request.getParameterNames();

    while (parameters.hasMoreElements()) {

      // Get the next parameter passed and its corresponding value
      String parameterName = (String)parameters.nextElement();
      String parameterValue = (String)request.getParameter(parameterName);

      // Trim the parameter value
      parameterValue = parameterValue.trim();

      // Change the value of the attribute in the request to the 
      // trimmed string. Note that the servlet must retrieve this
      // using the getAttribute method rather than the getParameter
      // method.
      request.setAttribute(parameterName, parameterValue);
      }
 
    // Pass the request on to the next element (either the servlet or
    // another filter).
    chain.doFilter(request, response);
    }
  }
