본문 바로가기
Spring

인터셉터 설정

by 혀눅짱 2023. 10. 5.

인터셉터란?

 

DispatcherServlet과 컨트롤러 사이에서 요청을 가로채는 역할을 수행

 

인터셉터를 사용하면 비즈니스 로직을 직접 수정하지 않고도 로직 전후에 특정기능을 수행할 수 있음.

구현을 위해 HandlerInterceptor 인터페이스를 사용

 

 

전체적인 요청과 응답의 흐름에서  디스패쳐서블릿에서 핸들링 매핑 과정 후 해당 비즈니스 로직을 처리할 컨트롤러 진입 전, 후에 실행됨.

 

HandlerInterceptor 구조 

 preHandle

      컨트롤러로 요청이 가기 전에 수행할 코드를 작성하는 메소드

      리턴타입이 불리언이며 리턴이 true면 컨트롤러로 요청을 전달하고 false면 전달하지 않음.

      Object handler: 요청을 전달할 컨트롤러 객체가 담겨 있음.

 

 postHandle 

      컨트롤러의 로직 수행이후 View가 렌더링되기전에 수행할 코드 작성하는 메소드

 

  afterCompletion

       View가 렌더링 된 후에 실행되는 메소드

 

 

 

간단히 로깅을 찍는 인터셉터 예제소스를 구성해보았다.

 

@Component
@Slf4j
public class LoggingInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("PreHandle Interceptor In");
        log.info("Request path info : {}",request.getPathInfo());
        log.info("PreHandle Interceptor Out");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("PostHandle Interceptor In");
        log.info("Response : {} ",response.getHeaderNames());
        log.info("PostHandle Interceptor Out");
    }
}

컨트롤러 진입 전과 후에 로깅을 찍는 간단한 인터셉터이다.

 

이제 로깅인터셉터를 등록해보도록 하자.

 

@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

    private final LoggingInterceptor loggingInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loggingInterceptor)
                .addPathPatterns("/interceptor/**")
                .excludePathPatterns("/interceptor/exclude");
    }
}

WebMvcConfigurer 인터셉터를 구현한 클래스를 만들고 여기서 addInterceptors 메소드를 통해 등록한다.

빈으로 등록한 로깅인터셉터를 주입받아 등록 후 interceptor가 붙은 요청에는 모두 로깅인터셉터가 적용되도록한다. 단 interceptor/exlcude라는 요청은 해당 인터셉터에서 제외한다.

 

테스트를 위해 요청두개를 생성하였다.

 

@GetMapping("/interceptor/include")
    public String interceptorTest(){
        return "Include";
    }

    @GetMapping("/interceptor/exclude")
    public String interceptorTest2(){
        return "Exclude";
    }
}

 

첫번째 url로 요청할 경우 로깅인터셉터가 정상적으로 실행된것을 확인할 수 있다.

하지만 콘솔을 클리어하고 두번째 url로 요청할 경우 콘솔에 아무것도 찍히지 않았다.

해당 인터셉터가 정상적으로 패턴에 맞게 동작했다.

 

예전에 취준할 당시 공부했던 레거시 프로젝트, 또한 현재 근무하고있는 프로젝트에서는 인터셉터를 등록하는 과정을 별도 xml에서 빈으로 등록하여 패턴설정을 하고있다.  확실히 Java기반 설정들이 편하고 가시성도 좋은 것 같다.

'Spring' 카테고리의 다른 글

Redis와 SpringBoot 연동  (1) 2023.11.20
@Conditional과 @AutoConfiguration  (0) 2023.11.06
SpringBoot AutoConfiguration  (0) 2023.11.06
SpringBoot와 웹서버  (0) 2023.10.31
전역예외처리  (1) 2023.10.05