HttpIntercaptor

 对http进行拦截处理

import com.mmall.model.SysUser;
import com.mmall.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: zhouheng
 * @Created: with IntelliJ IDEA.
 * @Description:
 * @Date: 2018-07-17
 * @Time: 10:48
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {

    private static final String START_TIME = "requestTime";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();

        Long time = System.currentTimeMillis();
        request.setAttribute(START_TIME, time);
        log.info("request start. url:{}, params:{}", url, JsonMapper.obj2String(parameterMap));

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        String url = request.getRequestURL().toString();
//        Map parameterMap = request.getParameterMap();
//
//        Long start = (Long) request.getAttribute(START_TIME);
//        Long end = System.currentTimeMillis();
//
//        logger.info("end url {} end - start,{}", url, end - start, JsonMapper.obj2String(parameterMap) );
        removeThreadLocal();

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();

        Long time = System.currentTimeMillis();
        log.info("exception url {} time-->{}, error-->{}", url, time, JsonMapper.obj2String(parameterMap));

        removeThreadLocal();
    }

    public void removeThreadLocal() {
        RequestHolder.remove();
    }
}

 

也是一个很不错的工具类,可以获取访问过程中的请求 

你可能感兴趣的:(java框架,javaEE)