@Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("locale/messages"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; }Above, we've set the path to the property files as resources/locale/messages. Next we create the property files: one for each language and one for default:
messages.properties:
hello.header=Welcome!messages_fr.properties
hello.content=Click here to advance to the next page
greeting.header=Hello on a second page!
greeting.content=Click here to go back
hello.header=Welcome!
hello.content=Click here to advance to the next page
greeting.header=Bonjour!
greeting.content=Click here to go back
Next we create the localeResolver Bean and set the default locale, the cookie file name and the cookie's maximum age:
@Bean public LocaleResolver localeResolver() { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setDefaultLocale(new Locale("fr")); resolver.setCookieName("myLocaleCookie"); resolver.setCookieMaxAge(4800); return resolver; }
Lastly, we set up the way to update the locale through creating LocaleChangeInterceptor Bean and registering it as a interceptor through addInterceptors
@Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("mylocale"); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); }
In the test.html, we call the message through the Thymeleaf notation as below:<h3>i18n</h3>
<p th:text="#{greeting.header}"></p>
The Result:
When we set the variable mylocale through the URL, the locale is updated and the messages_fr.properties file is used as a source:
Hiç yorum yok:
Yorum Gönder