SpringBoot中使用過濾器
阿新 • • 發佈:2018-06-04
response tco sca api param throw ride AC etl
場景: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"); } @Overridepublic 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中使用過濾器