JavaWeb filter (Filter)

1. Introduction to the filter:

  Filter is the most commonly used technology in JavaWeb. It is often used for URL access control, encoding conversion, error page jumping, intercepting and filtering pictures, html files, and specifying text.

Second, how the filter works:

  Rough process : When the client sends a request, that is, before the HttpServletRequest or HttpServletResponse reaches the Servlet, the Filter will intercept it, check the data and filter it accordingly, and then release or jump accordingly, and then generate When the response is returned, the Filter again finalizes the server's response and reaches the view layer, in general: Request -> Filter -> Response -> Filter -> Display . In a web application, multiple Filters can be developed and written, and these Filters are combined and called a Filter chain . The web server decides which Filter to call first according to the registration order of the Filter in the web.xml file. If the annotation method is used to register, the execution order should be the order of the first letter of the file name of the filter . When the first Filter's doFilter method is called, the web server creates a FilterChain object representing the Filter chain and passes it to the method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the web server will check whether there is a filter in the FilterChain object, if so, call the second filter, if not, call the target resource.

  Life cycle : There are three methods to be implemented in the Filter interface implementation class: the init method, the doFilter method, and the destroy method.

  (1) init(FilterConfig):

    Initialization interface, Filter initialization is called when the web server starts. It has the same function as the init method of Servlet. FilterConfig can get the initialization parameters of the container and some corresponding data.

1 String getFilterName(); // Get the name of the filter. 
2 String getInitParameter(String name); // Returns the value of the initialization parameter with the name specified in the deployment description. Returns null if it does not exist. 
3 Enumeration getInitParameterNames(); // Returns an enumeration set of names of all initialization parameters of the filter. 
4  public ServletContext getServletContext(); // Returns a reference to the Servlet context object.

  (2) doFilter(ServletRequest, ServletResponse, FilterChain):

    This method will be called when each user's request comes in. This method will be called before the servlet's service method and is the main body of the filter. FilterChain represents the entire current request chain. By calling FilterChain.doFilter, the request can be passed on. How to intercept this request, as long as this method is not called, the request will be returned directly. So Filter is a chain of responsibility design pattern. doFilter can do it: let a piece of code execute before calling the target resource. Whether to call the target resource (that is, whether to let the user access the web resource). When the web server calls the doFilter method, it will pass in a filterChain object. The filterChain object is the most important object in the filter interface. It also provides a doFilter method. Developers can decide whether to call this method according to their needs. Then the web server will call the service method of the web resource, that is, the web resource will be accessed, otherwise the web resource will not be accessed.

  (3) destroy

    After the Filter object is created, it will reside in memory and will be destroyed when the web application is removed or the server is stopped. When the Filter object is destroyed, this method is called. It is worth noting that there will be a filter based on the response mentioned above, so when the web container calls this method, the container will call the doFilter method again.

3. Simple example:

  Here we use the new annotation method of Servlet3.0 to replace the previously used xml configuration:

  

package Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*", //对所有url进行过滤
        initParams = {@WebInitParam(name = "url", value = "index.jsp;LoginServlet;error.jsp"), @WebInitParam(name = "encoding", value = "UTF-8")})
public class LoginFilter implements Filter {
    private FilterConfig config = null;

    public void destroy() {
        config = null;
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;

        // Encoding conversion filter 
        String charset = config.getInitParameter("encoding" );
        request.setCharacterEncoding(charset);
        response.setCharacterEncoding(charset);

        // Do not filter the login page and the specified page 
        String url = config.getInitParameter("url" );
        String[] urlList = url.split(";");
        for (String urlFilt : urlList) {
            if (request.getRequestURI().indexOf(urlFilt) != -1) {
                chain.doFilter(req, resp);
                return;
            }
        }

        // Determine whether the user is logged in 
        if (request.getSession().getAttribute("username") != null ) {
            chain.doFilter(req, resp);
        } else {
            response.sendRedirect("../index.jsp");
        }
    }

    public  void init(FilterConfig config) throws ServletException {
         this .config = config;   // Get initialization parameters 
    }

}

 

 

Some knowledge sources: https://www.cnblogs.com/coderland/p/5902878.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324930578&siteId=291194637