com.zcj.web.springmvc.interceptor.LogMdcInterceptor Maven / Gradle / Ivy
package com.zcj.web.springmvc.interceptor;
import com.zcj.util.UtilString;
import com.zcj.web.context.HttpContextUtil;
import com.zcj.web.mdc.UtilMdc;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogMdcInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
UtilMdc.removeLogId();
UtilMdc.removeClientIp();
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
// Do nothing
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String logId = request.getHeader(UtilMdc.KEY_HEADER_LOG_ID);
if (logId == null) {
logId = UtilString.getUUID();
}
UtilMdc.putLogId(logId);
String remoteIp = request.getHeader(UtilMdc.KEY_HEADER_CLIENT_IP);
if (remoteIp == null) {
remoteIp = HttpContextUtil.getRemoteIP(request);
}
UtilMdc.putClientIp(remoteIp);
return true;
}
}