The concept and structure of Servlet Filter

Source: Internet
Author: User

What does Servlet filter mean? What is the structure of the Servlet filter? What is implementation? To start our explanation:

1. What is a Servlet filter?

Servlet filters are small Web Components that intercept requests and responses to view, extract, or operate in some way the data being exchanged between the client and the server. Filters are Web Components that typically encapsulate some functions. These functions are important but not decisive for processing client requests or sending responses. Typical examples include recording data about requests and responses, processing security protocols, and managing session attributes. Filters provide an object-oriented modularization mechanism to encapsulate common tasks into pluggable components that are declared in a configuration file and processed dynamically.

Servlet filters combine many elements to make filters unique, powerful, and modular Web components. That is to say, the Servlet filter is:

◆ Declarative: the filter is declared using the xml tag in the Web deployment descriptor web. XML. This allows you to add and delete filters without modifying any application code or JSP pages.

◆ Dynamic: The Servlet container calls the filter at runtime to intercept and process requests and responses.

◆ Flexible: filters are widely used in Web processing environments and cover many of the most common auxiliary tasks, such as logging and security. Filters are flexible because they can be used to perform preprocessing and post-processing for Direct calls from clients and to process requests scheduled between Web components after the firewall. Finally, you can link the filter to provide the required functions.

◆ Modular: By encapsulating the application processing logic into a single class file, the filter defines modular units that can be easily added or deleted from the request/response chain.

◆ Portable: Like many other aspects of the Java platform, Servlet filters are portable across platforms and containers, further supporting the modularization and reusable nature of Servler filters.

◆ Reusable: thanks to the modular design of the filter implementation class and declarative filter configuration methods, filters can be easily used across different projects and applications.

◆ Transparent: A filter is included in the request/response chain, which is designed to supplement rather than replace in any way) core processing provided by servlet or JSP pages. Therefore, the filter can be added or deleted as needed without damaging the servlet or JSP page.

2. Servlet filter architecture

As its name implies, the Servlet filter is used to intercept incoming requests and/or outgoing responses and monitor, modify, or process the data streams being passed in some way. Filters are self-contained and modular components that can be added to the request/response chain or deleted without affecting other Web Components in the application. Filters are only used to modify the runtime processing of requests and responses. Therefore, they should not be directly embedded into the Web application framework, unless they are implemented through standard interfaces well defined in Servlet APIs.

Web resources can be configured as not associated with a filter, which is the default condition), associated with a single filter, which is a typical case), or even associated with a filter chain. So what exactly does the filter do? Like servlet, it accepts requests and responds to objects. The filter then checks the request object and decides to forward the request to the next component in the chain, or abort the request and send a response directly to the client. If the request is forwarded, it will be passed to another resource filter, servlet, or JSP page in the chain ). After the request is processed by the server through the filter chain, a response will be sent back through the chain in reverse order. This gives each filter the opportunity to process the response object as needed.

When filters are first introduced in the Servlet 2.3 specification, they can only filter content between the Web Client and the specified Web Resource accessed by the client. If the resource then schedules the request to other Web resources, you cannot apply the filter to any requests entrusted by the background. 2.4 The specification eliminates this restriction. Servlet filters can now be applied anywhere in the J2EE Web environment where request and response objects exist. Therefore, the Servlet filter can be applied between the client and servlet, between servlet and servlet or JSP pages, and between each included JSP page. This is what I call powerful capabilities and flexibility!

3. Compile the Servlet Filter Implementation class Program

The filter API contains three simple interfaces which are neatly nested in the javax. servlet package. The three interfaces are Filter, FilterChain, and FilterConfig. From the programming point of view, the Filter class will implement the Filter interface, and then use the FilterChain and FilterConfig interfaces in this Filter class. A reference to the filter class is passed to the FilterChain object, allowing the filter to pass control to the next resource in the chain. The FilterConfig object is provided to the filter by the container to allow access to the initialization data of the filter.

To be consistent with our three-step mode, the Filter must use three methods to fully implement the Filter interface:

Init (): This method is called when the container instantiates a filter. It is mainly designed to prepare the filter for processing. This method accepts an object of the FilterConfig type as input.

DoFilter (): Like servlet's method of having a service () method and calling doPost () or doGet () to process requests, does the filter have a single method used to process requests and responses? D? D doFilter (). This method accepts three input parameters: A ServletRequest, response, and a FilterChain object.

