首页 > 其他分享 > springboot 过滤器FilterRegistrationBean详解

springboot 过滤器FilterRegistrationBean详解

时间:2023-03-03 15:45:52浏览次数:46  
标签:springboot FilterRegistrationBean bean 详解 过滤器 import servlet public

一:基础知识

1.通过FilterRegistrationBean实例注册,该方法能够设置过滤器之间的优先级

2.为了演示优先级,这里创建2个测试过滤器类:Test1Filter、Test2Filter

通过实现javax.servlet.Filter接口,覆盖其doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)方法,决定拦截或放行

    public class Test1Filter implements Filter {
     
        @Override
        public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
                throws IOException, ServletException {
            // TODO Auto-generated method stub
            HttpServletRequest request=(HttpServletRequest)arg0;
            System.out.println("自定义过滤器filter1触发,拦截url:"+request.getRequestURI());
            arg2.doFilter(arg0,arg1);
        }
     
    }

    public class Test2Filter implements Filter {
     
        @Override
        public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
                throws IOException, ServletException {
            // TODO Auto-generated method stub
            HttpServletRequest request=(HttpServletRequest)arg0;
            System.out.println("自定义过滤器filter2触发,拦截url:"+request.getRequestURI());
            arg2.doFilter(arg0,arg1);
        }
     
    }

通过在springboot的configuration中配置不同的FilterRegistrationBean实例,来注册自定义过滤器

这里创建一个configuration类

    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
     
    import com.example.demo.filter.Test1Filter;
    import com.example.demo.filter.Test2Filter;
     
    @Configuration
    public class DemoConfiguration {
     
        @Bean
        public FilterRegistrationBean<Test1Filter> RegistTest1(){
            //通过FilterRegistrationBean实例设置优先级可以生效
            //通过@WebFilter无效
            FilterRegistrationBean<Test1Filter> bean = new FilterRegistrationBean<Test1Filter>();
            bean.setFilter(new Test1Filter());//注册自定义过滤器
            bean.setName("flilter1");//过滤器名称
            bean.addUrlPatterns("/*");//过滤所有路径
            bean.setOrder(1);//优先级,最顶级
            return bean;
        }
        @Bean
        public FilterRegistrationBean<Test2Filter> RegistTest2(){
            //通过FilterRegistrationBean实例设置优先级可以生效
            //通过@WebFilter无效
            FilterRegistrationBean<Test2Filter> bean = new FilterRegistrationBean<Test2Filter>();
            bean.setFilter(new Test2Filter());//注册自定义过滤器
            bean.setName("flilter2");//过滤器名称
            bean.addUrlPatterns("/test/*");//过滤所有路径
            bean.setOrder(6);//优先级,越低越优先
            return bean;
        }
    }

其中

1第一个bean拦截所有路径,而第二个只拦截/test/*路径

2第一个bean优先级设置了1,而第二个设置了6,越低越优先,所以过滤器1应该在过滤器2前面拦截

运行springboot,访问/test/*请求如下图,再访问/v请求如下图只拦截了过滤器1,而过滤器2路径不匹配

以上原文地址:spring boot过滤器FilterRegistrationBean - 稚语希听 - 博客园

 二:实战练习

1.管理员过滤器

    package com.imooc.mall.filter;
     
    import com.imooc.mall.common.ApiRestResponse;
    import com.imooc.mall.common.Constant;
    import com.imooc.mall.exception.ImoocMallExceptionEnum;
    import com.imooc.mall.model.pojo.Category;
    import com.imooc.mall.model.pojo.User;
    import com.imooc.mall.service.UserService;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletResponseWrapper;
    import javax.servlet.http.HttpSession;
    import org.springframework.beans.BeanUtils;
    import org.springframework.beans.factory.annotation.Autowired;
     
    /**
     * 描述:     管理员校验过滤器
     */
    public class AdminFilter implements Filter {
     
        @Autowired
        UserService userService;
     
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
     
        }
     
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpSession session = request.getSession();
            User currentUser = (User) session.getAttribute(Constant.IMOOC_MALL_USER);
            if (currentUser == null) {
                PrintWriter out = new HttpServletResponseWrapper(
                        (HttpServletResponse) servletResponse).getWriter();
                out.write("{\n"
                        + "    \"status\": 10007,\n"
                        + "    \"msg\": \"NEED_LOGIN\",\n"
                        + "    \"data\": null\n"
                        + "}");
                out.flush();
                out.close();
                return;
            }
            //校验是否是管理员
            boolean adminRole = userService.checkAdminRole(currentUser);
            if (adminRole) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                PrintWriter out = new HttpServletResponseWrapper(
                        (HttpServletResponse) servletResponse).getWriter();
                out.write("{\n"
                        + "    \"status\": 10009,\n"
                        + "    \"msg\": \"NEED_ADMIN\",\n"
                        + "    \"data\": null\n"
                        + "}");
                out.flush();
                out.close();
            }
        }
     
        @Override
        public void destroy() {
     
        }
    }

