使用SpringBoot 中MVC 的 Interceptor 来实现接口入口参数的日志打印.
@Component
public class LogInterceptor implements HandlerInterceptor {private Logger logger = LoggerFactory.getLogger(LogInterceptor.class);@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {if (request.getDispatcherType().equals(DispatcherType.ASYNC)) {return true;}if (logger.isInfoEnabled()) {StringBuilder sb = new StringBuilder("请求地址为:").append(request.getRequestURI()).append(" 请求参数为:");Enumeration<String> paramNames = request.getParameterNames();boolean hasParam = false;while (paramNames.hasMoreElements()) {hasParam = true;String paramName = (String) paramNames.nextElement();String value = request.getParameter(paramName);sb.append(paramName).append(Constant.LEFT_BRACKET).append(value).append(Constant.RIGHT_BRACKET);}if (!hasParam) {sb.append("无");}logger.info(sb.toString());}// 获取请求IP地址String ipAddr = request.getHeader("X-Forwarded-For");if (ipAddr == null || ipAddr.trim().length() == 0) {ipAddr = request.getHeader("Proxy-Client-IP");}if (ipAddr == null || ipAddr.trim().length() == 0) {ipAddr = request.getHeader("WL-Proxy-Client-IP");}if (ipAddr == null || ipAddr.trim().length() == 0) {ipAddr = request.getRemoteAddr();}request.setAttribute("ClientIP", ipAddr);return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {// TODO Auto-generated method stub}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {}}
通过拦截器判断请求参数中是否携带某个参数
@Component
@Slf4j
public class SyncInterceptor implements HandlerInterceptor {@Value("${batch.batchKey}")private String batchKey;@Overridepublic boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {String batchKey = httpServletRequest.getParameter("batchKey");String errorMsg = "验证失败,无法进行操作";if (StringUtils.isBlank(batchKey)) {sendErrorMsg(httpServletResponse, errorMsg);return false;};if (!this.batchKey.equals(batchKey)) {sendErrorMsg(httpServletResponse, errorMsg);return false;} ;return true;}public void sendErrorMsg(HttpServletResponse httpServletResponse, String errorMsg) throws IOException {log.info(errorMsg);httpServletResponse.setStatus(500);PrintWriter out = httpServletResponse.getWriter();out.print(errorMsg);out.flush();out.close();}@Overridepublic void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {}@Overridepublic void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {}
}