SpringBoot使用Filter过滤器注解配置方法
创建filter目录放置过滤器类,在该目录下创建一个TestFilter过滤器
package com.zeromemos.filter; import com.google.common.collect.Lists; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.IOException; import java.util.List; @Order(1) //数值越低优先级越高 @Component @WebFilter(filterName = "testFilter" , urlPatterns = "/*") //对所有链接/*进行过滤 public class TestFilter implements Filter {
//过滤白名单 public static List<String> WHITE_PATH = Lists.newArrayList("/index","/favicon.ico"); @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("过滤器初始化"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("进入过滤器"); //获取请求链接 HttpServletRequest request = (HttpServletRequest)servletRequest; String requestURI = request.getRequestURI(); System.out.println("当前请求路径是 " + requestURI); //如果是白名单里的链接,直接进入到下一个过滤器处理 if (WHITE_PATH.contains(requestURI)){ System.out.println("判断是白名单里的方法"); filterChain.doFilter(servletRequest, servletResponse); return; } //这里执行拦截的方法,比如跳转到指定的页面 System.out.println("判断不是白名单里的方法"); System.out.println("跳转到指定页面/index"); HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse)servletResponse); wrapper.sendRedirect("/index"); } //过滤器销毁方法 @Override public void destroy() { } }
过滤器init()方法在项目启动时执行
请求http://localhost:9001/article/getAll路径测试,会被过滤跳转到http://localhost:9001/index