스프링 인터셉터 - Springboot

Jiwon Park·2023년 5월 21일
0

스프링 MVC가 제공하는 스프링 인터셉트는 서블릿 필터와 같이 웹과 관련된 공통 관심 사항을 효율적으로 처리 할 수 있는 기술로 필터에 비해 매우 정밀하게 URL 패턴을 지정할 수 있다

스프링 인터셉터 흐름

HTTP 요청 -> WAS -> 필터 -> 서블릿 -> 스프링 인터셉터(체인 구성)> 컨트롤러(선택)

preHandle : 컨트롤러 호출 전, 핸들러 어댑터 호출 전에 호출(응답값이 true 이면 다음으로 진행)
postHandle : 컨트롤러 호출 후, 핸들러 어댑터 호출 후에 호출(예외 발생 시 호출x)
afterCompletion : 뷰가 렌더링 된 이후에 호출(예외 발생해도 항상 호출)

요청 로그 구현

@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    private 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(); //요청 로그를 구분하기 위한 uuid 를 생성

        request.setAttribute(LOG_ID, uuid); // LogInterceptor 는 싱글톤 처럼 사용되기 때문에 맴버변수를 사용하면 위험하므로 request에 담는다.
        
        /*if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler; // 호출할 컨트롤러 메서드의 모든 정보가 포함되어 있다.
        }*/
        
        log.info("REQUEST [{}][{}][{}]", uuid, requestURI, handler);

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle[{}]", modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String requestURI = request.getRequestURI();
        Object uuid = (String) request.getAttribute(LOG_ID);
        log.info("RESPONSE [{}][{}][{}]", uuid, requestURI, handler);
        if(ex!=null){
            log.error("afterCompletion error!!", ex);
        }
    }
}

인증 체크 구현

@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();

        log.info("인증 체크 인터셉트 실행 {}", requestURI);

        HttpSession session = request.getSession(false);

        if(session == null || session.getAttribute(SessionConst.LOGIN_MEMBER) == null){
            log.info("미인증 사용자 요청");
            response.sendRedirect("/login?redirectURL=" + requestURI);
            return false;
        }
        return true;
    }
}

설정

@Configuration
public class WebConfig implements WebMvcConfigurer {

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

        registry.addInterceptor(new LoginCheckInterceptor())
                .order(2)
                .addPathPatterns("/**")
                .excludePathPatterns("/", "/members/add", "/login", "/logout", "/css/**", "/*.ico", "/error");
    }

PathPattern 공식 문서 ←

profile
안녕하세요

0개의 댓글