Themes and Theme resolvers in Spring MVC

In this section, you will learn about theme and theme resolvers in Spring MVC.

Themes and Theme resolvers in Spring MVC

Themes and Theme resolvers in Spring MVC

In this section, you will learn about theme and theme resolvers in Spring MVC.

Themes in a application can be define as overall look-and-feel. Basically, theme is a collection of static resources like images, CSS etc.

Defining themes

For using theme in your application, you must use interface org.springframework.ui.context.ThemeSource. ThemeSource is extended by the WebApplicationContext interface but real work is done by the implementation of org.springframework.ui.context.support.ResourceBundleThemeSource that loads properties files from the root of the classpath.

You can register a bean in the application context with the reserved name themeSource for custom ThemeSource implementation or to configure the base name prefix of the ResourceBundleThemeSource. A bean with that name is automatically detected and use by the web application context.

Using ResourceBundleThemeSource, you can define a theme in properties file. You need to make a list of resources inside property file. Given below a sample :

styleSheet=/themes/cool/style.css
background=/themes/cool/img/coolBg.jpg

The keys of the property file represents the themed element of view. For example : in JSP, you can use <spring:theme> custom tag to refer a themed elements. Given below the sample code :

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<link rel="stylesheet" href="<spring:theme code='styleSheet'/>" type="text/css"/>
</head>
<body style="background=<spring:theme code='background'/>">
...
</body>
</html>

The properties files are loaded from the root of the classpath.

Theme resolvers

After defining theme, you decide which theme to use. The DispatcherServlet look for a bean named themeResolver to determine which implementation of ThemeResolver to use. It detects the theme for a specific request and can also modify the theme of the request. Spring have following theme resolvers:

Class Description
FixedThemeResolver This theme resolver picks fixed theme which can be set using defaultThemeName property.
SessionThemeResolver This theme resolver is used to set the theme for a whole session but not for different session.
CookieThemeResolver This theme resolver set the selected theme in a cookie for each client.
 ThemeChangeInterceptor This theme resolver changes theme on every request having a simple request parameter.