【web-Filter】Use of filters

Filter Technology in WEB

Filter, also known as filter , is the most exciting technology in Servlet technology. Through Filter technology, WEB developers can intercept all web resources managed by the web server: such as Jsp, Servlet, static image files or static html files, etc. , so as to achieve some special functions. For example, it implements some advanced functions such as URL-level permission access control, filtering sensitive words, and compressing response information.


Filter development is divided into two steps:

1. Write a java class to implement the Filter interface and implement its doFilter method.
2. Register the filter class written with and element in the web.xml file, and set the resources it can intercept.

<java>
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;

/**
 *
 * @author 
 * @data 
 * @version 1.0
 * @See功能介绍 :解析字符编码
 */
public class CharEncodingFilter implements Filter {

    private FilterConfig config = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if ("get".equalsIgnoreCase(httpRequest.getMethod())) {
            System.out.println("get请求");
            GetHttpServletRequest wrapper = new GetHttpServletRequest(httpRequest, "UTF-8");
            System.out.println("----请求被" + this.config.getFilterName() + "过滤----");
            chain.doFilter(wrapper, response);
            System.out.println("----响应被" + this.config.getFilterName() + "过滤----");
        } else {
            System.out.println("post请求");
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            System.out.println("----请求被" + this.config.getFilterName() + "过滤----");
            //执行下一个过滤器(如果有的话,否则执行目标servlet)  
            chain.doFilter(request, response);
            System.out.println("----响应被" + this.config.getFilterName() + "过滤----");
        }

    }

    @Override
    public void destroy() {
        System.out.println(this.config.getFilterName() + "被销毁");
        this.config = null;
    }

}
//定义GetHttpServletRequest类
class GetHttpServletRequest extends HttpServletRequestWrapper {

    private String encoding;

    public GetHttpServletRequest(HttpServletRequest request) {
        super(request);
    }

    public GetHttpServletRequest(HttpServletRequest request, String encoding) {
        super(request);
        this.encoding = encoding;
    }

    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if (null != value) {
            try {
                // tomcat默认以ISO8859-1处理GET传来的参数。把tomcat上的值用ISO8859-1获取字节流,再转换成UTF-8字符串 
                value = new String(value.getBytes("ISO8859-1"), encoding);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return value;
    }
}

</java>

2. Deployment of Filter

The deployment of the Filter is divided into two steps:
1. Registering
the Filter After the Filter is developed, it needs to be registered in the web.xml file so that it can be called by the web server. Register the Filter example
in the web.xml file:

    <filter>
       <description>FilterDemo02过滤器</description>
       <filter-name>FilterDemo02</filter-name>
       <filterclass>com.mis.filter.FilterDemo02</filter-class>
        <!--配置FilterDemo02过滤器的初始化参数-->
        <init-param>
        <description>配置FilterDemo02过滤器的初始化参数</description>
        <param-name>name</param-name>
        <param-value>gacl</param-value>
        </init-param>
        <init-param>
        <description>配置FilterDemo02过滤器的初始化参数</description>
        <param-name>like</param-name>
        <param-value>java</param-value>
        </init-param>
    </filter>

<description>It is used to add description information. The content of this element can be empty <description>or not configured.
Used to specify a name for the filter, the content of this element cannot be empty.
Element is used to specify the fully qualified class name of the filter.
The element is used to specify initialization parameters for the filter, and its child elements specify the name of the parameter and the value of the parameter. In a filter, you can use the FilterConfig interface object to access initialization parameters. If the filter does not need to specify initialization parameters, then the element can be left unconfigured.

2. Mapping Filter
After the Filter is registered in the web.xml file, the Filter must be mapped in the web.xml file

<!--映射过滤器-->
<filter-mapping>
    <filter-name>FilterDemo02</filter-name>
    <!--“/*”表示拦截所有的请求 -->
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>Elements are used to set the resources that a Filter is responsible for intercepting. The resource intercepted by a Filter can be specified in two ways: the servlet name and the request path for resource access. The
sub- element is used to set the registered name of the filter. The value must be the name of the filter declared in the element.
Set the request path intercepted by filter (the URL pattern associated with the
filter) to specify the name of the servlet intercepted by the filter.
Specifies the way the resource intercepted by the filter is called by the servlet container, which can be one of REQUEST, INCLUDE, FORWARD and ERROR. The default is REQUEST. Users can set multiple sub-elements to specify Filter to intercept multiple invocations of resources. as follows:

<filter-mapping>
   <filter-name>testFilter</filter-name>
   <url-pattern>/index.jsp</url-pattern>
   <dispatcher>REQUEST</dispatcher>
   <dispatcher>FORWARD</dispatcher>
</filter-mapping>

Values ​​that can be set on child elements and their meanings:
- REQUEST: When the user directly accesses the page, the web container will invoke the filter. If the target resource is accessed through the RequestDispatcher's include() or forward() methods, this filter will not be called. - INCLUDE: If the target resource is accessed through RequestDispatcher's include() method, then this filter will be called. Other than that, the filter will not be called.
- FORWARD: If the target resource is accessed through the forward() method of the RequestDispatcher, the filter will be called, otherwise, the filter will not be called.
- ERROR: This filter will be invoked if the target resource is invoked through the declarative exception handling mechanism. Other than that, the filter will not be called.

Guess you like

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