码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot中使用过滤器

时间:2018-06-04 19:17:45      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:场景   mon   style   oid   can   obj   str   cto   ati   

场景: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

SpringBoot中使用过滤器

标签:场景   mon   style   oid   can   obj   str   cto   ati   

原文地址:https://www.cnblogs.com/JoeyWong/p/9134750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!