SoFunction
Updated on 2025-03-08

Recording of steps for configuring and using filters in Servlets

Configuring and using filters in Servlets mainly includes creating filter classes, configuring filters, and using filters in web applications. The following are the specific contents:

Create a filter class

  • The filter class needs to be implementedand rewrite the interfaceinitdoFilteranddestroymethod.
    • initMethods are used to initialize filters and are called when the server starts. They are usually used to load configuration files, initialize resources, and other operations.
    • doFilterMethods are the core method of filters, used to implement specific filtering logic, and process each request and response entering the filter chain.
    • destroyThe method is called when the server is shut down and is used to free the resources occupied by the filter.

Here is a simple filter class example for uniformly setting the character encoding of requests and responses to UTF-8:

import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class CharacterEncodingFilter implements Filter {

    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Get the configured character encoding from it, if there is no configuration, use the default UTF-8        encoding = ("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // Set the requested character encoding        (encoding);
        // Set the character encoding of the response        ("text/html;charset=" + encoding);
        // Pass the request to the next filter or Servlet        (request, response);
    }

    @Override
    public void destroy() {
        // Release resources, there is no resource that needs to be released here, so it is an empty method    }
}

Configure filters

  • Annotation method (Servlet 3.0 and above): Used on filter class@WebFilterAnnotation to configure filters. You can specify the filtering attributes such as URL pattern, filter name, etc.
import ;
import ;

@WebFilter(filterName = "CharacterEncodingFilter", urlPatterns = "/*")
public class CharacterEncodingFilter implements Filter {
    // Implementation code of filter class}

In the above code,@WebFilterThe annotation willCharacterEncodingFilterFilters map to all URL paths (/*) , that is, all requests in the web application are filtered.

  • Configuration method:existUse in the file<filter>and<filter-mapping>Tags to configure filters.
&lt;web-app&gt;
    &lt;!-- Filter definition --&gt;
    &lt;filter&gt;
        &lt;filter-name&gt;CharacterEncodingFilter&lt;/filter-name&gt;
        &lt;filter-class&gt;&lt;/filter-class&gt;
        &lt;!-- Filter initialization parameters --&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;encoding&lt;/param-name&gt;
            &lt;param-value&gt;UTF-8&lt;/param-value&gt;
        &lt;/init-param&gt;
    &lt;/filter&gt;

    &lt;!-- Filter Mapping --&gt;
    &lt;filter-mapping&gt;
        &lt;filter-name&gt;CharacterEncodingFilter&lt;/filter-name&gt;
        &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
    &lt;/filter-mapping&gt;
&lt;/web-app&gt;

In the above configuration,<filter>The tag defines the filter name, class name, and initialization parameters.<filter-mapping>The tag maps the filter name to the URL pattern, and all paths are filtered here.

Using filters

  • When the client sends a request to the server, the request will first enter the filter chain. If the requested URL matches the map path of the filter, the corresponding filter will be executed. The filter can preprocess the request, such as verifying the user's login status, checking the request parameters, etc. If the request passes the filter's verification, it will be passed to the next filter or target Servlet for processing. After the servlet has processed the request and generated a response, the response will be forwarded along the filter chain. The filter can post-process the response, such as modifying the response header, compressing the response data, etc.

Assume that there are multiple servlets in a web application, when the above character encoding filter is configured, all character encodings for requests and responses to access the web application will be set to UTF-8, ensuring the correct processing of data during transmission and avoiding the problem of garbled code.

Summarize

This is the end of this article about configuring and using filters in Servlets. For more related Servlet configuration and using filters, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!