• SpringBoot 使用 Filter 过滤器


     Filter 过滤器 是Java EE 提供的只能处理  ServletRequest 和 ServletResponse 里的相关信息,不能处理与Spring相关的信息

    package com.example.interceptor;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;
    
    import javax.servlet.*;
    import java.io.IOException;
    
    @Component
    public class DemoFilter implements Filter {
        private static final Logger logger = LoggerFactory.getLogger(DemoFilter.class);
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            logger.info("=========DemoFilter=======init==============");
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            logger.info("=========DemoFilter=======doFilter==start============");
    
            filterChain.doFilter(servletRequest,servletResponse);//执行过滤
    
            logger.info("=========DemoFilter=======doFilter==end============");
        }
    
        @Override
        public void destroy() {
            logger.info("=========DemoFilter=======destroy==============");
        }
    }
    package com.example.config;
    
    import com.example.interceptor.DemoFilter;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Configuration//说明这是一个配置类
    public class WebConfig {
    
        @Bean  //Bean注入,相当于原本在web.xml中写配置注入类
        public FilterRegistrationBean demoFilter(){
            FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    
            //在DemoFilter类上不用@Compent注入则可以用如下方法注入
            DemoFilter demoFilter = new DemoFilter();
            registrationBean.setFilter(demoFilter);
            List<String> urls = new ArrayList<>();
            urls.add("/*");//对所有url起作用
            registrationBean.setUrlPatterns(urls);
    
            return  registrationBean;
        }
    }
  • 相关阅读:
    抬起头,看到满天星星
    别再嫌弃你妈妈话多唠叨啦,她可能正在做声音健脑操呢
    此生不能不認識的一個人
    长尾夹除了夹东西还能做什么?
    Markdown使用经验总结
    注册quora失败
    电脑插入耳机后声音仍然外放
    centOS下安装tree命令
    解决ubuntu “无法获得锁"
    虚拟机上Ubuntu无法上网问题
  • 原文地址:https://www.cnblogs.com/mingforyou/p/14617839.html
Copyright © 2020-2023  润新知