1. 어노테이션 인터페이스 작성
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE, ElementType.METHOD}) //클래스 혹은 메서드에 어노테이션 적용
public @interface SslCheck {
boolean isBlock() default false; //어노테이션에 인수를 입력받아 활용하고 싶을 경우 메서드 정의
}
2. HandlerInterceptorAdapter를 상속받은 인터셉터 클래스를 작성하면서 어노테이션을 활용
public class SslCheckInterceptor extends HandlerInterceptorAdapter {
//주로 preHandle()에 로직을 작성할 것이다.
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
//현재 호출된 핸들러 메서드에 해당 어노테이션이 존재하는지 체크
SslCheck sslCheckAnnotation = handlerMethod.getMethodAnnotation(SslCheck.class);
//현재 호출된 핸들러 클래스에 해당 어노테이션이 존재하는지 체크
sslCheckAnnotation = (sslCheckAnnotation == null) ? handlerMethod.getBeanType().getAnnotation(SslCheck.class) : sslCheckAnnotation;
/*
* 아래 조건에 해당할 경우 이 Interceptor를 실행하지 않고 SKIP한다.
*/
if(sslCheckAnnotation == null){ /* 메서드에도, 클래스에도 어노테이션이 없을 경우 */
return super.preHandle(request, response, handlerMethod); /* 바이패스 */
}
/*
* 어노테이션 사용시 괄호 안에 인수로 입력한 값을 활용하는 예시 (예: @SslCheck(isBlock = true))
*/
if(sslCheckAnnotation.isBlock()){
response.sendRedirect("http://google.com"); //리디렉션
return false; //preHandle()에서 false를 리턴하면 DispatcherServlet은 Interceptor가 알아서 response를 처리했다고 간주한다.
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
}
}
3. controller.xml 에 Interceptor bean을 선언하고 Interceptor chain에 등록
(controller.xml 은 DispatcherServlet의 init-param 에 contextConfigLocation 이라는 이름으로 삽입되는 파일명이다.)
<bean id="sslCheckInterceptor" class="common.interceptor.SslCheckInterceptor" /> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> <property name="useSuffixPatternMatch" value="true" /> <property name="alwaysUseFullPath" value="true" /> <property name="order" value="1" /> <property name="interceptors"> <list> <ref bean="controllerLogger"/> <ref bean="sslCheckInterceptor"/> </list> </property> </bean>
딱 찾던 글이었습니다. 감사합니다.
도움이 됐다니 좋네요~^^