HttpOpLogInterceptor.java 2.03 KB
package com.bsth.oplog.http;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * @ClassName: HttpOpLogger
 * @Description: TODO(HTTP 接口日志拦截器)
 * @author PanZhao
 * @date 2016年10月20日 上午12:03:11
 *
 */
//@Component
public class HttpOpLogInterceptor implements HandlerInterceptor {

	private final PathMatcher pathMatcher = new AntPathMatcher();

	// GET 白名单
	private String[] httpGetWhiteList = { "/user/login/**", "/user/currentUser","/dictionary/**", "/module/findByCurrentUser", "/gps/**", "/error/**" };

	// POST 白名单
	private String[] httpPostWhiteList = {
		"/control/upstream" 
	};
	
	@Autowired
	HttpRecorder httpRecorder;

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {

		String method = request.getMethod(), path = request.getRequestURI();
		// white list
		String[] whiteList = method == "GET" ? httpGetWhiteList : httpPostWhiteList;

		if (!isWhiteURL(whiteList, path)) 
			httpRecorder.record(request, (HandlerMethod)arg2);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

		return true;
	}

	private boolean isWhiteURL(String[] whiteList, String currentURL) {
		for (String whiteURL : whiteList) {
			if (pathMatcher.match(whiteURL, currentURL)) {
				return true;
			}
		}
		return false;
	}
}