1.拦截器
java里的拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行,同时也提供了一种可以提取action中可重用部分的方式。在AOP(Aspect-Oriented Programming)中拦截器用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。
package com.shitou.deposit.interceptor; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Parameter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.MethodParameter; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.shitou.deposit.contract.dto.req.Request; /** * DepositInterceptor * @author zhouky * @since 2018年12月27日 */ public class DepositInterceptor implements HandlerInterceptor { private Logger logger = LoggerFactory.getLogger(getClass()); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("DepositInterceptor ..."); // 所有请求第一个进入的方法 String reqURL = request.getRequestURL().toString(); String ip = request.getRemoteHost (); InputStream is = request.getInputStream (); StringBuilder responseStrBuilder = new StringBuilder (); BufferedReader streamReader = new BufferedReader (new InputStreamReader (is,"UTF-8")); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); String parmeter = responseStrBuilder.toString(); long startTime = System.currentTimeMillis(); request.setAttribute("startTime", startTime); if (handler instanceof HandlerMethod) { StringBuilder sb = new StringBuilder(1000); sb.append("-----------------------\n"); HandlerMethod h = (HandlerMethod) handler; Parameter[] objs =h.getMethod().getParameters(); for(Object obj:objs){ Request req = (Request) obj; System.out.println(""); if(obj instanceof Request){ } } //Controller 的包名 sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n"); //方法名称 sb.append("Method: ").append(h.getMethod().getName()).append("\n"); //请求方式post\put\get 等等 sb.append("RequestMethod: ").append(request.getMethod()).append("\n"); //所有的请求参数 sb.append("Params: ").append(parmeter).append("\n"); //部分请求链接 sb.append("URI : ").append(request.getRequestURI()).append("\n"); //完整的请求链接 sb.append("AllURI: ").append(reqURL).append("\n"); //请求方的 ip地址 sb.append("request IP: ").append(ip).append("\n"); logger.info(sb.toString()); } //修改request中的参数并保存到request中 request.setAttribute("parmeter_json", parmeter); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {} }
package com.shitou.deposit.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.shitou.deposit.interceptor.DepositInterceptor; import com.shitou.deposit.interceptor.DepositInterceptor1; /** * InterceptorConfig * @author zhouky * @since 2018年12月27日 */ @Configuration public class InterceptorConfig extends WebMvcConfigurerAdapter { @Bean public DepositInterceptor getDepositInterceptor() { return new DepositInterceptor(); } @Bean public DepositInterceptor1 getDepositInterceptor1() { return new DepositInterceptor1(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getDepositInterceptor()).addPathPatterns("/deposit/**"); // registry.addInterceptor(getDepositInterceptor1()).addPathPatterns("/deposit/**"); super.addInterceptors(registry); } }
package com.shitou.deposit.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSONObject; import com.shitou.deposit.filter.BufferedServletRequestWrapper; /** * DepositInterceptor1 * @author zhouky * @since 2018年12月27日 */ public class DepositInterceptor1 implements HandlerInterceptor { private Logger logger = LoggerFactory.getLogger(getClass()); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("DepositInterceptor begin ..."); BufferedServletRequestWrapper requestWrapper = new BufferedServletRequestWrapper(request); //在这边替换流,使用工具类GetRequestJsonUtils获取json参数 JSONObject json = GetRequestJsonUtils.getRequestJsonObject(requestWrapper); logger.info("DepositInterceptor end ...{}",json.toJSONString()); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {} }
package com.shitou.deposit.filter; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * BufferedServletRequestWrapper * @author zhouky * @since 2018年12月27日 */ public class BufferedServletRequestWrapper extends HttpServletRequestWrapper { private byte[] buffer; public BufferedServletRequestWrapper(HttpServletRequest request) throws IOException { super(request); InputStream is = request.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buff[] = new byte[1024]; int read; while ((read = is.read(buff)) > 0) { baos.write(buff, 0, read); } this.buffer = baos.toByteArray(); } @Override public ServletInputStream getInputStream() throws IOException { return new BufferedServletInputStream(this.buffer); } // 对外提供读取流的方法 @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } }
package com.shitou.deposit.interceptor; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import com.alibaba.fastjson.JSONObject; /** * GetRequestJsonUtils * @author zhouky * @since 2018年12月27日 */ public class GetRequestJsonUtils { public static JSONObject getRequestJsonObject(HttpServletRequest request) throws IOException { String json = getRequestJsonString(request); return JSONObject.parseObject(json); } /*** * 获取 request 中 json 字符串的内容 * * @param request * @return :byte[]
* @throws IOException */ public static String getRequestJsonString(HttpServletRequest request) throws IOException { String submitMehtod = request.getMethod(); // GET if (submitMehtod.equals("GET")) { if(StringUtils.isNotEmpty(request.getQueryString())){ return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\""); }else{ return new String("".getBytes("iso-8859-1"), "utf-8").replaceAll("%22", "\""); } // POST } else { return getRequestPostStr(request); } } /** * 描述:获取 post 请求的 byte[] 数组 ** 举例: ** @param request * @return * @throws IOException */ public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException { int contentLength = request.getContentLength(); if(contentLength<0){ return null; } byte buffer[] = new byte[contentLength]; for (int i = 0; i < contentLength;) { int readlen = request.getInputStream().read(buffer, i, contentLength - i); if (readlen == -1) { break; } i += readlen; } return buffer; } /** * 描述:获取 post 请求内容 ** 举例: ** @param request * @return * @throws IOException */ public static String getRequestPostStr(HttpServletRequest request) throws IOException { byte buffer[] = getRequestPostBytes(request); String charEncoding = request.getCharacterEncoding(); if (charEncoding == null) { charEncoding = "UTF-8"; } return new String(buffer, charEncoding); } }
2.过滤器
package com.shitou.deposit.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; /** * DepositFilter * @author zhouky * @since 2018年12月27日 */ @Component @WebFilter(filterName="DepositFilter",urlPatterns="/**") public class DepositFilter implements Filter{ /** * 过滤 */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletRequest requestWrapepr = null; if(request instanceof HttpServletRequest){ requestWrapepr = new BufferedServletRequestWrapper((HttpServletRequest)request); } if(requestWrapepr == null){ chain.doFilter(request, response); }else{ chain.doFilter(requestWrapepr, response); } } /** * 初始化 */ @Override public void init(FilterConfig arg0) throws ServletException {} /** * 销毁 */ @Override public void destroy() {} }
package com.shitou.deposit.filter; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; class BufferedServletInputStream extends ServletInputStream { private ByteArrayInputStream inputStream; public BufferedServletInputStream(byte[] buffer) { this.inputStream = new ByteArrayInputStream( buffer ); } @Override public int available() throws IOException { return inputStream.available(); } @Override public int read() throws IOException { return inputStream.read(); } @Override public int read(byte[] b, int off, int len) throws IOException { return inputStream.read( b, off, len ); } @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener listener) {} }
package com.shitou.deposit.filter; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * BufferedServletRequestWrapper * @author zhouky * @since 2018年12月27日 */ public class BufferedServletRequestWrapper extends HttpServletRequestWrapper { private byte[] buffer; public BufferedServletRequestWrapper(HttpServletRequest request) throws IOException { super(request); InputStream is = request.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buff[] = new byte[1024]; int read; while ((read = is.read(buff)) > 0) { baos.write(buff, 0, read); } this.buffer = baos.toByteArray(); } @Override public ServletInputStream getInputStream() throws IOException { return new BufferedServletInputStream(this.buffer); } // 对外提供读取流的方法 @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } }
package com.shitou.deposit.filter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSONObject; //@Component //@WebFilter(filterName = "DepositFilter1", urlPatterns = "/*") public class DepositFilter1 implements Filter { @SuppressWarnings("unused") private Logger logger = LoggerFactory.getLogger(DepositFilter1.class); @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) srequest; // 访问地址 String uri = request.getRequestURI(); if ("/deposit/execute".equals(uri)) { Mapm = new HashMap (request.getParameterMap()); logger.info(JSONObject.toJSONString(m)); HttpServletRequest req = (HttpServletRequest) request; ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper(req, m); logger.info(JSONObject.toJSONString(wrapRequest.getParameterMap())); request = wrapRequest; } filterChain.doFilter(request, sresponse); } @Override public void destroy() {} }
3.切面
package com.shitou.deposit.aspect; import java.util.Base64; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.shitou.deposit.baofu.config.BaoFuConfig; import com.shitou.deposit.contract.dto.req.Request; import com.shitou.deposit.lanmaoly.config.LanMaolyConfig; import com.shitou.deposit.strategy.enums.TransactionChannelEnum; import com.shitou.framework.log.LOG_TYPE; @SuppressWarnings("unchecked") //@Component //@Aspect public class DepositAspect { private final Logger logger = LoggerFactory.getLogger(LOG_TYPE.CONTROLLER_ASPECT.val); @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)") public void depositAspect() {} @Before(value = "depositAspect()") public void beforeAdvice(JoinPoint pjp) throws Throwable { Object[] objects = pjp.getArgs(); for(Object obj:objects){ if(obj instanceof Request){ Request paramVO = (Request) obj; MapreqMap = (Map ) paramVO.getReqData(); boolean bool = reqMap.containsKey("retUrl"); if(bool){ String retUrl = (String) reqMap.get("retUrl"); if(StringUtils.isNotBlank(retUrl)){ String encodedUrl = Base64.getEncoder().encodeToString(retUrl.getBytes()); if(TransactionChannelEnum.LANM.getCode().equals("")&& !"1".equals(LanMaolyConfig.ifSyncDirectSwitch)){// 懒猫是否开启同步回盘直连前端开关 1-是 0-否 retUrl = LanMaolyConfig.syncLM+"/"+encodedUrl; }else if(TransactionChannelEnum.BAOF.getCode().equals("")&& !"1".equals(BaoFuConfig.ifSyncDirectSwitch)){ retUrl = BaoFuConfig.syncBF+"/"+encodedUrl; } reqMap.put("retUrl", retUrl); paramVO.setReqData(reqMap); } } } } } }