Spring 3 MVC: Themes in Spring-Tutorial with Example

Welcome to Part 6 of Spring 3.0 MVC Series. In previous article we saw how to add Internationalization i18n and Localization L10n support to Spring 3.0 based web application. We used LocaleChangeInterceptor to intercept the change in locale and ReloadableResourceBundleMessageSource class to add message resources properties. In this part we will see how to add Themes in Spring MVC. We will create three different themes and add functionality in our HelloWorldSpring project for user to select any of the available theme. Once user selects a theme, we can save it in cookies so that it can be persisted between different sessions. [sc:SpringMVC_Tutorials]

Introduction to Themes in Spring MVC

A theme is a collection of static resources, typically style sheets and images, that affect the visual style of the application. We can apply Spring Web MVC framework themes to set the overall look-and-feel of application, thereby enhancing user experience. To use themes in your web application, you must set up an implementation of the org.springframework.ui.context.ThemeSource interface. The WebApplicationContext interface extends ThemeSource but delegates its responsibilities to a dedicated implementation. By default the delegate will be an org.springframework.ui.context.support.ResourceBundleThemeSource implementation that loads properties files from the root of the classpath. To use a custom ThemeSource implementation or to configure the base name prefix of the ResourceBundleThemeSource, you can register a bean in the application context with the reserved name themeSource. The web application context automatically detects a bean with that name and uses it. When using the ResourceBundleThemeSource, a theme is defined in a simple properties file. The properties file lists the resources that make up the theme. Here is an example:

Our Goal

Our goal is to change the Hello World Spring 3 MVC and add Theme support to it. User will have option to select theme from 3 predefined themes (default, black and blue). spring-mvc-theme-demo

Adding Theme support to Spring 3 MVC

Let us configure our Spring 3 MVC application to add Theme support. For this we will add following code into spring-servlet.xml file. File: WebContent/WEB-INF/spring-servlet.xml
<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource"> <property name="basenamePrefix" value="theme-" /> </bean> <!-- Theme Change Interceptor and Resolver definition --> <bean id="themeChangeInterceptor" class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"> <property name="paramName" value="theme" /> </bean> <bean id="themeResolver" class="org.springframework.web.servlet.theme.CookieThemeResolver"> <property name="defaultThemeName" value="default" /> </bean> <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <list> <ref bean="localeChangeInterceptor" /> <ref bean="themeChangeInterceptor" /> </list> </property> </bean>
Code language: HTML, XML (xml)
In the above configuration, first we have added themeSource bean. Notice that this bean is an instance of class ResourceBundleThemeSource and we also have specified a property basenamePrefix with value “theme-“. ResourceBundleThemeSource class will load the property files containing theme definition starting with prefix “theme-“. Thus, if we have defined 3 new themes in our project (default, black and blue) then we will create 3 property files while will have certain configuration properties. Also these files will be placed under the project classpath. Next, we defined an interceptor bean themeChangeInterceptor which is an instance of class org.springframework.web.servlet.theme.ThemeChangeInterceptor. Also note here that we have specified a property paramName with value theme. This interceptor is invoked whenever a request is made with parameter “theme” with different values. Once the themeChangeInterceptor intercepts the change in the theme, the changes are then stored in the cookies using class org.springframework.web.servlet.theme.CookieThemeResolver. We have configured this class in our spring-servlet.xml configuration file. Also note that we have specified default theme name with this bean. Now create following properties files in resources/ folder of the project. spring-mvc-theme-directory-structure File: resources/theme-default.properties
css=themes/default.css
Code language: HTML, XML (xml)
File: resources/theme-blue.properties
css=themes/blue.css
Code language: HTML, XML (xml)
File: resources/theme-black.properties
css=themes/black.css
Code language: HTML, XML (xml)

CSS Stylesheet for different Themes

