• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring MVC 5 Thymeleaf 3 Hello World Example

March 13, 2018 by javainterviewpoint Leave a Comment

Thymeleaf is a Java template engine for processing  HTML, XML, JavaScript, CSS, and text. In this Spring MVC 5 Thymeleaf example, we will learn how to configure Thymeleaf with Spring MVC. We need to add the dependency “thymeleaf-spring5″ in order to use Thymeleaf in our Spring MVC 5. 

We need to configure ServletContextTemplateResolver, SpringTemplateEngine and ThymeleafViewResolver bean in our JavaConfig as well.

Folder Structure:

Spring MVC 5 Thymeleaf 3

  1. Create a simple Maven webapp Project “SpringMVCThymeleaf” and create a package for our source files “com.javainterviewpoint” under  src/main/java 
  2. Now add the following dependency in the 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/maven-v4_0_0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<groupId>com.javainterviewpoint</groupId>
    	<artifactId>SpringMVCThymeleaf</artifactId>
    	<packaging>war</packaging>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>Spring MVC Thymeleaf Example Application</name>
    	<url>http://maven.apache.org</url>
    	
    	<properties>
    		<failOnMissingWebXml>false</failOnMissingWebXml>
    		<maven.compiler.source>8</maven.compiler.source>
    		<maven.compiler.target>8</maven.compiler.target>
    		<jdk.version>1.8</jdk.version>
    		<spring.version>5.0.4.RELEASE</spring.version>
    		<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-webmvc</artifactId>
    			<version>${spring.version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.thymeleaf</groupId>
    			<artifactId>thymeleaf-spring5</artifactId>
    			<version>${thymeleaf.version}</version>
    		</dependency>
    	
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>javax.servlet-api</artifactId>
    			<version>4.0.0</version>
    			<scope>provided</scope>
    		</dependency>
    
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-simple</artifactId>
    			<version>1.7.25</version>
    			<scope>compile</scope>
    		</dependency>
    	</dependencies>
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>3.3</version>
    				<configuration>
    					<source>${jdk.version}</source>
    					<target>${jdk.version}</target>
    				</configuration>
    			</plugin>
    
    			<plugin>
    				<groupId>org.apache.tomcat.maven</groupId>
    				<artifactId>tomcat7-maven-plugin</artifactId>
    				<version>2.2</version>
    				<configuration>
    					<path>/</path>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    </project>
  3. Create the Java class HelloController.java,WebApplicationInitializer.java and WebMvcConfiguration.java under  com.javainterviewpoint folder.
  4. Place the hello.jsp under the sub directory under WEB-INF/pages

Other interesting articles which you may like …

  • Spring MVC Form Validation -Annotations and ResourceBundle
  • Spring MVC Exception Handling @ExceptionHandler
  • Spring MVC Exception Handling @ControllerAdvice and @ExceptionHandler
  • Spring MVC Custom Exception Handling
  • context:annotation-config vs context:component-scan
  • Spring MVC BeanNameUrlHandlerMapping Example
  • Spring MVC ControllerClassNameHandlerMapping Example
  • Spring MVC SimpleUrlHandlerMapping Example
  • Spring MVC Flow Diagram
  • Spring MVC Multiple submit buttons in a single form
  • Spring MVC SimpleFormController Example
  • Spring 4 – Spring MVC Hello World Example
  • Spring REST Hello World Example – JSON and XML responses
  • ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
  • Fix missing src/main/java folder in Eclipse Maven Project – 2 build path entries are missing

Spring MVC 5 Thymeleaf 3 Hello World Example

[INFO] ------------------------------------------------------------------------
[INFO] Building Spring MVC Thymeleaf Example Application 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ SpringMVCThymeleaf ---
[INFO] com.javainterviewpoint:SpringMVCThymeleaf:war:0.0.1-SNAPSHOT
[INFO] +- org.springframework:spring-webmvc:jar:5.0.4.RELEASE:compile
[INFO] |  +- org.springframework:spring-aop:jar:5.0.4.RELEASE:compile
[INFO] |  +- org.springframework:spring-beans:jar:5.0.4.RELEASE:compile
[INFO] |  +- org.springframework:spring-context:jar:5.0.4.RELEASE:compile
[INFO] |  +- org.springframework:spring-core:jar:5.0.4.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-jcl:jar:5.0.4.RELEASE:compile
[INFO] |  +- org.springframework:spring-expression:jar:5.0.4.RELEASE:compile
[INFO] |  \- org.springframework:spring-web:jar:5.0.4.RELEASE:compile
[INFO] +- org.thymeleaf:thymeleaf-spring5:jar:3.0.9.RELEASE:compile
[INFO] |  +- org.thymeleaf:thymeleaf:jar:3.0.9.RELEASE:compile
[INFO] |  |  +- org.attoparser:attoparser:jar:2.0.4.RELEASE:compile
[INFO] |  |  \- org.unbescape:unbescape:jar:1.1.5.RELEASE:compile
[INFO] |  \- org.slf4j:slf4j-api:jar:1.7.25:compile
[INFO] +- javax.servlet:javax.servlet-api:jar:4.0.0:provided
[INFO] \- org.slf4j:slf4j-simple:jar:1.7.25:compile

WebMvcConfiguration.java

Create our WebMvcConfiguration.java under the com.javainterviewpoint package.

package com.javainterviewpoint;

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.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
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.javainterviewpoint")
public class WebMvcConfiguration implements WebMvcConfigurer 
{
    @Autowired
    ApplicationContext applicationContext;
    
    //1. Creating SpringResourceTemplateResolver
    @Bean
    public SpringResourceTemplateResolver springTemplateResolver(){
        SpringResourceTemplateResolver springTemplateResolver = new SpringResourceTemplateResolver();
        springTemplateResolver.setApplicationContext(this.applicationContext);
        springTemplateResolver.setPrefix("/WEB-INF/pages/");
        springTemplateResolver.setSuffix(".html");
        return springTemplateResolver;
    }
    
    //2. Creating SpringTemplateEngine
    @Bean
    public SpringTemplateEngine springTemplateEngine(){
        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
        springTemplateEngine.setTemplateResolver(springTemplateResolver());
        return springTemplateEngine;
    }
    
    
    //3. Registering ThymeleafViewResolver
    @Bean
    public ViewResolver viewResolver(){
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(springTemplateEngine());
        return viewResolver;
    }
}
  • SpringContextTemplateResolver resolves templates with provided prefix and suffix.You can also add other settings such as templateMode, characterEncoding,cacheable, cacheTTLMs
  • SpringTemplateEngine process the templates, we need to pass the SpringContextTemplateResolver instance to the  SpringTemplateEngine
  • ThymeleafViewResolver will get executed at the end of the Controller execution, they process the view name which is received

We have annotated our WebMvcConfiguration class with the below annotation

  1. @Configuration indicates that our WebMvcConfiguration class can be used by the Spring IoC container as a source of bean definitions.
  2. @EnableWebMvc is equivalent to <mvc:annotation-driven /> in XML. It enables support for @Controller annotated classes. This annotation imports configuration from WebMvcConfigurationSupport
  3. @ComponentScan scans the stereotype annotations specified in @Controller, @Service etc.. annotated classes.

Equivalent XML configuration

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd	
	http://www.springframework.org/schema/context
 	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:component-scan base-package="com.javainterviewpoint"/>

     <bean id="springTemplateResolver"
          class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".html" />
    </bean>

    <bean id="springTemplateEngine"
          class="org.thymeleaf.spring5.SpringTemplateEngine">
        <property name="templateResolver" ref="springTemplateResolver" />
    </bean>

    <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="springTemplateEngine" />
    </bean>

</beans>

WebApplicationInitializer.java

We can use AbstractAnnotationConfigDispatcherServletInitializer class to register and initialize the DispatcherServlet when the Servlet used in greater than 3.0 (No need for web.xml)

package com.javainterviewpoint;

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

public class WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer 
{
    @Override
    protected Class<?>[] getRootConfigClasses()
    {
        return null;
    }

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

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

Equivalent XML configuration

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	      version="3.0">
	
    <servlet>
        <servlet-name>SpringConfig</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringConfig</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
     <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/SpringConfig-servlet.xml</param-value>
    </context-param>
	
	<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

HelloController.java

package com.javainterviewpoint;

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

@Controller
public class HelloController
{
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(Model model) {
        model.addAttribute("message", "Spring MVC Thymeleaf Hello World Example!!");
        return "hello";
    }
}
  • We have annotated our “HelloController” class with @Controller annotation which tells Spring Container to treat this class as a Controller.
  • @RequestMapping annotation on top of hello() redirects the request to this method, when the request given is “hello” and it can take only GET request which is denoted by method=RequestMethod.GET
  • Finally return to the view page “hello” along with our custom message passed to the Model class.
  • Rendering the view will be taken care by “ThymeleafViewResolver” which is configured in our “WebMvcConfiguration.java”

hello.html

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

<title>Spring MVC 5 + Thymeleaf</title>
</head>
<body>
   <h2 th:text="${message}"></h2>
</body>
</html>

In Thymeleaf, the model attributes an be accessed with the following syntax: ${attributeName}, where attributeName in our case is message.

Output

Use the command mvn tomcat7:run (when you are running through eclipse use the command tomcat7:run)  to run our application, hit on the url

http://localhost:8080/hello

Spring MVC 5 Thymeleaf

    Download Source Code

Filed Under: J2EE, Java, Spring MVC, Spring Tutorial Tagged With: Spring MVC, Spring MVC 5, Thymeleaf, Thymeleaf 3

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·