1、

filter过滤器是servlet JAR包里面的接口,继承该接口即可实现过滤器,并在web.xml中加载该filter

2、

filter有三个方法

public abstract void init(FilterConfig paramFilterConfig) throws ServletException;
public abstract void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse,FilterChain paramFilterChain) throws IOException, ServletException;
public abstract void destroy();

初始化init里面会初赋值FilterConfig,destroy做清理
FilterConfig有四个方法

public abstract String getFilterName();
public abstract ServletContext getServletContext();
public abstract String getInitParameter(String paramString);
public abstract Enumeration<String> getInitParameterNames();

其中的initParameter在web.xml配置filter的时候配置

3、

web.xml中代码示例

<filter>
  <filter-name>firstFilter</filter-name>
  <filter-class>com.filter.FirstFilter</filter-class>
  <init-param>
  <param-name>includeStrings</param-name>
  <param-value>.do;.jsp</param-value>
  </init-param>
  <init-param>
  <param-name>redirectPath</param-name>
  <param-value>/index.jsp</param-value>
  </init-param>
  </filter>
  <filter-mapping>
  <filter-name>firstFilter</filter-name>
  <url-pattern>*</url-pattern>
  </filter-mapping>

4、

Filter实现类示例:

package com.filter;
import java.io.IOException;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FirstFilter implements Filter {
	private static Logger logger = LoggerFactory.getLogger(FirstFilter.class);
	public FilterConfig config;
	
	public void destroy() {
		this.config = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {
		HttpServletRequest hrequest = (HttpServletRequest)request;
		logger.info(hrequest.getRequestURI());
		chain.doFilter(request, response);
		return;
	}
	
	public void init(FilterConfig arg0) throws ServletException {
		config = arg0;
	}
}

5、

Filter作用范围:
(1)session控制,如果一个用户没登陆要访问相关信息,则跳转到登录页面
(2)字符集控制,前台的汉字传到后台乱码,可以加个字符过滤器

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

(3)加日志,时间控制等等。

版权声明:本文为zhangbin1989原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zhangbin1989/p/9720007.html