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:
- Create a simple Maven webapp Project “SpringMVCThymeleaf” and create a package for our source files “com.javainterviewpoint” under src/main/java
- 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>
- Create the Java class HelloController.java,WebApplicationInitializer.java and WebMvcConfiguration.java under com.javainterviewpoint folder.
- Place the hello.jsp under the sub directory under WEB-INF/pages
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
- @Configuration indicates that our WebMvcConfiguration class can be used by the Spring IoC container as a source of bean definitions.
- @EnableWebMvc is equivalent to <mvc:annotation-driven /> in XML. It enables support for @Controller annotated classes. This annotation imports configuration from WebMvcConfigurationSupport
- @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
Leave a Reply