아키텍처와 함께

블로그 이미지
by gregorio
  • Total hit
  • Today hit
  • Yesterday hit

Spring Boot에서 Interceptor를 적용하는 방법이다.


먼저 Spring MVC에서는 Interceptor를 적용하기 위해서 HandlerInterceptorAdapter를 상속받아 Interceptor를 개발한다.


■SessionInterceptor.java


 import java.util.List;

import java.util.Map;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.InitializingBean;

import org.springframework.stereotype.Component;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


import dymn.demo.base.BaseConstants;

import dymn.demo.exception.BizException;

import dymn.demo.util.NetUtil;

import dymn.demo.util.NullUtil;

import dymn.demo.util.PatternUtil;

import dymn.demo.util.SessionUtil;


public class SessionInterceptor extends HandlerInterceptorAdapter implements InitializingBean{

private static final Logger LOGGER = LoggerFactory.getLogger(SessionInterceptor.class);

// private static final String sApiKey = "B69FAF368B184727E89A";

/** Login Check Skip URIs **/

private List<String> skipUris;

/** LOGIN URL **/

private String loginURI;


public void setSkipUris(List<String> skipUris) {

this.skipUris = skipUris;

}


public void setLoginURI(String loginURI) {

this.loginURI = loginURI;

}


/**

* Return boolean

* @param request HttpServletRequest

* @param response HttpServletResponse

* @param Object handler

* @return boolean

* @see 

*/


@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

String requestURI = request.getRequestURI();


long startTime = System.currentTimeMillis();

request.setAttribute("startTime", Long.valueOf(startTime));

request.setAttribute("requestURI", requestURI);

request.setAttribute("clientIP", NetUtil.getClinetIP());

/** Session Vo Check if null create new session Vo **/

boolean isSkipUri = false;

if (requestURI.equals("/") ) {

isSkipUri = true;

}

else {

if (!NullUtil.isNull(skipUris)) {

isSkipUri = PatternUtil.isPatternMatch(skipUris, requestURI);

}

}

/** Login Check **/

if (!isSkipUri) {

/** Get session value from HTTP Session **/

Map<String, Object> session = SessionUtil.getSession(BaseConstants.DEFAULT_SESSION_NAME);

/** Move to Login Page **/

if (NullUtil.isNull(session)) {

String contentType = request.getHeader("Content-Type") != null ? request.getHeader("Content-Type") : "";

if (!contentType.contains("json")) {

response.sendRedirect(loginURI);

}

LOGGER.error("You shoud logon the system to use the system(session is null) :: {}", requestURI);

throw new BizException("You shoud logon the system to use the system(session is null)");

}

else {

if (NullUtil.isNull(session.get("userId"))) {

String contentType = request.getHeader("Content-Type");

if (!contentType.contains("json")) {

response.sendRedirect(loginURI);

}

LOGGER.error("You shoud logon the system to use the system(userId is null) :: {}", requestURI);

throw new BizException("You shoud logon the system to use the system(userId is null)");

}

}

}

return super.preHandle(request, response, handler);

}


/**

* Return void

* @param request HttpServletRequest

* @param response HttpServletResponse

* @paeam Object handler

* @return void

* @see

*/

@Override

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav) throws Exception {


}


/**

*/

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {


String requestURI = request.getAttribute("requestURI").toString();


if (LOGGER.isDebugEnabled()) {

LOGGER.debug("Session Interceptor is called : {}", requestURI);

}

/** If request URI is login or logout, set host name, host address  to session information 

*  When logout, session information is invalidated

* */



long startTime = (Long) request.getAttribute("startTime");

long endTime = System.currentTimeMillis();

LOGGER.info("Request URL::{} Request ClinetIP::{} Response Code::{} Start Time::{} End Time::{}  Elapse Time::{}(ms)",

requestURI, request.getAttribute("clientIP"), response.getStatus(), startTime, endTime, (endTime - startTime));

}



@Override

public void afterPropertiesSet() throws Exception {

}


}



코드 개발이 완료되면 mvc-servlet-context.xml에 Interceptor를 등록한다.


■mvc-servlet-context.xml


     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">

        <property name="interceptors">

            <list>

                <ref bean="localeChangeInterceptor" />

                <ref bean="sessionInteceptor" />

            </list>

        </property>

    </bean>



<!-- Set the login check, block service and authorization for menu -->

<bean id="sessionInteceptor" class="batch.web.interceptor.SessionInterceptor">

<property name="skipUris">

<list>

<value>/login/*</value>

</list>

</property>

<property name="loginURI" value="/main/mainpage.do" />

<!-- The beans are configured in context-beans.xml file  -->

<!-- This is blocking service  -->

<!-- property name="blockServiceName" value="blockService" /-->

<!-- This is checking for unauthorized url -->

<!-- property name="authCheckServiceName" value="authCheckService" /-->

</bean>



Spring Boot에서 Interceptor 개발은 동일하며, @Component Annotation을 이용하여 bean으로 등록한다.


bean으로 등록하는 이유는 해당 Interceptor를 bean으로 사용하기 위해서 이다.


■WebConfig.java


import java.util.ArrayList;

import java.util.List;

import java.util.Locale;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.web.servlet.FilterRegistrationBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.support.ReloadableResourceBundleMessageSource;

import org.springframework.core.Ordered;

import org.springframework.web.servlet.LocaleResolver;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import org.springframework.web.servlet.view.json.MappingJackson2JsonView;


import dymn.demo.filter.ABCFilter;

import dymn.demo.interceptor.SessionInterceptor;

import dymn.demo.util.PropertiesUtil;


@Configuration

// @EnableWebMvc

// public class WebConfig extends WebMvcConfigurerAdapter {

// public class WebConfig extends WebMvcConfigurationSupport {

public class WebConfig implements WebMvcConfigurer {


@Autowired

private SessionInterceptor sessionInterceptor;


@Autowired

private ABCFilter abcFilter;



/** Register intercepter **/

@Override

public void addInterceptors(InterceptorRegistry registry) {

List<String> skipUris = new ArrayList<String>();


String[] uris = PropertiesUtil.getString("session.skip.uri").split(",");

;

for (String uri : uris) {

skipUris.add(uri);

}

sessionInterceptor.setSkipUris(skipUris);

registry.addInterceptor(sessionInterceptor);

// .addPathPatterns("/*");

// .excludePathPatterns(skipUris);

}

}

 


Spring MVC에서 sessionInterceptor bean 등록 시 skipUrl 주입하였으나, Spring Boot에서는 Properties 파일에 session.skip.uri 값을 읽어 sessionInterceptor에 주입한다.


그리고 InterceptorRegistry를 이용하여 sessionItnerceptor를 Interceptor로 등록한다.



AND

ARTICLE CATEGORY

분류 전체보기 (56)
Spring Framrwork (33)
Linux (1)
APM (1)
Java (8)
python (0)
ant (1)
chart (1)
OS (1)
tomcat (1)
apache (1)
database (0)

RECENT ARTICLE

RECENT COMMENT

CALENDAR

«   2024/10   »
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

ARCHIVE

LINK