스프링 인터셉터는 서블릿 필터와 비슷한 기술이지만 적용되는 순서와 범위 사용방법이 다르다.

 

스프링 인터셉터 흐름

  HTTP 요청 -> WAS -> 필터 -> 서블릿 -> 스프링 인터셉터 -> 컨트롤러

 

스프링 인터셉터 체인

  HTTP 요청 -> WAS -> 필터 -> 서블릿 -> 인터셉터1 -> 인터셉터2 -> 컨트롤러

스프링 인터셉터는 체인으로 구성되는데 중간에 인터셉터를 추가할 수 있다.

예를 들어 로그를 남기는 인터셉터를 먼저 적용하고, 로그인 여부를 체크하는 인터셉터를 만들 수 있다.


스프링 인터셉터 구현

public interface HandlerInterceptor {
	default boolean preHandle(HttpServletRequest request, HttpServletResponse 
	response, Object handler) throws Exception {}
    
	default void postHandle(HttpServletRequest request, HttpServletResponse 
	response, Object handler, @Nullable ModelAndView modelAndView)
	throws Exception {}
    
	default void afterCompletion(HttpServletRequest request, HttpServletResponse 
	response, Object handler, @Nullable Exception ex) throws Exception {}
}

스프링 인터셉터를 구현하려면 HandlerInterceptor 인터페이스를 구현하면 된다.

preHandle : 컨트롤러 호출 전에 호출된다. (더 정확히는 핸들러 어댑터 호출 전에 호출된다.)
	preHandle 의 응답값이 true 이면 다음으로 진행하고, false 이면 더는 진행하지 않는다. 
	false인 경우 나머지 인터셉터는 물론이고, 핸들러 어댑터도 호출되지 않는다. 그림에서 1번에서 끝이 나버린다.
postHandle : 컨트롤러 호출 후에 호출된다. (더 정확히는 핸들러 어댑터 호출 후에 호출된다.)
afterCompletion : 뷰가 렌더링 된 이후에 호출된다

위의 인터페이스를 잘 구현했다면 스프링에 등록하면 작동하게 된다.

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

인터셉터의 호출순서, 적용할 URL, 제외할 URL 패턴 등을 지정할 수 있다.

 

출처 : 인프런 강의

'개발공부 > Spring' 카테고리의 다른 글

Spring :: 타입 컨버터  (0) 2023.08.21
필터(Filter)  (0) 2023.08.02
데이터 검증 (Validation)  (0) 2023.07.31
타임리프에서 스프링부트 메시지 사용하기  (0) 2023.07.28
타임리프 기본 문법 정리 (form 태그)  (0) 2023.07.28

+ Recent posts