Following example shows how to register a custom ThemeSource . We are still going to use the default ResourceBundleThemeSource but we are going to specify a non-empty base name prefix with it.
Example
Java Config class
UiApplicationContextUtils.initThemeSource() looks for user configured ThemeSource bean by a specific name as defined by UiApplicationContextUtils.THEME_SOURCE_BEAN_NAME before falling back to the default one.
@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {
@Bean(UiApplicationContextUtils.THEME_SOURCE_BEAN_NAME)
public ThemeSource customResourceBundleThemeSource() {
ResourceBundleThemeSource source = new ResourceBundleThemeSource();
source.setBasenamePrefix("app_");
return source;
}
@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/app_theme.propertiesbackground=beige
content-style=width:500px;border:solid 2px blue;margin:auto;padding:30px;
src/main/resources/app_theme_fr_FR.propertiesbackground=darkBlue
content-style=width:500px;border:solid 2px white;color:white;margin:auto;padding:30px;
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'/>">
Test Content
</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
|