Spring MVC 5 - Hello world example with Thymeleaf template

Posted on January 28, 2018


Thymeleaf is a java template engine, which process six kind of templates (HTML, CSS, TEXT, JAVASCRIPT, CSS and RAW) in standalone and web application.

In this post, I will show you how to configure the Thymeleaf template in Spring MVC application.

Tools and technologies used for this example are -

  • Spring MVC 5.0.3.RELEASE
  • Servlet API 4.0.0
  • Thymeleaf 3.0.9.RELEASE
  • Java SE 9
  • Maven 3.5.2
  • Jetty Maven plugin 9.4.8
  • Eclipse Oxygen.2 Release (4.7.2)

So let us proceed to write a simple Spring MVC application which will print “Hello Spring MVC 5!”

Step 1 - Create web project using Maven

First, create a maven project with war packaging. You can refer this article to learn - how to create a maven web application in Eclipse IDE.

Final project structure of our application will look like as follows.

spring-mvc-thymeleaf-example.png

Step 2 - Add Jar dependencies

To use the Thymeleaf in Spring MVC application, you need to add the thymeleaf-spring5 as dependency on your classpath.

Open pom.xml file of your maven project and add the following jars dependencies in it.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.boraji.tutorial.springmvc</groupId>
   <artifactId>spring-mvc-thymeleaf-hello-world-example</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>war</packaging>
   <name>Spring MVC - Thymeleaf Integration example</name>

   <properties>
      <failOnMissingWebXml>false</failOnMissingWebXml>
      <maven.compiler.source>9</maven.compiler.source>
      <maven.compiler.target>9</maven.compiler.target>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-webmvc</artifactId>
         <version>5.0.3.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.thymeleaf</groupId>
         <artifactId>thymeleaf-spring5</artifactId>
         <version>3.0.9.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>javax.servlet-api</artifactId>
         <version>4.0.0</version>
         <scope>provided</scope>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <!-- Embedded Jetty HTTP Server for testing war application -->
         <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.4.8.v20171121</version>
         </plugin>
      </plugins>
   </build>
</project>

Step 3 - Spring MVC Configuration

Create a @Configuration class, named as MvcWebConfig, under com.boraji.tutorial.spring.config package.

To register the Thymeleaf view in Spring MVC, you need to define the SpringResourceTemplateResolver and SpringTemplateEngine bean methods as follows -

MvcWebConfig.java

package com.boraji.tutorial.spring.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.boraji.tutorial.spring.controller")
public class MvcWebConfig implements WebMvcConfigurer {

   @Autowired
   private ApplicationContext applicationContext;

   /*
    * STEP 1 - Create SpringResourceTemplateResolver
    * */
   @Bean
   public SpringResourceTemplateResolver templateResolver() {
      SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
      templateResolver.setApplicationContext(applicationContext);
      templateResolver.setPrefix("/WEB-INF/views/");
      templateResolver.setSuffix(".html");
      return templateResolver;
   }

   /*
    * STEP 2 - Create SpringTemplateEngine
    * */
   @Bean
   public SpringTemplateEngine templateEngine() {
      SpringTemplateEngine templateEngine = new SpringTemplateEngine();
      templateEngine.setTemplateResolver(templateResolver());
      templateEngine.setEnableSpringELCompiler(true);
      return templateEngine;
   }

   /*
    * STEP 3 - Register ThymeleafViewResolver
    * */
   @Override
   public void configureViewResolvers(ViewResolverRegistry registry) {
      ThymeleafViewResolver resolver = new ThymeleafViewResolver();
      resolver.setTemplateEngine(templateEngine());
      registry.viewResolver(resolver);
   }

}

WebMvcConfigurer interface provides the default methods to customize the java-based configuration for Spring  MVC application.

@EnableWebMvc annotation is used to import the Spring MVC configuration from WebMvcConfigurationSupport (main class behind java-based MVC config).

@ComponentScan scans the stereotype annotations (@Controller@Service etc...) in a package specified by basePackagesattribute.

SpringResourceTemplateResolver integrates with Spring's own resource resolution infrastructure. You can use it to specify the location of template, mode of template, cache expire TTL etc. 

SpringTemplateEngine applies SpringStandardDialect and enables Spring's own MessageSource message resolution mechanisms resolution mechanisms.

 

In Spring MVC, The DispatcherServlet needs to be declared and mapped for processing all requests either using java or web.xmlconfiguration.

In a Servlet 3.0+ environment, you can use AbstractAnnotationConfigDispatcherServletInitializer class to register and initialize the DispatcherServlet programmatically as follows.

MvcWebApplicationInitializer.java

package com.boraji.tutorial.spring.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
   protected Class<?>[] getRootConfigClasses() {
      return null;
   }

   @Override
   protected Class<?>[] getServletConfigClasses() {
      return new Class[] { MvcWebConfig.class };
   }

   @Override
   protected String[] getServletMappings() {
      return new String[] { "/" };
   }

}

Step 4 - Create Thymeleaf Template/View

Create an index.html file under src/main/webapp/WEB-INF/views folder and write the following code in it.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">

<title>BORAJI.COM</title>
</head>
<body>
   <h1>Spring MVC + Thymeleaf  Hello World example</h1>
   <p th:text="${message}"></p>
</body>
</html>

The attribute th:text="" is known as Standard Dialect, which evaluate the object with ${...} standard expression.

Step 5 - Create Controller

Create a @Controller class under com.boraji.tutorial.spring.controller package and write the following code in it.

MyController.java

package com.boraji.tutorial.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {

   @GetMapping("/")
   public String index(Model model) {

      model.addAttribute("message", "Hello Spring MVC 5!");
      return "index";
   }
}

Step 6 - Run Application

Use the following maven command to run your application.

mvn jetty:run (This command deploy the webapp from its sources, instead of build war).

Enter the http://localhost:8080 URL in browser's address bar to test our application.

spring-mvc-thymeleaf-example_01.png