JavaWeb study notes eight: filter

Filter Filter

The filter is to filter the resources accessed by the client. If the conditions are met, it will be released, and if the conditions are not met, it will not be released. It can also perform logical processing on the target resources before and after accessing them.

step:

  1. Write a filter class that implements the Filter interface
  2. Implement methods that have not been implemented in the interface (focus on implementing the doFilter method)
  3. Configure in web.xml (mainly configure which resources to filter)

Example, filter implementation class:

package com.yyb.filter;

import java.io.IOException;
import javax.servlet.*;

/**
 * Created by Administrator on 2017/7/28.
 */
public class FilterDemo implements Filter {
    
    
    @Override
    //Filter创建的时候执行init方法
    public void init(FilterConfig filterConfig) throws ServletException {
    
    
        //1、获得web.xml中filter 的名称<filter-name>FilterDemo</filter-name>
        System.out.println(filterConfig.getFilterName());
        //2、获得当前filter的初始化参数
        System.out.println(filterConfig.getInitParameter("aaa"));
        //3、获得servletContext
        filterConfig.getServletContext();

        System.out.println("init ....");
    }

    @Override
    //doFilter是Filter的核心过滤的方法
    /*
     * request: 内部封装是客户端http请求的内容
     * response: 代表是响应
     * FilterChain: 过滤器链对象
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
    
    

        System.out.println("quick1 running....");
        //放行请求
        chain.doFilter(request, response);
    }

    @Override
    //Filter对象销毁的时候执行destory方法
    public void destroy() {
    
    
        System.out.println("destroy...");
    }
}

web.xml

<filter>
        <filter-name>FilterDemo</filter-name>
        <filter-class>com.yyb.filter.FilterDemo</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FilterDemo</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Detailed API of Filter

The filter lifecycle and its lifecycle-related methods, the Filter interface has three methods, and these three are all methods related to the life of the Filter:

  • init(Filterconfig): Represents the filter object initialization method, which is executed when the filter object is created.
  • doFilter(ServletRequest,ServletResponse,FilterCha): represents the core method of filter to perform filtering. If a resource has been configured to this filter for filtering, the doFilter method will be executed every time the resource is accessed.
  • destroy(): represents the filter destruction method, which is executed when the filter object is destroyed.

The life cycle of the Filter object

  • When the Filter is created: the filter object is created when the server starts
  • When the Filter is destroyed: the filter is destroyed when the server is closed
    init(FilterConfig): the parameter config represents the object of the configuration information of the Filter object, and the internal package is the configuration information of the filter.

destroy() method: Executed when the filter object is destroyed.

The doFilter method: doFilter(ServletRequest, ServletResponse, FilterChain), the parameter ServletRequest/ServletResponse is that the web container is responsible for creating a request and a response object as the parameters of the doFilter every time the doFilter method is executed. The request and response are the request and response when accessing the service method of the target resource. FilterChain is a filter chain object, and the request can be released through the doFilter method of the object. The chain object executes filters sequentially according to the configured filter-mapping order.
insert image description here

<filter>
        <filter-name>FilterDemo</filter-name>
        <filter-class>com.yyb.filter.FilterDemo</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FilterDemo</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

url-pattern configuration

  • Exactly match
        /Servlet1, execute only when accessing Servlet1

  • Directory matching /aaa/bbb/*
    /user/ : Access to resources in the foreground enter this filter
    /admin/
    : Execute this filter when accessing resources in the background

  • The extension matches *.abc *.jsp

Note: url-pattern can be replaced by servlet-name or mixed.

<filter-mapping>
        <filter-name>FilterDemo</filter-name>
        <!--<url-pattern>/*</url-pattern>-->
        <servlet-name>FilterTest</servlet-name>
        <servlet-name>FilterTest1</servlet-name>
    </filter-mapping>

dispatcher: the way of access

  • REQUEST: The default value, which means to execute filter when directly accessing a resource
  • FORWARD: execute filter only when forwarding
  • INCLUDE: Execute filter when resources are included
  • ERROR: Execute filter when jumping when an error occurs

Example: web.xml

  <filter>
        <filter-name>FilterDemo</filter-name>
        <filter-class>com.yyb.filter.FilterDemo</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FilterDemo</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

In FilterTest, add forwarding code request.getRequestDispatcher("/index.jsp").forward(request, response);. At this time, when FilterTest is accessed, the filter will only be executed in sequence instead of twice. Filters are not executed when forwarding.

But the redirection will be executed twice. In FilterTest, add the forwarding code response.sendRedirect(request.getContextPath()+"/index.jsp");, and you can see the execution result.

The role of Filter

  • Extraction of public code
  • Methods in request and response can be enhanced (decorator mode/dynamic proxy)
  • Perform permission control

Use filter to solve parameter Chinese garbled characters

package com.ithiema.web.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class EncodingFilter implements Filter{
    
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
    
    
        
        //request.setCharacterEncoding("UTF-8");
        
        //在传递request之前对request的getParameter方法进行增强
        /*
         * 装饰者模式(包装)
         * 
         * 1、增强类与被增强的类要实现统一接口
         * 2、在增强类中传入被增强的类
         * 3、需要增强的方法重写 不需要增强的方法调用被增强对象的
         * 
         */
        
        //被增强的对象
        HttpServletRequest req = (HttpServletRequest) request;
        //增强对象
        EnhanceRequest enhanceRequest = new EnhanceRequest(req);
        chain.doFilter(enhanceRequest, response);
    }

    @Override
    public void destroy() {
    
    
    }
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    
    }

}

class EnhanceRequest extends HttpServletRequestWrapper{
    
    
    private HttpServletRequest request;
    public EnhanceRequest(HttpServletRequest request) {
    
    
        super(request);
        this.request = request;
    }
    
    //对getParaameter增强
    @Override
    public String getParameter(String name) {
    
    
        String parameter = request.getParameter(name);//乱码
        try {
    
    
            parameter = new String(parameter.getBytes("iso8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
    
    
            e.printStackTrace();
        }
        return parameter;
    }
}

Guess you like

Origin blog.csdn.net/weixin_42838061/article/details/121198500