2.管理员过滤器配置

    package com.imooc.mall.config;
     
    import com.imooc.mall.filter.AdminFilter;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
     
    /**
     * 描述:     Admin过滤器的配置
     */
    @Configuration
    public class AdminFilterConfig {
     
        @Bean
        public AdminFilter adminFilter() {
            return new AdminFilter();
        }
     
        @Bean(name = "adminFilterConf")
        public FilterRegistrationBean adminFilterConfig() {
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
            filterRegistrationBean.setFilter(adminFilter());
            filterRegistrationBean.addUrlPatterns("/admin/category/*");
            filterRegistrationBean.addUrlPatterns("/admin/product/*");
            filterRegistrationBean.addUrlPatterns("/admin/order/*");
            filterRegistrationBean.setName("adminFilterConf");
            return filterRegistrationBean;
        }
    }




标签:springboot,FilterRegistrationBean,bean,详解,过滤器,import,servlet,public
From: https://www.cnblogs.com/tiancai/p/17175821.html

相关文章

  • Springboot Controller接口默认自动填充 业务实体参数值
    前言今天看有小伙伴求救: 我还是一贯如此,有人不明白,没玩过HandlerMethodArgumentResolver。那么很可能不止他一个人,那么我就有必要出手。不多说,开搞。 正文快速模拟出......
  • Linux下的samba服务配置详解
    (Linux下的samba服务配置详解)一、Samba介绍1.SMB(ServerMessagesBlock,信息服务块)是一种在局域网上共享文件和打印机的一种通信协议,它为局域网内的不同计算机之间提供文......
  • springboot(三)
    1.热部署可以在不重启服务器的情况下重新加载更新后的程序.1.1实现原理①非springboot项目热部署实现原理开发非springboot项目时,我们要制作一个web工程并通过tomca......
  • SpringBoot接口返回统一格式
    packagecom.example.springboot.common;importorg.springframework.core.MethodParameter;importorg.springframework.http.MediaType;importorg.springframework......
  • Jmeter 的常见参数化方式详解
    在接口测试和性能测试中,参数化都是一个必须掌握的知识点。参数化的使用场景,例如:多个请求都是同一个ip地址,若服务器地址更换了,则脚本需要更改每个请求的ip注册账号,不允许......
  • IDEA 服务器热部署详解(On Update action/On frame deactivation)
    配置属性:OnUpdateaction:当代码改变的时候,Idea执行什么操作;-Updateresource:如果有更新,并且更新资源为(*.jsp,*.xml,不包括java文件),就会立即生效-Updateclassesandr......
  • 《程序员的自我修养》学习笔记——静态链接详解【第三弹】
    静态链接详解现在对ELF可重定位文件的整体轮廓和某些局部细节都有了一定了解。那么对于两个可重定位文件,如何将其链接起来形成可执行文件呢!以如下两个文件为例:/*main.......
  • springboot整合mybatis
    1,引入依赖<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version><scope>runtime</scope></depend......
  • SpringBoot集成Knife4j
    转载自: SpringBoot集成Knife4j-hviger-博客园(cnblogs.com)Knife4j简介Knife4j官网地址:https://doc.xiaominfo.com/knife4j是为JavaMVC框架集成Swagger生成Ap......
  • 串口通信原理详解232、422、485,入门必看!
    串口通信原理详解232、422、485,入门必看!混说Linux ​关注他 50人赞同了该文章本文介绍了串口通讯的基本概念、数据格式、通讯方式、典型的串口通讯......