自定义Filter拦截器

这里使用Servlet3.0的注解进行配置
一、创建拦截器类

@WebFilter(urlPatterns = "/get/api/*", filterName = "loginFilter")
public class LoginFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("拦截器init");
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("执行拦截器");
       HttpServletRequest httpServletRequest=(HttpServletRequest)request;
       HttpServletResponse httpServletResponse=(HttpServletResponse)response;
       String username=httpServletRequest.getParameter("username");
       if(username.equals("xiaoqiang")) {
    	   chain.doFilter(request, response);
       }else {
    	   httpServletResponse.sendRedirect("/fale.html");
     	  return;
       }
	}
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
       System.out.println("filter容器被销毁");
	}
}

创建拦截器类,需要基本两步
1、实现Filter类后需要实现init,doFilter,destroy三个方法
容器启动时首先会调用init方法,有匹配的请求访问时会调用doFiter方法,容器正常关闭时会调用destroy方法
在doFilter方法里实现拦截逻辑
chain.doFilter(request, response)调用放行
2、在类前面添加@WebFilter(urlPatterns = “/get/api/*”, filterName = “loginFilter”)
urlPatterns 定义拦截那些路径下面的
二、启动类加注解
在启动类添加@ServletComponentScan //自动扫描本包下或者子包下拦截器

©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页