본문 바로가기

개발/Spring

스프링 인터셉터(Interceptor)

728x90
반응형
인터셉터

 

인터셉터(Interceptor)는 필터와 비슷한 기능을 하지만 필터는 웹 애플리케이션의 특정한 위치에서만 동작하는 데 반해 인터셉터는 좀 더 자유롭게 위치를 변경해서 기능을 수행할 수 있습니다.
즉 인터셉터는 애플리케이션 안에서 적용 범위를 설정할 수 잇습니다.


인터셉터를 사용하면 브라우저 요청이 있을 때 요청 메서드 호출 전후에 원하는 기능을 수행할 수 있습니다.
주로 쿠키(cookie) 제어, 파일 업로드 등의 작업에 사용합니다.

 

[ 스프링 HandlerInterceptor 여러가지 메서드 ]

 

메서드 기능
preHandle() 컨트롤러 실행 전 호출됩니다.
postHandle() 컨트롤러 실행 후 DispatcherServlet 이 View 로 보내기 전에 호출됩니다.
afterCompletion() View 까지 실행하고 난 후 호출됩니다.

 

 

 

인터셉터를 이용한 다국어 기능

 

[ WEB-INF/spring/servlet-context.xml ]

 

<?xml version="1.0" encoding="UTF-8"?>
<!-- <mvc: ..> 태그를 사용하기 위해 추가 -->
<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:mvc="http://www.springframework.org/schema/mvc"
	
	xmlns:context="http://www.springframework.org/schema/context"
	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">

	<!-- 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.myspring.myproject" />

	<!-- 인터셉터 기능을 사용하도록 설정 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<!-- 특정요청 /test/*.do 에 대해서만 인터셉터 빈을 수행 -->
			<mvc:mapping path="/test/*.do" />
			<!-- 모든 요청에 대해 인터셉터 빈을 수행 -->
			<mvc:mapping path="/*/*.do" />
			<!-- 인터셉터 기능을 수행할 빈을 설정 -->
			<beans:bean class="com.myspring.myproject.LocaleInterceptor" />
		</mvc:interceptor>
	</mvc:interceptors>
</beans:beans>

 

 

[ /WEB-INF/spring/message-context.xml ]

 

ReloadableResourceBundleMessageSource 클래스를 사용해 message 프로퍼티 파일을 읽어 들이면 다국어 기능을 사용할 수 있습니다.

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- 스프링의 SessionLocalResolver 클래스를 이용해 locale 정보를 세선에 저장해서 사용 -->
	<bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basenames">
			<list>
				<!-- message.properties 를 패키지 locale 에서 읽어들임 -->
				<value>classpath:locale/messages</value>
			</list>
		</property>
		<!-- 파일의 기본 인코딩 지정 -->
		<property name="defaultEncoding" value="UTF-8" />
		<!-- properties 파일이 변경되었는지 확인 주기 지정(60초) -->
		<property name="cacheSeconds" value="60" />
	</bean>
</beans>

 

 

[ /src/main/java/myspring/myproject/LocaleInterceptor.java ]

 

...

// HandlerInterceptorAdapter 상속
public class LocaleInterceptor extends HandlerInterceptorAdapter {
	@Override
	// 컨트롤러 실행 전 호출 ... (컨트롤러는 뷰만 반환)
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		HttpSession session = request.getSession();
		// 브라우저에서 전달한 locale 정보를 가져옴
		String locale = request.getParameter("locale");
		// locale 이 없을 경우 기본값으로 "ko" 지정(최초 요청시)
		if (locale == null)
			locale = "ko";
		// LOCALE 속성 값을 세션에 저장해 SessionLocaleResolver 가 사용 가능
		session.setAttribute("org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE", new Locale(locale));
		return true;
	}
...
}

 

 

[ WEB-INF/views/locale.jsp ]

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import="java.io.*" pageEncoding="UTF-8" isELIgnored="false"%>
<!-- <spring:message> 태그를 사용할 수 있게 설정 -->
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
request.setCharacterEncoding("UTF-8");
%>

<!DOCTYPE html >
<html>
<head>
<meta charset="UTF-8">
<title><spring:message code="site.title" text="Member Info" /></title>
</head>
<body>
	<!-- locale "ko" 요청 -->
	<a href="${pageContext.request.contextPath }/test/locale.do?locale=ko">한국어</a>
	<!-- locale "en" 요청 -->
	<a href="${pageContext.request.contextPath }/test/locale.do?locale=en">ENGLISH</a>
	<h1>
		<spring:message code="site.title" text="Member Info" />
	</h1>
	<p>
    	<!-- <spring:message> 태그를 이용해 각 항목에 맞는 값과 없을때 기본값 설정 -->
		<spring:message code="site.name" text="no name" />
		:
		<spring:message code="name" text="no name" />
	</p>
	<p>
		<spring:message code="site.job" text="no job" />
		:
		<spring:message code="job" text="no job" />
	</p>


	<input type=button value="<spring:message code='btn.send' />" />
	<input type=button value="<spring:message code='btn.cancel' />" />
	<input type=button value="<spring:message code='btn.finish' />" />

</body>
</html>

 

<spring:message> 태그의 사용 형식은 다음과 같습니다.

 

<spring:message code="properties key" text = "기본값" />

 

한국어와 ENGLISH 링크를 클릭하면 각 locale 에 맞게 내용이 출려됩니다.

728x90