SpringBoot中使用过滤器
Posted 精神病人思路广,弱智儿童欢乐多
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot中使用过滤器相关的知识,希望对你有一定的参考价值。
场景: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中使用过滤器的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot中表单提交报错“Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported“(代码片段
SpringBoot启动报错“Consider defining a bean of type ‘xxx.mapper.UserMapper‘ in your configuration.“(代码片段
Spring boot:thymeleaf 没有正确渲染片段
全栈编程系列SpringBoot整合Shiro(含KickoutSessionControlFilter并发在线人数控制以及不生效问题配置启动异常No SecurityManager...)(代码片段