Destroy (): As you imagine, this method performs any cleanup operations that may need to be performed before automatic garbage collection.

 
 
  1. SessionFilter.java  
  2. package net.pms.web.filter;  
  3.  
  4. import java.io.IOException;  
  5.  
  6. import javax.servlet.Filter;  
  7. import javax.servlet.FilterChain;  
  8. import javax.servlet.FilterConfig;  
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.ServletRequest;  
  11. import javax.servlet.ServletResponse;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14. import javax.servlet.http.HttpServletResponseWrapper;  
  15.  
  16. /**  
  17. * @author jfish  
  18. * @since 2006.1.12  
  19. */  
  20. public class SessionFilter implements Filter {  
  21.  
  22.      public static boolean isContains(String container, String[] regx) {  
  23.            boolean result = false;  
  24.  
  25.            for (int i = 0; i ﹤ regx.length; i++) {  
  26.                  if (container.indexOf(regx[i]) != -1) {  
  27.                        return true;  
  28.                  }  
  29.            }  
  30.            return result;  
  31.      }  
  32.  
  33.      public FilterConfig config;  
  34.  
  35.      public void setFilterConfig(FilterConfig config) {  
  36.            this.config = config;  
  37.      }  
  38.  
  39.      public FilterConfig getFilterConfig() {  
  40.            return config;  
  41.      }  
  42.  
  43.      public void doFilter(ServletRequest request, ServletResponse response,  
  44.                  FilterChain chain) throws IOException, ServletException {  
  45.  
  46.            HttpServletRequest httpreq = (HttpServletRequest) request;  
  47.            HttpServletResponse httpres = (HttpServletResponse) response;  
  48.  
  49.            HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(  
  50.                        (HttpServletResponse) response);  
  51.            String logonStrings = config.getInitParameter("logonStrings");  
  52.            String includeStrings = config.getInitParameter("includeStrings");  
  53.            String redirectPath = httpreq.getContextPath()  
  54.                        + config.getInitParameter("redirectPath");  
  55.            String disabletestfilter = config.getInitParameter("disabletestfilter");  
  56.  
  57.            if (disabletestfilter.toUpperCase().equals("Y")) {  
  58.                  chain.doFilter(request, response);  
  59.                  return;  
  60.            }  
  61.            String[] logonList = logonStrings.split(";");  
  62.            String[] includeList = includeStrings.split(";");  
  63.            Object user = httpreq.getSession().getAttribute("userinfo");  
  64.            if (user == null) {  
  65.                  if (!this.isContains(httpreq.getRequestURI(), includeList)) {  
  66.                        chain.doFilter(request, response);  
  67.                        return;  
  68.                  }  
  69.                  if (this.isContains(httpreq.getRequestURI(), logonList)) {  
  70.                        chain.doFilter(request, response);  
  71.                        return;  
  72.                  }  
  73.                  wrapper.sendRedirect(redirectPath);  
  74.  
  75.            } else {  
  76.                  chain.doFilter(request, response);  
  77.            }  
  78.      }  
  79.  
  80.      public void destroy() {  
  81.            this.config = null;  
  82.      }  
  83.  
  84.      public void init(FilterConfig filterConfig) throws ServletException {  
  85.            this.config = filterConfig;  
  86.      }  

4. Configure the Servlet Filter

In web. xml:

 
 
  1.   ﹤filter﹥  
  2.      ﹤filter-name﹥SessionFilter﹤/filter-name﹥  
  3.      ﹤filter-class﹥net.pms.web.filter.SessionFilter﹤/filter-class﹥  
  4.      ﹤init-param﹥  
  5.            ﹤param-name﹥logonStrings﹤/param-name﹥  
  6.            ﹤param-value﹥login.jsp﹤/param-value﹥  
  7.      ﹤/init-param﹥  
  8.      ﹤init-param﹥  
  9.            ﹤param-name﹥includeStrings﹤/param-name﹥  
  10.            ﹤param-value﹥.jsp;.html﹤/param-value﹥  
  11.      ﹤/init-param﹥  
  12.      ﹤init-param﹥  
  13.            ﹤param-name﹥redirectPath﹤/param-name﹥  
  14.            ﹤param-value﹥/login.jsp﹤/param-value﹥  
  15.      ﹤/init-param﹥  
  16.      ﹤init-param﹥  
  17.            ﹤param-name﹥disabletestfilter﹤/param-name﹥  
  18.            ﹤param-value﹥N﹤/param-value﹥  
  19.      ﹤/init-param﹥  
  20. /filter﹥  
  21. ﹤filter-mapping﹥  
  22.      ﹤filter-name﹥SessionFilter﹤/filter-name﹥  
  23.      ﹤url-pattern﹥/*﹤/url-pattern﹥  
  24. /filter-mapping﹥ 

The logonStrings parameter is displayed on the logon page.

Descridestrings: Filter page Parameters

RedirectPath, No Logon page

Disabletestfilter: whether the Servlet filter is valid.

  1. Servlet and JSP paths
  2. Servlet Lifecycle
  3. Analysis of form data in JSP Servlet Technology
  4. At the beginning of JSP Servlet Development
  5. Java Servlet API documentation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.