[백업][가리사니] 스프링 i18n (다국어) : 1. 기본설정 및 타임리프에 적용
java, spring

이 문서는 가리사니 개발자 포럼에 올렸던 글의 백업 파일입니다. 오래된 문서가 많아 현재 상황과 맞지 않을 수 있습니다.

스프링 i18n (다국어) 시리즈

1. 기본설정

import java.util.Locale;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class I18nConfig extends WebMvcConfigurerAdapter {
	@Bean
	public LocaleResolver localeResolver() {
		// 쿠키를 사용한 예제
		CookieLocaleResolver resolver = new CookieLocaleResolver();
		resolver.setCookieName("lang");
		return resolver;
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
		localeChangeInterceptor.setParamName("lang");
		registry.addInterceptor(localeChangeInterceptor);
	}

	@Bean
	public MessageSource messageSource() {
		ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
		messageSource.setBasename("classpath:/i18n/messages");
		messageSource.setDefaultEncoding("UTF-8");
		return messageSource;
	}
}
MessageSource messageSource()

메시지 소스를 설정합니다. 위와같이 설정된 경우 아래처럼 세팅해줍니다.

  • 리소스/i18n/messages.properties (기본값)
  • 리소스/i18n/messages_ko.properties (한국어)
  • 리소스/i18n/messages_{언어코드}.properties

localeResolver 을 설정합니다.

void addInterceptors(InterceptorRegistry registry)

언어 변경시 파라미터를 설정합니다. 위와 같이 설정된 경우 ?lang={언어코드} 로 언어를 바꿀 수 있습니다.

LocaleResolver localeResolver()

이 부분의 설명은 다음장에서 다루도록 하겠습니다.

메시지 설정

리소스/i18n/messages_ko.properties

title: 타이틀(한국어)
hello: 안녕
home: 홈

리소스/i18n/messages_en.properties

# 기본값을 확인하기위해 타이틀을 제거하였습니다.
hello: hello
home: home

뷰 (타임리프)

템플릿/main.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"/>
	<title th:text="#{title}"></title>
</head>
<body>
<div>

	<h1 th:text="#{home}"></h1>
	<h2 th:text="#{hello}"></h2>

	<a href="?lang=ko">한국어</a>
	<a href="?lang=en">영어</a>

</div>
</body>
</html>

컨트롤러

  • 타임리프가 알아서 잡아주기 때문에 특별히 할일이 없습니다.
@RequestMapping(path = "/")
public String root() {
	return "main";
}