Interceptor

2018. 10. 27. 18:04·Spring Framework/Spring
반응형
[Spring]Interceptor

Interceptor

  • interceptor를 통해 뷰의 공통적인 부분을 묶을 수 있다. 이를 통해 사용자 세션, 쿠키를 확인하거나 로그를 남기는 등 여러 작업을 할 수 있다.
interface CookieValidator {
    void checkUser(email);
}

컨트롤러에서 이 인터페이스를 상속받아 사용하면 된다.

인터셉터 작성

​x
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
​
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
​
        String email = getEmailInCookie(request.getCookies());
​
        HandlerMethod method = (HandlerMethod)handler;
        if (method.getBean() instanceof ViewController) {
            ViewController vc = (ViewController)method.getBean();
            vc.setUserEmail(email);
        }
​
        return true;
    }
​
    private String getEmailInCookie(Cookie[] cookies) {
        if (cookies == null) {
            return null;
        }
​
        for (Cookie cookie : cookies) {
            if ("email".equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
​
        return null;
    }
}

preHandle메소드를 통해 컨트롤러 처리 이전의 작업을 수행한다. 여기서 이전에 작성한 인터페이스를 수행시킨다.

인터셉터 등록

인터셉터를 config에 등록해야한다. 자바 MVC Config 클래스에 다음을 오버라이드 하면 된다.

x
​
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthorizationInterceptor());
    }
​

 

반응형
저작자표시 비영리 변경금지 (새창열림)
'Spring Framework/Spring' 카테고리의 다른 글
  • [Spring Batch] 메타 데이터 테이블 정리
  • [Spring Batch] skip / retry
  • [Spring Boot] 자동 설정(Auto Configuration)
  • [JPA] 연관 관계
덴마크초코우유
덴마크초코우유
IT, 알고리즘, 프로그래밍 언어, 자료구조 등 정리
    반응형
  • 덴마크초코우유
    이것저것끄적
    덴마크초코우유
  • 전체
    오늘
    어제
    • 분류 전체보기 (124)
      • Spring Framework (10)
        • Spring (5)
        • JPA (3)
        • Spring Security (0)
      • Language (51)
        • Java (11)
        • Python (10)
        • JavaScript (5)
        • NUXT (2)
        • C C++ (15)
        • PHP (8)
      • DB (16)
        • MySQL (10)
        • Reids (3)
        • Memcached (2)
      • 개발 (3)
      • 프로젝트 (2)
      • Book (2)
      • PS (15)
        • 기타 (2)
        • 백준 (2)
        • 프로그래머스 (10)
      • 딥러닝 (8)
        • CUDA (0)
        • Pytorch (0)
        • 모델 (0)
        • 컴퓨터 비전 (4)
        • OpenCV (1)
      • 기타 (16)
        • 디자인패턴 (2)
        • UnrealEngine (8)
        • ubuntu (1)
        • node.js (1)
        • 블로그 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    클래스
    블루프린트
    mscoco
    C++
    Unreal Engine
    PS
    select
    NUXT
    JavaScript
    자바
    MySQL
    CPP
    FPS
    언리얼엔진4
    파이썬
    map
    Unreal
    게임
    웹
    C
    프로그래머스
    pytorch
    JS
    딥러닝
    memcached
    php
    Python
    redis
    게임 개발
    알고리즘
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
덴마크초코우유
Interceptor
상단으로

티스토리툴바