My linux world » Java Spring – Theme

Java Spring - Theme


Contents

Prerequistes

Please read : Java spring – quickstart

Configuration

WebMvcConfig.java

In WebMvcConfig.java, add the following beans :

@Bean
public ResourceBundleThemeSource themeSource() {
  ResourceBundleThemeSource resourceBundleThemeSource =  new ResourceBundleThemeSource();
  resourceBundleThemeSource.setBasenamePrefix("theme-");
  return resourceBundleThemeSource;
}
 
@Bean
public CookieThemeResolver themeResolver() {
  CookieThemeResolver cookieThemeResolver = new CookieThemeResolver();
  cookieThemeResolver.setDefaultThemeName("default");
  return cookieThemeResolver;
}

Still WebMvcConfig.java, register interceptor:

@Override
public void addInterceptors(InterceptorRegistry registry) {
  ThemeChangeInterceptor themeInterceptor = new ThemeChangeInterceptor();
  themeInterceptor.setParamName("theme");
  registry.addInterceptor(themeInterceptor);
}

Finally, and still in WebMvcConfig.java, add the following resources to access to CSS:

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
  registry.addResourceHandler("/**").addResourceLocations("/");
}

Resources

Create the following file src/main/resources/theme-default.properties :

css=themes/default.css

Create the following file src/main/resources/theme-blue.properties :

css=themes/blue.css

CSS

Create the following file src/main/webapp/theme/default.css :

body {
	background-color: white;
	color: black;
}

Create the following file src/main/webapp/theme/blue.css:

body {
	background-color: #DBF5FF;
	color: #007AAB;
}

JSP

<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="<spring:theme code="css"/>" type="text/css"/>
</head>
<body>
 
<h3>Theme</h3>
 
<span style="float: left">
    <a href="?theme=default" id="theme-default">default</a> 
    | 
    <a href="?theme=blue" id="theme-blue">blue</a>
</span>
 
</body>
</html>

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.