Java/Spring

Spring에서 MessageUtil 사용하기

체리필터 2015. 2. 24. 14:18
728x90
반응형

다국어 사용을 위해서 그동안 Struts2 기반 MessageUtil만 사용하다가 Spring 기반으로 변경하기 위해 구글링, 작업한 내용을 정리 차원에서 올립니다.

 

1. applicationContext.xml에 다음 내용을 추가

 

<!-- for MessageUtil -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
	<property name="basenames">
		<list>
			<value>/WEB-INF/messages/messages</value>
		</list>
	</property>
	<property name="cacheSeconds" value="100000" />
	<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="messageSourceAccessor" class="org.springframework.context.support.MessageSourceAccessor">
	<constructor-arg ref="messageSource"/>
</bean>
<bean id="messageUtil" class="package.path.MessageUtil">
	<property name="messageSourceAccessor" ref="messageSourceAccessor"/>
</bean>

 

2. MessageUtil

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class MessageUtil {
	private static MessageSourceAccessor messageSourceAccessor = null;
     
    public void setMessageSourceAccessor(MessageSourceAccessor msAcc) {
		this.messageSourceAccessor = msAcc;
	}

	public static Locale getLocale() {

		Locale defaultLocale = Locale.ENGLISH;

		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String headerLocale = request.getHeader("Accept-Language");

		if (StringUtils.isNotBlank(headerLocale)) {
			if (headerLocale.indexOf(Locale.JAPAN.getLanguage()) != -1) {
				defaultLocale = Locale.JAPAN;
			} else if (headerLocale.indexOf(Locale.KOREA.getLanguage()) != -1) {
				defaultLocale = Locale.KOREA;
			}
		}

		return defaultLocale;
	}

	public static String getMessage(String key) {
		return messageSourceAccessor.getMessage(key, getLocale());
	}

	public static String getMessage(String key, Object... args) {
		return messageSourceAccessor.getMessage(key, args, getLocale());
	}

	public static String getMessage(Locale locale, String key, Object... args) {
		return messageSourceAccessor.getMessage(key, args, locale);
	}
}

 

 

참고 사이트

http://springsource.tistory.com/113

http://blog.naver.com/pureb612b/10120505318

http://zinlee.tistory.com/204

728x90
반응형