Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

Formoat's Open Blog

Interceptor - 인터셉터 본문

Java/Spring

Interceptor - 인터셉터

snd-snd 2019. 10. 16. 16:28

# 인터셉터 (Interceptor)

 

- 특정 URL 요청시 컨트롤러로 가는 요청을 가로채는 역할

- 다수 컨트롤러에 대해 동일한 기능을 제공한다. 

 

인터셉터는 주로 로그인후 사용이 가능한 페이지 접근에 많이 사용이 되는데,

인터셉터를 사용하지 않을경우 게시물 작성, 수정, 삭제 등의 페이지에 로그인 기록(세션)이 남아 있는지

확인하는 코드를 모든 페이지에 작성해야 한다. 이를 인터셉터를 이용해 페이지를 가로채 먼저

로그인 기록(세션)이 남아있는지를 체크한다면 중복되는 코드를 줄일 수 있다.

 


# 스프링 인터셉터 처리

 

HandlerInterceptor  AsyncHandlerInterceptor ← HandlerInterceptorAdapter

 

- 스프링에서는 HandlerInterceptorAdapter 추상클래스를 제공하며, 이 추상클래스를 상속받아 구현하는

인터셉터 클래스를 만들어 기능을 처리하게 된다. HandlerInterceptorAdapter 추상클래스는 3가지

주요 메서드를 가지고 있는데 상세 내용은 아래와 같다.

 

Method Description
preHandel

컨트롤러로 요청하기 전에 수행되는 메서드로 로그인 정보를 확인하거나, 컨트롤러로 들어가기 전

필요한 정보를 생성할 때 사용된다. 그리고 반환값에 의해 postHandle 호출 여부를 결정한다.

postHandle

컨트롤러의 처리가 끝난 뒤 결과를 보여줄 VIew를 찾기전 수행되는 메서드로 컨트롤러에서 전달한

Model 객체를 ModelAndView로 가지고 있다. 추가적인 작업이 남아있다면 이 객체를 사용하게 된다.

preHandel에서 false를 반환하거나, 컨트롤러 수행중 익셉션이 발생한다면 호출되지 않는다.

afterCompletion 컨트롤러, 뷰 응답 처리까지 끝난 뒤 수행되는 메서드

 


# 구현 방법

 

1) 인터셉터 설정 정보 등록 (servlet-context.xml)

<!-- interceptor 설정 -->
<beans:bean id="sampleInterceptor" class="com.spring.controller.SampleInterceptor"/>
<interceptors>
	<interceptor>
		<mapping path="/doA"/> <!-- 위와 같은 URL 요청이 있을 경우 인터셉터가 가로챔 -->
		<mapping path="/doB"/>
		<mapping path="/doC"/>
		<beans:ref bean="sampleInterceptor"/>
	</interceptor>
</interceptors>

<context:component-scan base-package="com.spring.controller" />

 

2) 인터셉터 클래스 생성

public class SampleInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("등록된 URL의 요청을 가로채 컨트롤러가 실행되기 전 호출");
		
		return true; //postHandle 실행 여부를 지정
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("컨트롤러 처리작업 후 호출되며, 추가적인 작업이 있을 경우 ModelAndView를 이용해 처리");
		
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("사용자에게 뷰까지 띄워준 이후 호출");
	}	
}

 

3) 인터셉터 실행 흐름 확인

 

Comments