앞서 살펴보았던 세 가지 메서드를 override 합니다.
public class GreetingInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle 1");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle 1");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion 1");
}
}
이때 preHandle에서는 다음 처리로 넘어갈 수 있도록 return 값을 true로 변경시킵니다.
또 다른 interceptor 생성
public class AnotherInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle 2");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle 2");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion 2");
}
}
설정 파일에 interceptor 설정 추가
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new GreetingInterceptor());
registry.addInterceptor(new AnotherInterceptor());
}
}
순서 설정
order 메서드를 사용하여 순서를 조정할 수 있다. (낮을수록 우선순위가 높다.)
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new GreetingInterceptor()).order(0);
registry.addInterceptor(new AnotherInterceptor()).order(-1);
}
}
PathPattern 설정
url 패턴을 설정하여 interceptor의 url을 지정할 수 있다.
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new GreetingInterceptor()).order(0);
registry.addInterceptor(new AnotherInterceptor()).order(-1)
.addPathPatterns("/hi");
}
}
코드 참조
https://github.com/mike6321/Spring/tree/master/SpringMVC/demo-boot-web
'Spring > Spring MVC' 카테고리의 다른 글
(SERVLET) HTTP 메세지 컨버터 (1) (0) | 2020.02.10 |
---|---|
(SERVLET) 리소스 핸들러 (0) | 2020.02.10 |
(SERVLET) 핸들러 인터셉터(1) (0) | 2020.02.05 |
(SERVLET) 스프링 부트의 스프링 MVC 설정 (0) | 2020.02.02 |
(SERVLET) WebMvcConfigurer (0) | 2020.02.02 |