zoukankan      html  css  js  c++  java
  • springboot-添加过滤器

    过滤器一次,顾名思义,过滤一些东西等等。那么怎么实现呢,具体代码如下

    首先肯定需要建一个filter的包,创建一个过滤类实现filter接口,用来过滤

    package com.gateway.filter;
    
    import java.io.IOException;
    
    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 org.springframework.stereotype.Component;
    
    @Component
    public class UserFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            // TODO Auto-generated method stub
            
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
                throws IOException, ServletException {
                HttpServletRequest request=(HttpServletRequest) servletRequest;
            
                HttpServletResponse response=(HttpServletResponse) servletResponse;
                
                System.out.println("过滤器实现");
                
                chain.doFilter(request, response);
        }
    
        @Override
        public void destroy() {
            // TODO Auto-generated method stub
            
        }
    
    }

    然后在启动类中将该过滤类加载进去

    @Bean
         public FilterRegistrationBean filterRegistrationBean(){
            
            FilterRegistrationBean  filterRegistrationBean=new FilterRegistrationBean();
            
            List<String>urlPatterns=new ArrayList<String>();
            
            filterRegistrationBean.setFilter(new UserFilter());
            
            urlPatterns.add("/user/touser");
            
            filterRegistrationBean.setUrlPatterns(urlPatterns);
            return filterRegistrationBean;
        }

    由上可知,我们过滤的路径是/user/touser,那么过滤器和拦截器先进谁呢,debug测试即可得知,当路径/user/touser过来,先进入过滤器完成之后在进入拦截器,最后执行 完成之后进入controller

  • 相关阅读:
    HTML <input> 标签的 maxlength 属性
    HTTP 方法:GET 对比 POST
    怎么在html页面和js里判断是否是IE浏览器
    一行神奇的javascript代码
    c# 数据库批量插入数据SqlBulkCopy 示例
    c# 多线程调用窗体上的控件 示例
    sqlserver查找使用了某个字段的所有存储过程
    SQL Server 数据库性能优化
    SQL语句的执行过程
    Sql Server- 性能优化辅助指标SET STATISTICS TIME ON和SET STATISTICS IO ON
  • 原文地址:https://www.cnblogs.com/1a2b/p/9024457.html
Copyright © 2011-2022 走看看