zeromemos
最好的学习方法就是输出所学的知识

SpringBoot使用Filter过滤器配置类配置方法

接着http://www.zeromemos.com/index/article/read.html?id=352

修改TestFilter,就是把@注解去掉了

package com.zeromemos.filter;

import com.google.common.collect.Lists;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.util.List;

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() {

    }
}

到Config配置类里加入一个Bean

    @Bean
    public FilterRegistrationBean<Filter> testFilter(){
        FilterRegistrationBean<Filter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
        //加入过滤器
        filterFilterRegistrationBean.setFilter(new TestFilter());
        //加入过滤路径
        filterFilterRegistrationBean.setUrlPatterns(Lists.newArrayList("/*"));
        //值越小优先级越高
        filterFilterRegistrationBean.setOrder(1);
        return filterFilterRegistrationBean;
    }

测试效果相同

评论区

关于我们

本站主要用于记录个人学习笔记,网站开发中,如需以前站内资料请加QQ群272473835索取。注册账号仅提供回帖功能,可不注册!

微信公众号