Following example shows how to use internationalization capability which comes with Spring MVC Theme functionality. By default ResourceBundleThemeSource (implements ThemeSource ) is used to load theme properties via a ResourceBundle. That means we can also add i18n based multiple theme properties files. One of them will be picked depending on the client Locale (based on 'Accept-Language' header value). Check out our MVC i18n tutorial as well.
Example
Java Config class
In this example we are using default FixedThemeResolver.
Other than multiple i18n theme.properties , we are also going to add some i18n based message files, for that we have to configure our own ResourceBundleMessageSource bean:
@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {
@Bean
public MessageSource messageSource() {
//this is only needed for text messages and not needed for theme internationalization
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("texts/msg");
return messageSource;
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//mapping '/' to index view name without a controller
ViewControllerRegistration r = registry.addViewController("/");
r.setViewName("index");
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp();//default prefix=/WEB-INF/", suffix=".jsp"
}
}
Theme Properties files
src/main/resources/theme.propertiesbackground=beige
content-style=width:500px;border:solid 2px blue;margin:auto;padding:30px;
src/main/resources/theme_fr.propertiesbackground=darkBlue
content-style=width:500px;border:solid 2px white;color:white;margin:auto;padding:30px;
Also note that by default, the theme's ResourceBundleThemeSource uses an empty base name prefix, so we don't need to use a prefix with theme properties files name. In the next example we will learn how to use a custom prefixes base name.
Message Properties files
src/main/resources/texts/msg.propertiesapp.msg = hi there
src/main/resources/texts/msg_fr.propertiesapp.msg = salut
JSP View:
/src/main/webapp/WEB-INF/index.jsp<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<body style="background-color:<spring:theme code='background'/>;">
<div style="<spring:theme code='content-style'/>">
<spring:message code="app.msg"/>
</div>
</body>
</html>
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Output
From browser with default locale of 'en-US':
Using Postman with an explicit 'Accept-Language' header value of 'fr-FR':
Example ProjectDependencies and Technologies Used: - spring-webmvc 5.0.2.RELEASE: Spring Web MVC.
- javax.servlet-api 3.1.0 Java Servlet API
- JDK 1.8
- Maven 3.3.9
|