Thursday, 30 October 2014

Spring MVC with thymeleaf

Spring MVC application with thymeleaf

Objective: Substitue view-layer web technologies such as JSP.

Pre-req: Spring STS as development environment

Why thymeleaf?: 

  • Natural templating for easy prototyping: display your templates statically in a browser (without running your app server).

  • Complete integration with Spring MVC (SpringStandard): form binding, property editors, internationalization, etc.

  • Full (and extensible) internationalization support: easy inclusion of externalized messages into templates.

  • URL rewriting capabilities for adding context and session information to URLs.

  • Spring Security support.

  • Out-of-the-box: templates can be read as classloader or ServletContext resources, as well as files (from the filesystem) and by calling URLs.


  1. Create spring mvc project

    • Go to File > New > Spring MVC Project

    • Select project name (ess) and top level package (com.njoshi.ess)

  2. Right click on project name > run on server to make sure project configuration is working

  3. Add thymeleaf dependancy

    • Open pom.xml

    • Add following dependancy

    • <dependency>

  4.  SpringTemplateEngine

    • Configure thymeleaf template engine in ess/src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml

    • <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns=""
       xmlns:xsi="" xmlns:context=""
       <context:component-scan base-package="com.njoshi.ess" />
       <bean id="templateResolver"
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".html" />
        <property name="templateMode" value="HTML5" />
       <bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver" />
       <bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />

  5. Changes in home.jsp

    • Change home.jsp to home.html

    • <!DOCTYPE html>
      <html xmlns=""
       <h1>Hello world!</h1>
       <p th:text="${serverTime}">Welcome to time check page. Site is down!</p>


Source code:

No comments:

Post a comment