### 참고 : https://justinrodenbostel.com/2014/05/13/part-4-internationalization-in-spring-boot/
### Spring Boot internationalization
    1. message.properties 생성
        - messages.properties
        - messages_en.properties
        - messages_ko.properties
    2. I18nConfiguration 생성
    3. hello.html 작성
### messages.properties
    msg_hello = Hello
    msg_world = World
    msg_complex = Good morning {0}!
### messages_en.properties
    msg_hello = Hello
    msg_world = World
    msg_complex = Good morning {0}!
### messages_ko.properties
    msg_hello = 안녕
    msg_world = 세계
    msg_complex = 좋은아침 {0}!
### I18nConfiguration.java
```java
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
/**
 * 로케일 처리 순서
 * 1. 웹 요청의 로케일을 확인
 *   1.1) 로케일 리졸버의 방식에 따라 세션 또는 쿠키에서 로케일 확인
 *   1.2) 세션 또는 쿠키에서 로케일 확인이 안될 때(ex.첫 요청등)는 브라우저가 보내는 로케일 확인
 *     1.2.1) 단, Resolver의 DefaultLocale이 설정되어 있을 경우 해당 값으로 덮어쓰기
 * 2. 로케일에 맞는 메세지 파일의 값을 호출
 * 3. 로케일에 맞는 메세지 파일이 없는 경우
 *   3.1) FallBackToSystemLocale이 true(기본값)인 경우
 *     3.1.1) 시스템 로케일에 맞는 메세지 파일의 값을 호출
 *     3.1.2) 못찾았을 경우 기본 메세지 파일(messages.properties)의 값을 호출
 *   3.2) FallBackToSystemLocale이 false인 경우
 *     3.2.1) 기본 메세지 파일(messages.properties)의 값을 호출
 * 4. 로케일에 맞는 메세지 파일이 없거나 값을 못찾았을 경우 예외 발생
 */
@Configuration
public class I18nConfiguration extends WebMvcConfigurerAdapter {
	@Bean
	public MessageSource messageSource() {
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		messageSource.setBasename("i18n/messages"); // in classpath
		messageSource.setDefaultEncoding("UTF-8");
		messageSource.setFallbackToSystemLocale(false);
		return messageSource;
	}
	@Bean
	public LocaleResolver localeResolver() {
		SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        /* CookieLocaleResolver localeResolver = new CookieLocaleResolver();
        localeResolver.setCookieName("my-locale-cookie");
        localeResolver.setCookieMaxAge(3600); // in second (-1: deleted when client shuts down) */
		localeResolver.setDefaultLocale(Locale.KOREAN);
		return localeResolver;
	}
	@Bean
	public LocaleChangeInterceptor localeChangeInterceptor() {
		LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
		interceptor.setParamName("lang"); // default: "locale"
		return interceptor;
	}
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(localeChangeInterceptor());
	}
}
```
### /src/main/resources/hello.html
 readLines = IOUtils.readLines(inputStream);
      IOUtils.writeLines(readLines, null, outputStream);
      IOUtils.closeQuietly(inputStream);
      IOUtils.closeQuietly(outputStream);
    }
}   
```
 
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8" />
    <title>HELLO</title>
</head>
<body>
<h1 th:text="#{msg_complex}">바다</h1><br/>
<h1 th:text="#{msg_hello}">안녕~~~</h1><br/>
<h1 th:text="#{msg_world}">세계~~~</h1><br/>
<br/>
<a href="?lang=en">English</a><br/>
<a href="?lang=ko">Korea</a><br/>
</body>
</html>
### test
    http://localhost:8080/hello.html
    http://localhost:8080/hello.html?lang=en
    http://localhost:8080/hello.html?lang=ko
### javascript에서 다국어 메시지 참조(jquery.i18n.properties.js)
    참고 : http://aretias.egloos.com/970593
    
    1. I18nController 생성
    2. Download jquery.i18n.properties.js
       https://github.com/jquery-i18n-properties/jquery-i18n-properties
    3. hello.html 작성
```java
@RestController
public class I18nController {
    @RequestMapping("/properties/{propertiesName}")
    public void getProperties(@PathVariable String propertiesName, HttpServletResponse response) throws IOException
    {
      OutputStream outputStream = response.getOutputStream();
      Resource resource = new ClassPathResource("/i18n/" + propertiesName + ".properties");
      //		Resource resource = new ClassPathResource("/i18n/" + propertiesName );
      InputStream inputStream = resource.getInputStream();
      List
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8" />
    <title>HELLO</title>
    <script type="text/javascript" src="/js/prevision/jquery.i18n.properties.js"></script>
    <script>
        jQuery.i18n.properties({
            name:'messages',
            path:'/properties/',
            mode:'map',
            language:'${lang}',
            callback: function () {
                jQuery.i18n.prop('msg_hello');
                jQuery.i18n.prop('msg_complex', 'John');
            }
        });
        function i18n(msg) {
            var args = "\""+ msg + "\"";
            for (var i = 1; i < arguments.length; i++) {
                args += ", \"" + arguments[i] + "\"";
            }
            if (parent != this) {
                return eval("parent.i18n(" + args + ")");
            }
            return eval("jQuery.i18n.prop(" + args + ")");
        }
        window.onload = function() {
            alert(i18n("msg_hello") + " / " + i18n("msg_world"));
            alert(i18n("msg_complex","바둑아"));
        }
    </script>
</head>
<body>
<h1 th:text="#{msg_complex}">바다</h1><br/>
<h1 th:text="#{msg_hello}">안녕~~~</h1><br/>
<h1 th:text="#{msg_world}">세계~~~</h1><br/>
<br/>
<a href="?lang=en">English</a><br/>
<a href="?lang=ko">Korea</a><br/>
</body>
</html>
### test
    http://localhost:8080/hello.html
'java' 카테고리의 다른 글
| Singletone Design Pattern (0) | 2019.01.30 | 
|---|---|
| Adapter Design Pattern (0) | 2019.01.30 | 
| 상관관계 분석(Correlation Analysis)? (0) | 2019.01.29 | 
| kmeans (0) | 2019.01.29 | 
| spring_sqlmap_selectkey (0) | 2019.01.29 | 

댓글