I have a CMS based on Spring MVC 4 and I want user to choose from different visual themes. They are stored in separate folders.
For now theme name is hardcoded in Properties.THEME_NAME, but I want to make the value stored in database and loaded as prefix part for InternalResourceViewResolver. So user can change it and switch to another theme. Is it possible to make this changes dinamically when app is running?
My code for configuration:
@EnableWebMvc
@Configuration
@ComponentScan({ "shop.main.*" })
@Import({ SecurityConfig.class })
@PropertySource("classpath:application.properties")
public class AppContextConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/pages/" + Properties.THEME_NAME + "/");
resolver.setSuffix(".jsp");
return resolver;
}
// other methods
}
One way of achieving my goal is to extend InternalResourceViewResolver and override getter method to return prefix loaded dinamicaly. So configuration changes to:
@Bean
public ThemedResourceViewResolver internalResourceViewResolver() {
ThemedResourceViewResolver resolver = new ThemedResourceViewResolver();
resolver.setSuffix(".jsp");
return resolver;
}
And the custom resolver class:
public class ThemedResourceViewResolver extends InternalResourceViewResolver {
@Autowired
private SitePropertyDAO sitePropertyDAO;
protected String getPrefix() {
String prefix = "/pages/" + Properties.THEME_NAME + "/";
SiteProperty property = sitePropertyDAO.findOneByName(Constants.THEME);
if (property != null) {
prefix = "/pages/" + property.getContent() + "/";
}
return prefix;
}
}
I used this approach because I need not only to change the CSS files path or properties, but folders where my .jsp views are stored, so different themes have different layouts.