springBoot添加自定义过滤器Filter

方式1

1.添加component注解

2.实现javax.servlet.Filter

3.重写init,doFilter,destory方法

 

方式2

添加

1添加@webfilter注解、@Order(1)注解,可以设定过滤的路径

 

@WebFilter(filterName = "**",urlPatterns = {"*.html"})
2.实现javax.servlet.Filter
3在启动类application上加注解@ServletComponentScan

@ServletComponentScan(basePackages = "com.zz.project")

 

另外:如果我们的应用程序运行在一台负载均衡代理服务器后方,因此需要将代理服务器发来的请求包含的IP地址转换成真正的用户IP。Tomcat 8 提供了对应的过滤器:RemoteIpFilter。通过将RemoteFilter这个过滤器加入过滤器调用链即可使用它 

@Configuration
public class WebConfiguration {

    @Bean
    public RemoteIpFilter remoteIpFilter() {
        System.out.println("this is my RemoteIpFilter");
        return new RemoteIpFilter();
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        System.out.println("this is my FilterRegistrationBean");
        filterRegistrationBean.setFilter(new MyFilter());
        List<String> urlPatterns = new ArrayList<>();
        urlPatterns.add("/*");
        filterRegistrationBean.setUrlPatterns(urlPatterns);
        filterRegistrationBean.addInitParameter("paramName","paramValue");
        filterRegistrationBean.setName("MyFilter");
        filterRegistrationBean.setOrder(1);
        return filterRegistrationBean;
    }

    public class MyFilter implements Filter {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
            System.out.println("this is MyFilter,url :" + httpServletRequest.getRequestURL());
            filterChain.doFilter(httpServletRequest,servletResponse);
        }

        @Override
        public void destroy() {

        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值