-
Spring InterceptorSPRING 공부/서블릿 2022. 7. 13. 21:05
인터셉터란?
스프링에서 제공하는 제공하는 기능으로 Dispatcher Servlet과 매핑된 URL의 Controller의 사이에서 존재하며
해당 Controller 호출 전과 후에 요청, 응답을 참조하거나 가공할 수 있는 필터라고 볼 수 있다.
주 용도로는 인증/인가 작업이나, API 호출에대한 로깅, 요청 응답 정보 가공등이 있다.
여기서 의문이 드는점이 있는데, 사실 필터랑 인터셉터랑 무슨 차이가 있냐이다.
1. 관리 주관자가 다르다. 필터 : 웹 Servlet 컨테이너 , 인터셉터: 스프링 컨테이너
2. Request,Response 객체를 새로운 객체로 넣을 수 있나? 필터 : Yes , 인터셉터 : No
-> 필터에서는 request,response를 다음 필터로 넘겨주는 필터 체인을 쓰나, 인터셉터에서는
request,response에 객체 내부 상태만 변경 가능 할 뿐이다.
3. 용도에서 Filter가 포괄적인 기능을 담당하고, Interceptor에서 세분화된 기능을 담당한다.
구현해보기
1. HadnlerInterceptor 인터페이스를 구현하는 구현체를 만든다.
@Component @RequiredArgsConstructor @Slf4j public class CustomInterceptor implements HandlerInterceptor { private final ExampleLog exampleLog; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("CustomInterceptor preHandle 호출"); log.info("인터셉터 CustomInterceptor 내의 exampleLog Bean 메서드 호출 시작 ====="); exampleLog.testLog(); log.info("인터셉터 CustomInterceptor 내의 exampleLog Bean 메서드 호출 끝 ====="); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.info("CustomInterceptor postHandle 호출"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.info("CustomInterceptor afterCompletion 호출"); } }
2. 각 메서드에 사용하고자 하는 기능을 넣는다.
1) preHadnle 메서드 - Controller 호출 직전 적용할 기능을 넣는다.
2) postHandle 메서드 - Controller 호출 후 적용할 기능을 넣는다.
3) afterCompletion 메서드 - View rendering 이후 적용할 기능을 넣는다.
모든 것이 끝나면 클라이언트에게 Response를 전달한다.
3. WebMvcConfigurer 구현체에 인터셉터를 추가 등록 해준다.
@RequiredArgsConstructor @Configuration public class WebConfig implements WebMvcConfigurer { private final CustomTestFilter customFilter; private final CustomInterceptor customInterceptor; //필터를 Bean으로 등록해주기 @Bean public FilterRegistrationBean customFilter(){ FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>(); filterRegistrationBean.setFilter(customFilter); filterRegistrationBean.setOrder(1); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; } //InterCeptor 등록해주기 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(customInterceptor); } }
4. 테스트코드로 해당 컨트롤러를 호출해서 로그를 확인해보자
@AutoConfigureMockMvc @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) public class ExampleControllerIntegreTest { @Autowired private MockMvc mockMvc; @Test void getExample() throws Exception{ ResultActions resultActions = mockMvc.perform(get("/example") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) ); resultActions.andDo(MockMvcResultHandlers.print()); } }
자세히 보면 Filter -> Interceptor -> Controller 순으로 호출되는 것을 볼 수 있다.
지식 출처 : [Spring] 필터(Filter) vs 인터셉터(Interceptor) 차이 및 용도 - (1) - MangKyu's Diary (tistory.com)
'SPRING 공부 > 서블릿' 카테고리의 다른 글
서블릿 필터 (0) 2022.07.10 Spring Servlet의 원리 (0) 2022.01.19