场景: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
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
span.s1 { color: #777777 }
span.s2 { color: #3933ff }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; color: #777777 }
原文地址:https://www.cnblogs.com/JoeyWong/p/9134750.html
时间: 2024-10-12 06:56:12