过滤器

Servlet分类

  • 普通servlet
  • 过滤器
  • 监听器

过滤器的基本结构

  • 普通的servlet是extendshttpServlet这个类

  • 但是过滤器是实现一个Fiter接口,过滤器采用链式操作

  • 方法

方法 解释
init(FilterConfig c) 初始化信息获取,不需要配置任何直接可以走到这一步程序
doFilter(ServletRequest req,ServletResponse resp,FilterChain chain) 重点介绍FilterChain 过滤链
destory() 销毁,服务器关闭的时候
public class MyFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		// 服务器关闭的时候销毁
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain arg2) throws IOException, ServletException {
		// TODO Auto-generated method stub
		resp.getWriter().write("doFilter...............");
	}
    // 过滤器不需要要任何的配置就可以init操作的
	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("过滤器初始化");
	}

}

  • 过滤器的web.xml配置
<filter>
  	<filter-name>myfilter</filter-name>
  	<filter-class>com.zhao.MyFilter</filter-class>
  </filter>
  
  <filter-mapping>
  	<filter-name>myfilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  • FilterChain

就是过滤链,如果有多个过滤器则会一直过滤下去,否则就会跳转到目标Servlet

public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub

		chain.doFilter(req, resp);

	}

过滤路径的语法

比较简单,举几个例子

/*  // 过滤所有
/demo/* //过滤demo路径下的所有

例子

编码过滤

private String charSet ;
	public void init(FilterConfig config)
          throws ServletException{
		this.charSet = config.getInitParameter("charset") ;	
	}
	public void doFilter(ServletRequest request,
              ServletResponse response,
              FilterChain chain)
              throws IOException,
                     ServletException{
		request.setCharacterEncoding(this.charSet) ;
		chain.doFilter(request,response) ;
	}
	public void destroy(){
	}
<filter>
		<filter-name>encoding</filter-name>
		<filter-class>org.lxh.filterdemo.EncodingFilter</filter-class>
		<init-param>
			<param-name>charset</param-name>
			<param-value>GBK</param-value>
		</init-param>
	</filter>

登录拦截

public class LoginFilter implements Filter {
	public void init(FilterConfig config)
          throws ServletException{
	}
	public void doFilter(ServletRequest request,
              ServletResponse response,
              FilterChain chain)
              throws IOException,
                     ServletException{
	
		HttpServletRequest req = (HttpServletRequest) request ;
		HttpSession ses = req.getSession() ;
		if(ses.getAttribute("userid") != null) {

			chain.doFilter(request,response) ;
		} else {
			request.getRequestDispatcher("login.jsp").forward(request,response) ;
		}
	}
	public void destroy(){
	}
}
posted @ 2018-03-28 23:27  墮落方能自由  阅读(151)  评论(0)    收藏  举报