zoukankan      html  css  js  c++  java
  • SpringBoot中使用过滤器Filter

    场景:API的参数都是经过加密的,于是在过滤器中,将获取到的请求的参数先解密再去进行处理

    一、实现Filter接口

    public class TestFilter implements Filter {
    
        private Logger logger = LoggerFactory.getLogger(this.getClass());
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            logger.info("TestFilter init");
        }
    
        @Override
        public void destroy() {
            logger.info("TestFilter destroy");
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            String servletPath = httpServletRequest.getServletPath();
    
            String body = HttpHelper.getBodyString(httpServletRequest);
            JSONObject param = JSONObject.parseObject(body);
            if (param == null) {
                logger.info("参数为空");
                return;
            }
            String data = param.getString("data");
            String time = param.getString("time");
            ServletRequestWrapper requestWrapper = new ServletRequestWrapper(httpServletRequest,
                    param.toString().getBytes(Charset.forName("UTF-8")));
    
            // 参数解密 解密过程省略
            //.............
            param.put("data", decryptParam); //将解密后的data取代加密的data
            requestWrapper.setBody(param.toString().getBytes(Charset.forName("UTF-8")));
            
             try {
                // 捕获异常
                chain.doFilter(requestWrapper, response);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    
    }        

    二、设置过滤的接口

     在TestFilter上添加 @WebFilter(filterName = "testFilter", urlPatterns = "/test/*") ,表示在test下的所有接口都经过过滤器

    三、启动过滤器

    Application中添加 @ServletComponentScan

  • 相关阅读:
    Python与常见加密方式
    ERROR 2002 (HY000):Can't connect to local MySQL server though socket '/var/lib/mysql/mysql.sock'(2)
    hive的分区表
    内部表和外部表的区别
    hive之SQL
    执行wc的时候提示连接被拒绝。Connection refused
    hive的简介
    hive的部署
    top命令信息
    web界面解读
  • 原文地址:https://www.cnblogs.com/JoeyWong/p/9134750.html
Copyright © 2011-2022 走看看