springboot的filter过滤器的用法

springboot的filter过滤器的用法

  1. 在项目下创建一个包,包名为filter

  2. filter包下创建一个类型,命名随便

  3. 然后配置过滤器

    1. 给类加上过滤器的注释@WebFilter(filename = "filtername",urlPatterns = "/*")filtername用来设置过滤器的名称,urlPatters配置过滤器作用于那些文件
    2. 实现Filter接口
    package com.xiaowei.reggie.filter;
    
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import java.io.IOException;
    
    /**
     * filterName 配置改过滤器的名称
     */
    @WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
    public class LoginCheckFilter implements Filter {
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("进入过滤器");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
    
  4. 然后再启动类ReggieApplication中配置注解@ServletComponentScan

    package com.xiaowei.reggie;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.ServletComponentScan;
    
    @Slf4j
    @SpringBootApplication
    @ServletComponentScan
    public class ReggieApplication {
        public static void main(String[] args) {
            SpringApplication.run(ReggieApplication.class,args);
            log.info("项目启动成功~~");
        }
    }
    
    
  5. 重启项目

posted @ 2024-03-27 19:28  xiaowei123456  阅读(22)  评论(0编辑  收藏  举报