▼ Backend/스프링 (Spring)

Spring Boot | 인터셉터(Interceptor) 적용하기

Valar 2021. 8. 4. 14:55
반응형

▶ 인터셉터(Interceptor)

컨트롤러(Controller)의 핸들러(Handler)를 호출하기 전 또는 후에 요청(HttpServletRequest)과

응답(HttpServletResponse)을 가로채는 역할

 

사용자 인증이 되어 있어야 사용 가능한 페이지에 주로 사용된다.

예) 웹 사이트를 사용하다가 마이페이지나 개인적인 메뉴에 접근할 경우 요청을 가로채 로그인이 되어 있지 않으면 로그인 페이지로 이동 시키는데 많이 사용된다.

 

LoginInterceptor

HandlerInterceptor를 상속받아 interface 메서드를 구현한다.

 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

    // 클라이언트의 요청을 컨트롤러에 전달하기 전에 호출된다. 여기서 false를 리턴하면 다음 내용(Controller)을 실행하지 않는다.
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	System.out.println("#Interceptor PreHandle Method Req URI : " + request.getRequestURI());
        /*
          이 영역에서 인증여부를 판단하여 로그인 페이지로 보낼 로직을 구현한다.
        */
        
        return true;
    }
 
    // 클라이언트의 요청을 처리한 뒤에 호출된다. 컨트롤러에서 예외가 발생되면 실행되지 않는다.
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
    }
 
    // afterCompletion : 클라이언트 요청을 마치고 클라이언트에서 뷰를 통해 응답을 전송한뒤 실행이 된다. 뷰를 생성할 때에 예외가 발생할 경우에도 실행이 된다.
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // TODO Auto-generated method stub
    }
}

 

WebConfig

WebMvcConfigurer를 상속 받아 addInterceptors 메서드를 구현한다.

 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.melon.boot.interceptor.LoginInterceptor;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()) // LoginInterceptor
            .addPathPatterns("/**") // 적용할 URL (모든 URL 적용)
            .excludePathPatterns("/login/**"); // 제외할 URL (/login/하위로 오는 URL 제외)
    }
}

 

반응형