ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring] 게시판 만들기(11) - 인터셉터(Interceptor) 설정
    Spring/4.3.x - 게시판 만들기 2018. 12. 14. 09:33
    반응형

     인터셉터를 지원하는 추상클래스 HandlerInterceptorAdaptor는 preHandler(), postHandle(), afterCompletion() 3가지 메서드를 지원하며, preHandler()과 postHandle()는 전처리기와 후처리기에 역할을 수행하며, preHandler()은 컨트롤러가 호출되기 전에 실행되고, postHandle()은 컨트롤러가 실행되고 난 후에 호출됩니다. 

     컨트롤러 실행 전이나 후에 공통적인 작업을 처리할 수 있는 HandlerInterceptorAdaptor를 상속받아 인터셉터를 설정하는 작업을 진행하도록 하겠습니다. 

     

    1. HandlerInterceptorAdapter를 상속받아 구현할 자바 파일을 생성

    1_1. src/main/java 폴더 com.spring.board 패키지에 common 폴더를 생성한 후 LoggerInterceptor.java 파일을 추가하세요.

    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
    32
    33
    34
    35
    36
    37
    38
    39
    40
    package com.spring.board.common;
     
    import java.util.Enumeration;
     
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
     
    public class LoggerInterceptor extends HandlerInterceptorAdapter {
     
        protected final Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);
     
        @SuppressWarnings("rawtypes")
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            logger.debug("==================== LoggerInterceptor START ====================");
            logger.debug(" URI [{}]," + request.getRequestURI());
     
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String key = (String) paramNames.nextElement();
                String value = request.getParameter(key);
                logger.debug(" RequestParameter Data ==>  " + key + " : " + value + "");
            }
     
            return super.preHandle(request, response, handler);
        }
     
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
                throws Exception {
     
            logger.debug("==================== LoggerInterceptor END ====================");
        }
    }
     
    cs

     

     

     

    2. servlet-context.xml 설정 추가

    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
    32
    33
    34
    35
    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns="http://www.springframework.org/schema/mvc"
        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: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
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
     
        <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
        
        <!-- Enables the Spring MVC @Controller programming model -->
        <annotation-driven />
     
        <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
        <resources mapping="/resources/**" location="/resources/" />
     
        <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
        <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <beans:property name="prefix" value="/WEB-INF/views/" />
            <beans:property name="suffix" value=".jsp" />
        </beans:bean>
        
        <context:component-scan base-package="com.spring.board" />
        
        <mvc:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/**"/>
                <beans:bean id="loggerInterceptor" class="com.spring.board.common.LoggerInterceptor"></beans:bean>
            </mvc:interceptor>
        </mvc:interceptors>
        
    </beans:beans>
    cs

     

     

    3. 인터셉터(Interceptor) 설정 확인
    3_1. localhost:9090/board/sample/getSample 호출 시에 preHandle(), postHandle() 메서드가 호출되는지 확인하세요. 

     

    소스 코드는 Github Repository - https://github.com/tychejin1218/board_v1 (branch : section11) 를 참조하세요.
    Github에서 프로젝트 가져오기 - https://tychejin.tistory.com/33

     

     

    반응형

    댓글

Designed by Tistory.