Post

필터 & 인터셉터

Filter

was 와 서블릿 사이에 위치하여 HTTP 요청 및 응답을 가로채어 추가 작업을 할 수 있는 구성요소

다음 구성요소로 요청이 전달하거나 전달되지 않도록 할 수 있다.

모든 요청 URL 혹은 특정 URL 패턴에 적용하는 것이 가능하다.

자유롭게 필터를 추가하여 체인 형식으로 구성할 수 있다.

1
2
3
4
5
6
7
public interface Filter {
	public default void init(FilterConfig filterConfig) throws ServletException;

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;

	public default void destroy();
}
init()
필터 초기화 메서드. 서블릿 컨테이너가 필터를 싱글톤 객체로 생성할 때 호출된다.
doFilter()
요청이 오고 응답이 나갈 때 호출된다. 인증 및 권한, 암호화 및 복호화, 데이터 변환 등 다양한 작업을 구현하면 된다.
destroy()
필터 종료 메서드. 서블릿 컨테이너가 종료될 때 호출된다.

필터 등록

1
2
3
4
5
6
7
8
9
10
11
@Configuration
public class WebConfig {
	@Bean
	public FilterRegistrationBean logFilter() {
		FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>();
		filterRegistrationBean.setFilter(new LogFilter());
		filterRegistrationBean.setOrder(1);
		filterRegistrationBean.addUrlPatterns("/*");
		return filterRegistrationBean;
	}
}

필터는 보통 web.xml 에 등록하지만 스프링부트의 경우 내장 서블릿 컨테이너를 사용하기 때문에 web.xml 을 사용하지 않는다. 따라서 스프링부트를 사용한다면 위 방식으로 필터를 등록해야 한다.

@ServletComponentScan , @WebFilter 와 같은 어노테이션을 사용해도 필터를 등록할 수 있지만 필터의 순서를 지정할 수 없다.

Interceptor

디스패처 서블릿과 컨트롤러 사이에 위치하여 추가 작업을 할 수 있는 스프링MVC가 제공하는 컴포넌트

다음 작업을 진행하거나 진행하지 않도록 할 수 있다.

모든 요청 URL 혹은 특정 URL 패턴에 적용하는 것이 가능하다.

자유롭게 인터셉터를 추가하여 체인 형식으로 구성할 수 있다.

1
2
3
4
5
6
7
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;
}

preHandle()

  • 컨트롤러 호출 전에 호출된다. (정확히는 핸들러 어댑터 호출 전에 호출된다.)
  • return 값이 true 이면 다음 작업을 진행하고 false 이면 작업을 진행하지 않는다.

postHandle()

  • 컨트롤러 호출 후에 호출된다. (정확히는 핸들러 어댑터 호출 후에 호출된다.)
  • 컨트롤러에서 예외가 발생하면 호출되지 않는다.

afterCompletion()

  • 뷰가 렌더링 된 이후에 호출된다.

인터셉터 등록

1
2
3
4
5
6
7
8
9
10
@Configuration
public class WebConfig implements WebMvcConfigurer{
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new LogInterceptor())
			.order(1)
			.addPathPatterns("/**")
			.excludePathPatterns("/css/**", "/*.ico", "/error");
	}
}
This post is licensed under CC BY 4.0 by the author.