spring

Spring Interceptor 설정

초이짬 2017. 1. 2. 13:55
728x90

기본 전제는 Spring 3.2 이상으로 본다. interceptor 의 예외처리기능도 사용하기 위해서(최소사양)

설정 파일(xml) 에서 기본적으로 전체 annotaion 을 읽는 기준이다 같은 설정 파일에 존재해야
정상동작한다. spring설정 파일은 여러개지만 한곳에만 전체를 읽어서 되진 않고 동일 설정 파일
상에 anntaion scan 이 되고 난 후에 interceptor를 읽는다고 보면 된다.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="">http://www.springframework.org/schema/beans"
xmlns:xsi="">http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="">http://www.springframework.org/schema/beans"
xmlns:context="">http://www.springframework.org/schema/context"
xmlns:p="">http://www.springframework.org/schema/p"
xmlns:mvc="">http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context ">http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven />

위의 설정 구문에서
xmlns:mvc="
http://www.springframework.org/schema/mvc">http://www.springframework.org/schema/mvc"

http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd

<mvc:annotation-driven
/>

이렇게 3개 라인이 기본 동작은 해야 interceptor 가 동작한다

그리고 아래 설정 구문이 실제 interceptor의 설정이다.

<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- <mvc:exclude-mapping path="/kr/co/example/get**"/> -->
<mvc:exclude-mapping path="/**/ajax**"/>
<mvc:exclude-mapping path="/kr/co/example/downloadFile.do"/>
<bean class="kr.co.example.com.Interceptor"/>
</mvc:interceptor>
</mvc:interceptors>

위 구문중 첫째 구분인 <mvc:mapping path="/**"/> 이 부분이 전체 스캔이고

<mvc:exclude-mapping path="/**/ajax**"/> 이 구문이 예외 처리이다.

예외 처리 패턴은 /**/ajax** 요 구문의 경우는 상단 url 패턴 자체가 urI 시작이 /**/**/**/ajax 등으로 시작하는
모든 패턴은 예외 하겟다는 것이니 참고 하면 된다.

인터셉터에서 예외 처리를 염두에 둘 경우 ajax나 이런류는 프로젝트 시작시에 미리 정의 하여 주소를 정의하고 시작

하는것이 나중에 더 효율적일 것이다.



추가로 인터셉터 클래스를 생성하고 extends HandlerInterceptorAdapter 를 상속하면


@Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
   throws Exception {
  // TODO Auto-generated method stub
  return super.preHandle(request, response, handler);
 }

 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
   ModelAndView modelAndView) throws Exception {
  // TODO Auto-generated method stub
  super.postHandle(request, response, handler, modelAndView);
 }
 
 @Override
 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
   throws Exception {
  // TODO Auto-generated method stub
  super.afterCompletion(request, response, handler, ex);
 }


이렇게 3개의 주요 메쏘드(상속박고 Ctrl+Space눌르면 나옴) 사용할수 있다


preHandle - 이벤트 호출전

postHandle - 이벤트 호출후 view 출력전

afterCompletion - view 출력 후

728x90