Spring MVC application with thymeleaf
Objective: Substitue view-layer web technologies such as JSP.
Pre-req: Spring STS as development environment
Why thymeleaf?:
Steps:
Source code: https://github.com/nnjoshi14/ess/tree/0.1
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.
Steps:
- Create spring mvc project
- Go to File > New > Spring MVC Project
- Select project name (ess) and top level package (com.njoshi.ess)
- Right click on project name > run on server to make sure project configuration is working
- Add thymeleaf dependancy
- Open pom.xml
- Add following dependancy
- <dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring3</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
- 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="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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"> <context:component-scan base-package="com.njoshi.ess" /> <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".html" /> <property name="templateMode" value="HTML5" /> </bean> <bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> </bean> <bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine" /> </bean> </beans>
- Changes in home.jsp
- Change home.jsp to home.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Home</title> </head> <body> <h1>Hello world!</h1> <p th:text="${serverTime}">Welcome to time check page. Site is down!</p> </body> </html>
Source code: https://github.com/nnjoshi14/ess/tree/0.1