SoFunction
Updated on 2025-03-10

jsp filter function and simple usage examples

This article describes the functions and simple usage of jsp filter. Share it for your reference, as follows:

What is the function of a filter?

Filters can dynamically intercept requests and responses to transform or use information contained in the request or response.

One or more filters can be attached to a Servlet or a group of Servlets. Filters can also be attached to JavaServer Pages (JSP) files and HTML pages.

  • Intercept the client's requests before accessing the backend resource.
  • Process these responses before the server's response is sent back to the client.

The filter implementation needs to implement this interface class

A simple filter class example

package demo;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class DemoFilter implements Filter
{
  private String name=null;
  @Override
  public void destroy()
  {
  }
  @Override
  public void doFilter(ServletRequest arg0, ServletResponse arg1,
      FilterChain arg2) throws IOException, ServletException
  {
    ("name", "init text string : " + name);
    (arg0, arg1);
  }
  @Override
  public void init(FilterConfig arg0) throws ServletException
  {
    //Get the configuration in filter init-param    name = ("name");
  }
}

Just writing this filter class is not OK. We want to declare which requests require filter calls

  <!--Declare afilter-->
  <filter>
  <!--filterName of-->
    <filter-name>demoFilter</filter-name>
  <!--filter kind-->
    <filter-class></filter-class>
  <!--Shouldfilterkind需要的配置-->
    <init-param>
      <param-name>name</param-name>
      <param-value>my name is tanyong</param-value>
    </init-param>
  </filter>

  <!--forurl-pattern Matched inurlLink Map to correspondingfilter filter pass filter-nameTo identify-->
  <filter-mapping>
    <filter-name>demoFilter</filter-name>
    <!--Match mapping rules,I'm using all requests heredemoFilter filter Go around inside-->
    <url-pattern>/*</url-pattern>
  </filter-mapping>

I hope this article will be helpful to everyone's jsp programming.