Let us create 3 CSS stylesheet which will act as the theme files for our project. Create following CSS files in WebContent/themes folder. File: WebContent/themes/default.css
body { background-color: white; color: black; }
Code language: CSS (css)
File: WebContent/themes/blue.css
body { background-color: #DBF5FF; color: #007AAB; }
Code language: CSS (css)
File: WebContent/themes/black.css
body { background-color: #888; color: white; }
Code language: CSS (css)

JSP View changes

We are almost done with the changes and last bit that is remaining is to add a functionality for user to select the theme from UI. For this we will change the header.jsp file and add 3 links with different themes. User can click on any of this link and change the theme of webapplication. File: WebContent/WEB-INF/jsp/header.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <h3><spring:message code="label.title"/></h3> <span style="float: right"> <a href="?lang=en">en</a> | <a href="?lang=de">de</a> </span> <span style="float: left"> <a href="?theme=default">def</a> | <a href="?theme=black">blk</a> | <a href="?theme=blue">blu</a> </span>
Code language: HTML, XML (xml)
Notice that in above JSP changes we created 3 links with argument “?theme=”. Thus whenever user will click these links, a new parameter will be passed in the request with the appropriate theme. The request interceptor of Spring will fetch this value and change the theme accordingly.

That’s All Folks

That’s pretty much it :) We just added Theme support to our demo Spring 3.0 MVC application. All you have to do is just execute the app in Eclipse. Press Alt + Shift + X, R. spring-mvc-theme-demo

Download Source Code

Click here to download Source code (21kb, zip)
Get our Articles via Email. Enter your email address.

You may also like...

74 Comments

  1. Naveen says:

    That worked like Charm. Thank you for all the great work.

    Naveen

  2. Aren’t you missing the link to the stylesheet.

    <link rel="stylesheet" href='’ type=”text/css” />

    I had to stick this within the HEAD tag in layout.jsp for the themes to work.

  3. Surendra Gade says:

    You have not mentioned the changes required in layout.jsp to support themes.

  4. Robert Wilson says:

    thanks for the post

  5. Mlobo says:

    Hi thanks for the tutorial! Do you have example of using ajax with Spring MVC 3?

  6. VK says:

    This doesnt seem to work as is. Any changes required in layout.jsp?

  7. Nirwana says:

    Please check the attached code sample. layout.jsp page need <link rel="stylesheet" href="” type=”text/css”/> line.

  8. Hemant says:

    Can this feature be implemented using Spring 2.5? If so, please let me know the changes. Thanks in advance.

  9. Nasa says:

    Please add in layout.jsp the following codes:

    <link rel="stylesheet" href="” type=”text/css”/>

    or you may refer to the attached codes.
    Thank you very much. Very comprehensive tutorial.

    • @Nasa – Thanks for the correction.

  10. Halcon de la sierra says:

    Estan todos muy tlacucahes aqui esta la correcion :)
    en el jsp template

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


    <link rel="stylesheet" href="<spring:theme code="css"/>" type="text/css"/>

    J_J gracias al compa oswaldo

  11. AJ says:

    Can someone please point list of jars required to run this applications?

    Thanks
    JA

  12. Kielbasa says:

    Great tutorial! Thanks!!!

  13. Graciano says:

    Just add
    <link rel="stylesheet" type="text/css" href="”/>

    to layout.jsp

    • Kiran says:

      I still can not make the theme working.
      Could you please tell me where exactly in layout.jsp I need to add
      ?

      • Smita says:

        Please add below line

        <link rel="stylesheet" href="” type=”text/css” />

        Layout.jsp

  14. Ashim says:

    Hi, my themeChangeInterceptor does not get call , Please could you help me anyone however it is work for localeChangeInterceptor.

    • @Ashim – Check if you are correctly configured ThemeChangeInterceptor and also the parameter that you are specifying matches with the request parameter in JSP.

    • Kiran says:

      Ashim,
      I have the same problem as you had.. Did you able to get it resolved, if so what did you do ?.

      My configuration is correct as per the tutorial.
      Thanks.

  15. Jason says:

    I added to layout.jsp but still cannot make it work.
    can you please send me the corrected maven proejct?

    • Jason says:

      I used <link rel="stylesheet" href="” type=”text/css”/>
      instead of
      worked like a charm!

  16. Tom says:

    In which tutorial we added the log4j.properties and folder WEB-INF/classes??

    Furthermore, in the header.jsp file, why do we need , when we even aren’t using the tag “c”?

  17. Turk says:

    Thank you so much! i have been looking for something like this that would walk you though step by step.

  18. Anil says:

    Brilliant!

    This article works perfectly as long as you add the below two changes in the layout.jsp

    1) Add the line: at the top of the layout.jsp file
    2) Add the line: <link rel="stylesheet" href='’ type=”text/css”> just before your tag ends. ie., just before

    Have you also worked on Spring Web Flow? I was curious to learn that in similar fashion you explained MVC. Do you know any resources I can look at?

  19. Anil says:

    Filling the missing info in my last posted comment..

    Brilliant!

    This article works perfectly as long as you add the below two changes in the layout.jsp

    1) Add the line: at the top of the layout.jsp file
    2) Add the line: just before your tag ends. ie., just before

    Have you also worked on Spring Web Flow? I was curious to learn that in similar fashion you explained MVC. Do you know any resources I can look at?

  20. Kam says:

    Good tutorial. For me at first instance the tutorial did not work. To correct it first I had to make following 2 modifications to layout.jsp –
    1) Add reference to tag library as –

    2) Modify the Head tag as –

    <link rel="stylesheet" href="” type=”text/css” />

  21. Dennis says:

    Download the layout.jsp file from the source of this part and replace your layer.jsp file and you will be ok it will work.

    Good Job nice and easy Tutorial thnx!!

    • rtchandrasekhar says:

      Thanks DENNIS I have tried added link under head but its not worked though many said….. But ur idea of downloading and COPY PASTE WORKED PERFECTLY…….. THX……

    • Tooie says:

      Thanks a lot Dennis.
      I’ve made the same as “rtchandrasekhar” and when I copied and pasted the downloaded file it has worked perfectly.
      Very nice tutorial, i’m really learning how to work with spring3.

  22. Purushottam says:

    I am still facing problem inserting image in jsp using the above code……

  23. rakesh says:

    This is a good tutorial. There is difference between downloaded code and step by step process. Step by step process giving issues because some codes are missing. downloaded code is working.

  24. Jack says:

    I can not get the themes work. No changes while changing the themes. Either go through step by step or copy paste the download sources could not get it work. Does any body could help with this issue?

  25. Amit says:

    Great help …

  26. Daniel says:

    Hi,
    Very good tutorial. It gave me the very first steps with Spring3.
    However, for this part with themes, I followed the instructions, but in Tomcat console I’m getting
    Theme ‘theme’: No message found under code ‘css’ for locale
    when I’m clicking on theme ‘link’.
    Thank you for your help.

  27. Sandeep says:

    @Viral, very good tutorials and appreciate your efforts. Thanks :)
    @Dennis, thanks for suggesting the solution of copy-paste for layout.jsp and it works fine.

    @All, I am able make theme working but the i18n stopped working after applying the theme code on top of i18n code. Any suggestion is highly appreciated for fixing this issue.

    Note: I am using the Apache Tomcat/7.0.28 and the jars recommended in this tutorial.

    Awaiting for help from anyone of this community.

    Thanks,
    Sandeep.

  28. Sandeep says:

    Hey folks, it works now, it was not working due to mismatch of parameter (lang vs language) in jsp and spring-servlet.xml files.

    Thanks,
    Sandeep

  29. Nikhitha says:

    Hi Viral Thanks for your various articles. I follow them very eagerly But of late i am facing a problrm with the Themes lab exercise. Pls help me solve this. I have got problems in the previous blogs also but when i changed to the latest version of jars it got rectified. But nothing seems to be working with this.
    The error i get is

    descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

    exception

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.apache.tiles.impl.CannotRenderException: ServletException including path ‘/WEB-INF/jsp/layout.jsp’.
    root cause

    org.apache.tiles.impl.CannotRenderException: ServletException including path ‘/WEB-INF/jsp/layout.jsp’.
    root cause

    org.apache.tiles.util.TilesIOException: ServletException including path ‘/WEB-INF/jsp/layout.jsp’.
    root cause

    javax.servlet.jsp.JspTagException: Theme ‘Grey’: No message found under code ‘css’ for locale ‘de’.

    Pls reply to my query

  30. Nikhitha says:

    Also is it necessary that properties file to be in classpath what do you mean by the term being in the classpath. Could you please throw some light on this?

  31. Supermicho says:

    Here is how “layout.jsp” should look like

    <link rel="stylesheet" href="” type=”text/css”/>

    Thx to “Halcon de la sierra”

  32. nakNatxo says:

    Hi,

    Very nice tutorial, but for me don’t work, i have the same web.xml and spring.xml, i gonna put my .jsp below… When i click on the themes No changes happens :/ Is something missing?

    <link rel="stylesheet" href="" type="text/css"/>
    	
    	 
    	Spring 3 MVC - Persona Manager
    	
    	
    	body {
    		font-family: sans-serif, Arial;
    	}
    

    Contacts

    <a href="?lang=en" rel="nofollow">en</a>
        |
        <a href="?lang=es" rel="nofollow">es</a>
    
    
        <a href="?theme=default" rel="nofollow">def</a>
        |
        <a href="?theme=black" rel="nofollow">blk</a>
        |
        <a href="?theme=blue" rel="nofollow">blu</a>
    

     

    ${persona.rut}
    ${persona.nombre}
    ${persona.apellidoPaterno}
    ${persona.apellidoMaterno}

    Thanks In advance!

  33. nakNatxo says:

    Hi

    I anwer myself, i think you forgot put this lines on “spring-servlet.xml”

    Best Regards, nice blog ;)

  34. nakNatxo says:

    !– the mvc resources tag does the themes magic –
    mvc:resources mapping=”/themes/**” location=”/themes/”
    !– also add the following beans to get rid of some exceptions –

  35. vnTex says:

    Thx for a working theme example. I want to do a similar task but with a small twist. That’s to apply a CSS to a request HTML page. I’ve a controller that invokes back-end server for html pages and wanted to apply a template CSS before send the html page to the client. Is there a way to that? TIA.

  36. Make sure you have done the prior tutorials.

    Place

    at the top of the layout.jsp

    Place
    <link rel="stylesheet" href="” type=”text/css”/>
    just below in layout.jsp

    Also, get the log4j.properties file from the downloaded source code.

  37. You can’t get the sample code to show up in the comments. You need to look at the downloaded code and add a taglib and the stylesheet example from the downloaded code to make this work.

    Dennis

  38. Prachi says:

    Hi
    With the code above and all the corrections incorporated, my program has a strange problem..the title of the page changes based on the theme link clicked but the color of the page does not change that css is not getting applied. I have written the link tag as suggested in the comments. If anyone can help to debug that will be great.
    Prachi

  39. caro says:

    Hi. Great tutorial! But I have a little problem. I’m using Maven 2 instead DynamicWebProject. Where should I make a “themes” folder? I tried to make it in “webapp/resources” or in “webapp/resources/themes” but it seems that css files are not visible and when I’m clicking on def/blk/blu nothing happens. Of course I added into my “layout.jsp? file. Thanks in advance for help :)

  40. Suraj says:

    adding following lines to layout.jsp will solve the problem.

    1. add the following tag on the top of the layout.jsp

    2. add the style tag in the tag
    <link rel="stylesheet" href="” type=”text/css”/>

  41. Mack says:

    I think “localeChangeInterceptor” definition is missing

  42. Rajashekhar says:

    these two lines has to be added.. than only it will work…

    <link rel="stylesheet" href="” type=”text/css”/>

  43. Srini says:

    Hi Patel,

    Thanks for your post. I have a quick question about css file. I have a project, which is using css file for styles and background images, after providing static content path in my spring servlet like:

    I am able to access all images and static files in jsp using like <img src="”, but there is some background images path defined in my css. Can you please advise how to give a path in css about images since css file doesn’t understand spring tags.

    Thank you very much your help.

    Thanks,
    Srini

    • @Srini: I understand thats always been a pain to include background-image path in a CSS file. I’m afraid there is no direct way of doing this, except for defining that particular style (which has background image) within your JSP file. So for example:

      Below is my JSP file

      //some.jsp
      ...
      <style>
      .someclass {
            background-image: url('${some_css_path}');
      }
      </style>
      


      So basically defined all of the styles of styleclass .someclass within your .CSS file and than just define background-image within your JSP. As much as I know thats the only way of doing it. Let me know if you figure out more normal way of doing this.

  44. Pathum says:

    Hi,

    This is a nice tutorial and I was able to run it properly. I have one question. what happen if a user enter invalid theme name to the URL? I meant now we have default,black and blue as our themes but what happen if some one pass theme=red manually? I got an exception when trying this. I searched for something like fallBackDefaultTheme or some other setting but didn’t find anything yet. Appreciate if you could give me some clue.

    Thanks

  45. khan says:

    what are the jar files needed and tld too

  46. khan says:

    what are jar files needed for this appl

  47. Jamie says:

    Hi,
    Great tutorial and works very well. I want to use this example in conjunction with REST and hence, I had to make slight changes, such as, replacing

    <url-pattern>*.html</url-pattern>

    with

    <url-pattern>/</url-pattern>

    in servlet-mapping section in the web.xml file and making the necessary updates by removing the .html extensions in the appropriate java & jsp files. I’ve been trying to solve the following issue for several days now and being looking up forums, etc., but have found no solution as to why I get the following error:

    WARN http-apr-8080-exec-6 (DispatcherServlet.java:947) – No mapping found for HTTP request with URI /Spring3MVC/themes/default.css in DispatcherServlet with name ‘spring’.

    Any help will be most appreciative.

  48. Jamie says:

    Hi Viral Patel:

    I have fixed the mapping problem by adding

    <mvc:default-servlet-handler /> 

    However, a new problem has arisen. I now get “HTTP Status 405 – Request method ‘GET’ not supported” browser error message if I use REST controller, but do NOT get this message and all works fine if I do NOT use REST at all. That is, if I run the same application without REST upon start up, it works, but if I run the program again using REST and the REST controller returning the same ‘view’ name as the normal Spring Controller does, but because it went via REST it does NOT work! Is there something that I may have missed or could this be a bug a with Spring MVC core?

  49. irineocoria says:

    All of these tutorials have been very helpful, thank you very much and at the same time I want to ask your permission to make a video tutorial in Spanish basing on yours. I’ll give you credit. Please answer

  50. Hendrik Kobi says:

    Hi Viral! thanks a lot for this greats tuts!!! just fantastic!
    all tutorials are running without any errors! amazing!

    I have just one litte problem:
    I cant access my css and image files from the jsp’s…i added the images to the root, to the resource folder etc…but none of this helps
    i’ve also tried a lot of things like:

    in the spring-servlet.xml
    mvc:resources mapping=”/resources/**” location=”/resources/” />

    nothing solves the problem…

    have anybody an idea?
    thanks in advance!
    hendrik

  51. DESH says:

    Hey, I’m using this code directly. but getting this exception:-
    java.lang.NoClassDefFoundError: org/apache/tiles/startup/BasicTilesInitializer
    at java.lang.ClassLoader.defineClass1(Native Method)
    I have added tiles-core-3.0.1.jar but still this prob coming. can anybody help me.

  52. Sergei says:

    Viral, you forgot to mention the changes in layout.jsp

    <link rel="stylesheet" href="<spring:theme code="css"/>" type="text/css"/>

    • Mahendra Bagul says:

      Thanks…Bro….

    • long says:

      You save my day! :)

      • Sachin says:

        It worked now :) Thanks!!!

  53. sandeep says:

    some programs are not running success fully like i18,themes
    in themes add a link like:<link rel="stylesheet" href="” type=”text/css” /> in layout.jsp if it not works remove jar files and add new jar files .
    or else refer this site ex:http://www.devmanuals.com/tutorials/java/spring/spring3/mvc/Spring3-MVC-Themes.html

    • sandeep says:

      <link rel="stylesheet" href="” type=”text/css” />

  54. kyochan19792002 says:

    The correction for layout.jsp should be

    <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
    <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="<spring:theme code="css"/>">
    <title><tiles:insertAttribute name="title" ignore="true" /></title>
    </head>
    

    • jrp says:

      Thanks kyochan19792002

    • Boechi says:

      Thanks, saved me lot of time to search this out.

    • eagleeye1984 says:

      Thanks. It really helped. You saved me 15 minutes of spring doc reading.

  55. Nitin says:

    Hello Viral,

    I am facing issue with loading themes. The scenario is described below.
    The controller in the application have request mapping at class level and method level so the URL for a request is generally in the following format. “http://server:port/context/req_map_class/req_map_method.jsp”. When I try to switch the theme, the css url is of the format “http://server:port/context/req_map_class/theme/blue.css”, which is non-existent. The css is actually available “http://server:port/context/theme/blue.css”.

    Please advise.

    Thanks,
    Nitin

  56. Dnyaneshwar says:

    Kindly provide jar files for above web application. it is very difficult to trial and error to get which version of JAR files suite for this application.

  57. Navaneet says:

    Thanks a lot for this amazing feature..

  58. Tuan Huy says:

    copy the layout.jsp of author and pass for you , it’s will work like a charm :D

Leave a Reply

Your email address will not be published. Required fields are marked *