Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Generic Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Overview

When designing a web application, its look-and-feel, or theme, is a key component. It impacts our application's usability and accessibility and can further establish our company's brand.

In this tutorial, we'll go through the steps required to configure themes in a Spring MVC application.

2. Use Cases

Simply put, themes are a set of static resources, typically stylesheets and images, that impact the visual style of our web application.

We can use themes to:

  • Establish a common look-and-feel with a fixed theme
  • Customize for a brand with a branding theme – this is common in a SAAS application where each client wants a different look-and-feel
  • Address accessibility concerns with a usability theme – for example, we might want a dark or a high-contrast theme

3. Maven Dependencies

So, first things first, let's add the Maven dependencies we'll be using for the first part of this tutorial.

We'll need the Spring WebMVC and Spring Context dependencies:


And since we're going to use JSP in our example, we'll need Java Servlets, JSP, and JSTL:


4. Configuring Spring Theme

4.1. Theme Properties

Now, let's configure light and dark themes for our application.

For the dark theme, let's create dark.properties:


And for the light theme, light.properties:


From the properties above, we notice that one refers to a CSS file and another refers to a CSS style. We'll see in a moment how these are manifest in our view.

4.2. ResourceHandler

Reading the properties above, the files black.css and white.css must be placed in the directory named /themes.

And, we must configure a ResourceHandler to enable Spring MVC to correctly locate the files when requested:

public void addResourceHandlers(ResourceHandlerRegistry registry) {

4.3. ThemeSource

We can manage these theme-specific .properties files as ResourceBundles via ResourceBundleThemeSource:

public ResourceBundleThemeSource resourceBundleThemeSource() {
    return new ResourceBundleThemeSource();

4.4. ThemeResolvers

Next, we need a ThemeResolver to resolve the correct theme for the application. Depending on our design needs, we can choose between existing implementations or create our own.

For our example, let's configure the CookieThemeResolver. As the name depicts, this resolves the theme information from a browser cookie or falls back to the default if that information isn't available:

public ThemeResolver themeResolver() {
    CookieThemeResolver themeResolver = new CookieThemeResolver();
    return themeResolver;

The other variants of ThemeResolver shipped with the framework are:

  • FixedThemeResolver: Used when there is a fixed theme for an application
  • SessionThemeResolver: Used to allow the user to switch themes for the active session

4.5. View

In order to apply the theme to our view, we must configure a mechanism to query the resource bundles.

We'll keep the scope to JSP only, though a similar lookup mechanism could be configured for alternate view rendering engines as well.

For JSPs, we can import a tag library that does the job for us:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

And then we can refer to any property specifying the appropriate property name:

<link rel="stylesheet" href="<spring:theme code='styleSheet'/>"/>


<body bgcolor="<spring:theme code='background'/>">

So, let's now add a single view called index.jsp into our application and place it in the WEB-INF/ directory:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="<spring:theme code='styleSheet'/>"/>
        <title>Themed Application</title>
            <h1>Themed Application</h1>
            <hr />
            <h2>Spring MVC Theme Demo</h2>
            <form action="<c:url value='/'/>" method="POST" name="themeChangeForm" id="themeChangeForm">
                        Change Theme
                <select id="theme" name="theme" onChange="submitForm()">
                    <option value="">Reset</option>
                    <option value="light">Light</option>
                    <option value="dark">Dark</option>

        <script type="text/javascript">
            function submitForm() {

Actually, our application would work at this point, always choosing our light theme.

Let's see how we can allow the user to change their theme.

4.6. ThemeChangeInterceptor

The job of the ThemeChangeInterceptor is to understand the theme change request.

Let's now add a ThemeChangeInterceptor and configure it to look for a theme request parameter:

public void addInterceptors(InterceptorRegistry registry) {

public ThemeChangeInterceptor themeChangeInterceptor() {
    ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor();
    return interceptor;

5. Further Dependencies

Next, let's implement our own ThemeResolver that stores the user's preference to a database.

To achieve this, we'll need Spring Security for identifying the user:




And Spring Data, Hibernate, and HSQLDB for storing the user's preference:



6. Custom ThemeResolver

Let's now dive more into ThemeResolver and implement one of our own. This custom ThemeResolver will save the user's theme preference to a database.

To achieve this, let's first add a UserPreference entity:

@Table(name = "preferences")
public class UserPreference {
    private String username;

    private String theme;

Next, we'll create UserPreferenceThemeResolver, which must implement the ThemeResolver interface. Its key responsibilities are to resolve and save theme information.

Let's first address resolving the name by implementing UserPreferenceThemeResolver#resolveThemeName:

public String resolveThemeName(HttpServletRequest request) {
    String themeName = findThemeFromRequest(request)
    request.setAttribute(THEME_REQUEST_ATTRIBUTE_NAME, themeName);
    return themeName;

private Optional<String> findUserPreferredTheme() {
    Authentication authentication = SecurityContextHolder.getContext()
    UserPreference userPreference = getUserPreference(authentication).orElse(new UserPreference());
    return Optional.ofNullable(userPreference.getTheme());

private Optional<String> findThemeFromRequest(HttpServletRequest request) {
    return Optional.ofNullable((String) request.getAttribute(THEME_REQUEST_ATTRIBUTE_NAME));
private Optional<UserPreference> getUserPreference(Authentication authentication) {
    return isAuthenticated(authentication) ? 
      userPreferenceRepository.findById(((User) authentication.getPrincipal()).getUsername()) : 

And now we can write our implementation for saving the theme in UserPreferenceThemeResolver#setThemeName:

public void setThemeName(HttpServletRequest request, HttpServletResponse response, String theme) {
    Authentication authentication = SecurityContextHolder.getContext()
    if (isAuthenticated(authentication)) {
        request.setAttribute(THEME_REQUEST_ATTRIBUTE_NAME, theme);
        UserPreference userPreference = getUserPreference(authentication).orElse(new UserPreference());
        userPreference.setUsername(((User) authentication.getPrincipal()).getUsername());
        userPreference.setTheme(StringUtils.hasText(theme) ? theme : null);

And finally, let's now change out the ThemeResolver in our app:

public ThemeResolver themeResolver() { 
    return new UserPreferenceThemeResolver();

Now, the user's theme preference is saved in the database instead of as a cookie.

An alternative way of saving the user's preference could've been through a Spring MVC Controller and a separate API.

7. Conclusion

In this article, we learned the steps to configure Spring MVC themes.

We can also find the complete code over on GitHub.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Generic footer banner
Comments are closed on this article!