스프링/4. 스프링 MVC-2

64. 서블릿 예외처리 인터셉터

sdafdq 2023. 9. 10. 20:01
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    public static final String LOG_ID = "logId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        String uuid = UUID.randomUUID().toString();
        request.setAttribute(LOG_ID, uuid);

        log.info("REQUEST [{}][{}][{}][{}]", uuid, request.getDispatcherType(), requestURI, handler);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("RESPONSE [{}][{}][{}][{}]", request.getAttribute(LOG_ID), request.getDispatcherType(), request.getRequestURI(), handler);
    }
}

인터셉터 등록.

 

간단하게 uri, uuid 지정해서 request에 넣어주고, dispatcherType 출력

 

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogInterceptor())
                .order(1)
                .addPathPatterns("/**")
                .excludePathPatterns("/css/**", "*.ico", "/error", "/error-page/**");
    }
}

등록.

인터셉터 추가해주고,

순서 정해주고,

경로 지정해주고,

근데 여기선 DispatcherType대신 아예 uri 경로로 지정. 이러면 저쪽 경로는 인터셉터를 안거침.