Spring/Spring MVC

(SERVLET) 핸들러 인터셉터(2)

주누 2020. 2. 5. 22:13

 

앞서 살펴보았던 세 가지 메서드를 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");
    }

}

2는 출력이 안된것을 볼 수 있다.


코드 참조

https://github.com/mike6321/Spring/tree/master/SpringMVC/demo-boot-web

 

mike6321/Spring

Contribute to mike6321/Spring development by creating an account on GitHub.

github.com