Spring Boot 에서 messages.properties 을 이용한 다국어 처리 (4)
2019/01/29 - [Programming/Spring Boot 시작하기] - Spring Boot 에서 messages.properties 을 이용한 다국어 처리 (3)
쿠키로 관리되고 매개변수로 그 값을 변경하는 것이 완벽히 이해가 안된다면 간단한 예제 프로그램을 만들어 보는 것이 좋습니다.
- 각자 편한 대로 Spring Boot 프로젝트를 만듭니다. 이 때 Web 와 Thymeleaf 만 선택합니다.
- 호출할 간단한 Controller 을 만듭니다. 앞 선 예제와 같이 MessageConfig 와 WebMvcConfig 도 만들어줍니다.
- 다국어 출력을 위해 Thymeleaf 기반의 HTML 하나와 messages.properties, messages_ko_KR.properties, messages_en_US.properties 도 만들어줍니다.
아래와 같은 모습으로 프로젝트가 생성되었을 것입니다.
TestContoller 에는 아래와 같이 간단하게 /test 요청을 받을 수 있도록 합니다.
@RequestMapping("") @Controller public class TestController { @RequestMapping("/test") public String test() { return "test"; } }
MessageConfig 에는 Cookie 기반으로 저장하고 매개변수로 들어온 값을 Locale 로 처리할 수 있도록 설정을 합니다.
@Configuration public class MessageConfig { @Bean public LocaleResolver localeResolver() { // 쿠키 기반 지역 선택 CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setCookieName("cookie_language"); return resolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor(); interceptor.setParamName("cookie_language"); return interceptor; } }
WebMvcConfig 에서는 수정한 LocalChangeInterceptor 을 WebMvcConfigurer#addInterceptors 에 등록합니다.
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Autowired private LocaleChangeInterceptor localeChangeInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { localeChangeInterceptor.setParamName("cookie_language"); localeChangeInterceptor.setHttpMethods("GET"); registry.addInterceptor(localeChangeInterceptor); } }
messages.properties 등에는 다음과 같이 다국어를 등록해둡니다.
마지막으로 test.html 에서 메세지를 출력하도록 다음과 같이 구현합니다.
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <span th:text="#{test_ok}"> </body> </html>
그리고 프로젝트를 실행한 뒤 브라우져에서 호출해봅니다.
Cookie 가 생성되어 있지 않지만 한글로 출력됩니다.
이제, 영어로 바꾸어 보겠습니다.
Query String 에 en_US 을 등록했더니 영어로 출력됩니다.
한국어로 강제로 변경해보겠습니다.
한국어로 변경이 잘 됩니다.
이렇게 다국어를 사용할 수 있고, IDE 의 지원을 받아 동시에 같은 key 을 여러 언어로 입력도 할 수 있고 누락된 것이 없는지 확인도 가능합니다.
하지만, 문제가 있습니다. 위 이미지를 자세히 봤다면 "값" 에 약간의 의문을 가져야 합니다.
ko_KR 이나 en_US 가 아니라 ko-KR 로 출력된다는 것입니다.
그리고, 다음과 같이 enus 로 입력하면 엉뚱한 결과가 출력됩니다.
2019/01/29 - [Programming/Spring Boot 시작하기] - Spring Boot 에서 messages.properties 을 이용한 다국어 처리 (5)