springboot使用过滤器
作者:mmseoamin日期:2023-12-14

一:过滤器

1.过滤器介绍

过滤器是处于客户端与服务器资源文件之间的一道过滤网,帮助我们过滤一些不符合要求的请求。通常用作 Session校验,判断用户权限。

2.过滤器生命周期

使用过滤器很简单,只需要实现Filter类,然后重写它的3个方法即可。

  • init方法:程序启动调用Filter的init()方法(永远只调用一次);在容器中创建当前过滤器的时候自动调用这个方法。
  • destory方法:程序停止调用Filter的destroy()方法(永远只调用一次);在容器中销毁当前过滤器的时候自动调用这个方法。
  • doFilter方法:doFilter()方法每次的访问请求如果符合拦截条件都会调用(程序第一次运行,会在servlet调用init()方法以后调用;不管第几次,都在调用doGet(),doPost()方法之前)。这个方法有3个参数,分别是ServletRequest、ServletResponse和FilterChain可以从参数中获取HttpServletReguest和HttpServletResponse对象进行相应的处理操作。

    二:使用注解方式实现过滤器(@WebFilter) 

     1.在springboot 启动类添加该注解@ServletComponentScan

    @SpringBootApplication
    @ServletComponentScan // 过滤器
    public class Springboot02WebTestApplication {
        SpringApplication.run(Springboot02WebTestApplication.class, args);
    }

     2.写个过滤器类,实现Filter接口

    import com.alibaba.fastjson.JSONObject;
    import org.springframework.core.annotation.Order;
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import java.io.IOException;
    import java.io.PrintWriter;
    // urlPatterns 过滤路径  filterName 过滤器name
    @WebFilter(urlPatterns = "/user/*", filterName = "tokenFilter1")
    public class TokenFilter1 implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    //        Filter.super.init(filterConfig);
            System.out.println("init");
        }
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("doFilter");
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String token = request.getHeader("token");
            System.out.println(token);
            //该方法执行后直接运行至下一个过滤器
            if(token!=null){
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                servletResponse.setCharacterEncoding("UTF-8");
                servletResponse.setContentType("application/json; charset=utf-8");
                PrintWriter out = servletResponse.getWriter();
                JSONObject res = new JSONObject();
                res.put("msg", "错误");
                res.put("success", "false");
                out.append(res.toString());
            }
        }
        @Override
        public void destroy() {
    //        Filter.super.destroy();
            System.out.println("destroy");
        }
    }
    

    3.访问,我使用的Postman软件进行的测试

            添加请求头token信息,才可以访问成功。


    三:使用非注解方式实现过滤器(直接注入到spring中)

     1.Filter代码

    import com.alibaba.fastjson.JSONObject;
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import java.io.IOException;
    import java.io.PrintWriter;
    public class TokenFilter2 implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            System.out.println("init");
        }
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("doFilter");
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String token = request.getHeader("token");
            System.out.println(token);
            //该方法执行后直接运行至下一个过滤器
            if(token!=null){
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                servletResponse.setCharacterEncoding("UTF-8");
                servletResponse.setContentType("application/json; charset=utf-8");
                PrintWriter out = servletResponse.getWriter();
                JSONObject res = new JSONObject();
                res.put("msg", "错误");
                res.put("success", "false");
                out.append(res.toString());
            }
        }
        @Override
        public void destroy() {
            System.out.println("destroy");
        }
    }
    

     2.Filter配置文件

    import com.itsufu.filter.TokenFilter2;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    @Configuration
    public class FilterConfig {
        // Filter代码类
        @Bean
        public TokenFilter2 tokenFilter2() {
            return new TokenFilter2();
        }
        @Bean
        public FilterRegistrationBean getFilterRegistrationBean(TokenFilter2 tokenFilter2) {
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
            filterRegistrationBean.setFilter(tokenFilter2);
            filterRegistrationBean.setOrder(2);
            filterRegistrationBean.addUrlPatterns("/user/*");
            filterRegistrationBean.setName("tokenFilter2");
            return filterRegistrationBean;
        }
    }
    

     3.测试与注解式一样。

    在此,祝各位帅哥美女,步步高升,一帆风顺!!!