一、在Spring中使用thymeleaf的步骤

1.配置

In order to use Thymeleaf with Spring, you’ll need to configure three beans that enable Thymeleaf-Spring integration:
 A ThymeleafViewResolver that resolves Thymeleaf template views from logical view names
 A SpringTemplateEngine to process the templates and render the results
 A TemplateResolver that loads Thymeleaf templates

ThymeleafViewResolver is an implementation of Spring MVC ’s ViewResolver . Just like any view resolver, it takes a logical view name and resolves a view. But in this case,that view is ultimately a Thymeleaf template.

Notice that the ThymeleafViewResolver bean is injected with a reference to theSpringTemplateEngine bean. SpringTemplateEngine is a Spring-enabled Thymeleaf engine for parsing templates and rendering results based on those templates. As you can see, it’s injected with a reference to the TemplateResolver bean.

TemplateResolver is what ultimately locates the templates. It’s configured much as you previously configured InternalResourceViewResolver with prefix and suffix properties. The prefix and suffix are applied to the logical view name to locate the Thymeleaf template. Its templateMode property is also set to HTML5 , indicating that the templates resolved are expected to render HTML5 output.

(1)Java配置

 package spittr.web;

 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.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver; @Configuration
@EnableWebMvc
@ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter { @Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
@Bean
public SpringTemplateEngine templateEngine(TemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
} @Bean
public TemplateResolver templateResolver() {
TemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
//indicating that the templates resolved are expected to render HTML5 output
templateResolver.setTemplateMode("HTML5"); return templateResolver;
} @Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
} }

(2)Xml配置

 <bean id="viewResolver"
class="org.thymeleaf.spring3.view.ThymeleafViewResolver"
p:templateEngine-ref="templateEngine" />
<bean id="templateEngine"
class="org.thymeleaf.spring3.SpringTemplateEngine"
p:templateResolver-ref="templateResolver" />
<bean id="templateResolver" class=
"org.thymeleaf.templateresolver.ServletContextTemplateResolver"
p:prefix="/WEB-INF/templates/"
p:suffix=".html"
p:templateMode="HTML5" />

2.定义Thymeleaf模板

(1)标签介绍

 <a th:href="@{/spitter/register}">Register</a>

 <div th:fragment="header">

 <img th:src="@{/resources/images/spitter_logo_50.png}" border="0" /></a>

 <div id="header" th:include="page :: header"></div>
<form method="POST" th:object="${spitter}"> <div class="errors" th:if="${#fields.hasErrors('*')}">
<ul>
<li th:each="err : ${#fields.errors('*')}"
th:text="${err}">Input is incorrect</li>
</ul>
</div> <label th:class="${#fields.hasErrors('firstName')}? 'error'">First Name</label>:
<input type="text" th:field="*{firstName}"
th:class="${#fields.hasErrors('firstName')}? 'error'" /><br/> <span th:text="${spitter.username}">username</span><br/> <li th:each="spittle : ${spittleList}"
th:id="'spittle_' + ${spittle.id}">
<div class="spittleMessage" th:text="${spittle.message}">Spittle message</div>
<div>
<span class="spittleTime" th:text="${spittle.time}">spittle timestamp</span>
<span class="spittleLocation" th:text="'{' + ${spittle.latitude} + ', ' + ${spittle.longitude} + ')'">lat, long</span>
</div>
</li>

thymeleaf标签的优势是定在原生的html里,不会破坏原来的html结构,可以用浏览器直接打开,只是动态计算的东西无效。

(2)home.html

 <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spitter</title>
<link rel="stylesheet"
type="text/css"
th:href="@{/resources/style.css}"></link>
</head>
<body>
<div id="header" th:include="page :: header"></div> <div id="content">
<h1>Welcome to Spitter</h1> <a th:href="@{/spittles}">Spittles</a> |
<a th:href="@{/spitter/register}">Register</a> <br/> View: <span th:text="${view}">unknown</span>
</div>
<div id="footer" th:include="page :: copy"></div>
</body>
</html>

(2.1)registerForm.html

 <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spitter</title>
<link rel="stylesheet" type="text/css"
th:href="@{/resources/style.css}"></link>
</head>
<body>
<div id="header" th:include="page :: header"></div> <div id="content">
<h1>Register</h1> <form method="POST" th:object="${spitter}">
<div class="errors" th:if="${#fields.hasErrors('*')}">
<ul>
<li th:each="err : ${#fields.errors('*')}"
th:text="${err}">Input is incorrect</li>
</ul>
</div>
<label th:class="${#fields.hasErrors('firstName')}? 'error'">First Name</label>:
<input type="text" th:field="*{firstName}"
th:class="${#fields.hasErrors('firstName')}? 'error'" /><br/> <label th:class="${#fields.hasErrors('lastName')}? 'error'">Last Name</label>:
<input type="text" th:field="*{lastName}"
th:class="${#fields.hasErrors('lastName')}? 'error'" /><br/> <label th:class="${#fields.hasErrors('email')}? 'error'">Email</label>:
<input type="text" th:field="*{email}"
th:class="${#fields.hasErrors('email')}? 'error'" /><br/> <label th:class="${#fields.hasErrors('username')}? 'error'">Username</label>:
<input type="text" th:field="*{username}"
th:class="${#fields.hasErrors('username')}? 'error'" /><br/> <label th:class="${#fields.hasErrors('password')}? 'error'">Password</label>:
<input type="password" th:field="*{password}"
th:class="${#fields.hasErrors('password')}? 'error'" /><br/>
<input type="submit" value="Register" /> </form>
</div>
<div id="footer" th:include="page :: copy"></div>
</body>
</html>

解析:

a)由<form th:object="${spitter}">指定了对象,By using th:field="*{firstName}", you get both a value attribute set to the value of firstName and also a name attribute set to firstName .

b)<li th:each>:

The th:each attribute on the <li> tag instructs Thymeleaf to render the <li> one time for each error,assigning the current error in each iteration to a variable named err .
The <li> tag also has a th:text attribute. This attribute instructs Thymeleaf to evaluate an expression (in this case, the value of the err variable) and render its value as the body of the <li> tag. In effect, there will be one <li> for each error, displaying
the text of that error.

c)You may be wondering about the difference between the expressions wrapped with ${} and those wrapped with *{} . The ${} expressions (such as ${spitter} ) are variable expressions. Normally, these are Object-Graph Navigation Language ( OGNL )expressions (http://commons.apache.org/proper/commons-ognl/). But when used with Spring, they’re SpEL expressions. In the case of ${spitter} , it resolves to the model property whose key is spitter .

As for *{} expressions, they’re selection expressions. Whereas variable expressions are evaluated against the entire SpEL context, selection expressions are evaluated on a selected object. In the case of the form, the selected object is the one given in the

(3)page.html

 <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"> <body> <div th:fragment="header">
<a th:href="@{/}">
<img th:src="@{/resources/images/spitter_logo_50.png}" border="0" /></a>
</div> <div>Content goes here</div> <div th:fragment="copy">Copyright &copy; Craig Walls</div>
</body> </html>

(4)spittles.html

 <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spitter</title>
<link rel="stylesheet"
type="text/css"
th:href="@{/resources/style.css}" ></link>
</head>
<body>
<div id="header" th:include="page :: header"></div> <div id="content">
<div class="spittleForm">
<h1>Spit it out...</h1>
<form method="POST" name="spittleForm">
<input type="hidden" name="latitude" />
<input type="hidden" name="longitude" />
<textarea name="message" cols="80" rows="5"></textarea><br/>
<input type="submit" value="Add" />
</form>
</div>
<div class="listTitle">
<h1>Recent Spittles</h1>
<ul class="spittleList">
<li th:each="spittle : ${spittleList}"
th:id="'spittle_' + ${spittle.id}">
<div class="spittleMessage" th:text="${spittle.message}">Spittle message</div>
<div>
<span class="spittleTime" th:text="${spittle.time}">spittle timestamp</span>
<span class="spittleLocation" th:text="'{' + ${spittle.latitude} + ', ' + ${spittle.longitude} + ')'">lat, long</span>
</div>
</li>
</ul>
</div>
</div> <div id="footer" th:include="page :: copy"></div>
</body>
</html>

(5)spittle.html

 <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spitter</title>
<link rel="stylesheet"
type="text/css"
th:href="@{/resources/style.css}"></link>
</head>
<body>
<div id="header" th:include="page :: header"></div> <div id="content">
<div class="spittleView">
<div class="spittleMessage" th:text="#{spittle.message}">Spittle message</div>
<div>
<span class="spittleTime" th:text="#{spittle.time}">spittle timestamp</span>
</div>
</div>
</div>
<div id="footer" th:include="page :: copy"></div> </body>
</html>

(6)profile.html

 <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spitter</title>
<link rel="stylesheet"
type="text/css"
th:href="@{/resources/style.css}"></link>
</head>
<body>
<div id="header" th:include="page :: header"></div> <div id="content">
<h1>Your Profile</h1>
<span th:text="${spitter.username}">username</span><br/>
<span th:text="${spitter.firstName}">First</span> <span th:text="${spitter.lastName}">Last</span><br/>
<span th:text="${spitter.email}">email</span>
</div> <div id="footer" th:include="page :: copy"></div>
</body>
</html>

二、SpringMVC view层的总结

Thymeleaf is a compelling option because it enables the creation of natural templates that are still pure HTML and can be edited and viewed in the raw as if they were static HTML , but still render dynamic model data at runtime. Moreover, Thymeleaf templates are largely decoupled from servlets, enabling them to be used in places where JSP s can’t.

SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-006- 使用thymeleaf(TemplateResolver、SpringTemplateEngine、ThymeleafViewResolver、th:include、th:object、th:field="*{firstName}")的更多相关文章

  1. SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-002- Spring的JSP标签之form标签(<sf:input><sf:errors><sf:form>)

    一. Spring offers two JSP tag libraries to help define the view of your Spring MVC web views. One tag ...

  2. SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-003- SPRING的GENERAL TAG LIBRARY简介及用<s:message>和ReloadableResourceBundleMessageSource实现国际化

    一. SPRING支持的GENERAL TAG LIBRARY 1. 二.用<s:message>和ReloadableResourceBundleMessageSource实现国际化 1 ...

  3. SPRING IN ACTION 第4版笔记-第六章Rendering web views-001- Spring支持的View Resolver、InternalResourceViewResolver、JstlView

    一.Spring支持的View Resolver 二.InternalResourceViewResolver Spring supports JSP views in two ways: Inte ...

  4. SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-005- 使用ApacheTiles(TilesConfigurer、TilesViewResolver、<put-attribute>、<t:insertAttribute>)

    一. 1.定义TilesConfigurer.TilesViewResolver的bean 注意有tiles2和tiles3,这里使用tiles3 (1)java形式 package spittr.w ...

  5. SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-004- <s:url>、<s:escapeBody>标签

    一.<s:url> <s:url>可以直接生成一个url或url变量,它会在href的基础上加上应用context 1. <a href="<s:url ...

  6. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)

    一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...

  7. SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-006Spring-Data的运行规则(@EnableJpaRepositories、<jpa:repositories>)

    一.JpaRepository 1.要使Spring自动生成实现类的步骤 (1)配置文件xml <?xml version="1.0" encoding="UTF- ...

  8. SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-003编写JPA-based repository( @PersistenceUnit、 @PersistenceContext、PersistenceAnnotationBeanPostProcessor)

    一.注入EntityManagerFactory的方式 package com.habuma.spittr.persistence; import java.util.List; import jav ...

  9. SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-002设置JPA的EntityManagerFactory(<persistence-unit>、<jee:jndi-lookup>)

    一.EntityManagerFactory的种类 1.The JPA specification defines two kinds of entity managers:  Applicatio ...

随机推荐

  1. 微信公众账号 Senparc.Weixin.MP SDK 开发教程

    http://www.cnblogs.com/szw/archive/2013/05/14/weixin-course-index.html 微信公众账号 Senparc.Weixin.MP SDK ...

  2. 第五篇、HTML标签类型

    <!--1.块级标签 独占一行,可以设置高度和宽度 如:div p h ul li  -----display: none(隐藏标签) block(让行内标签变块级标签) inline(让块级标 ...

  3. C#上传图片和生成缩略图以及图片预览

    因工作需要,上传图片要增加MIME类型验证和生成较小尺寸的图片用于浏览.根据网上代码加以修改做出如下效果图: 前台代码如下: <html xmlns="http://www.w3.or ...

  4. CSS3几个速记标签2

    @font-face:CSS3允许使用自己的字体,用户会自动下载     语法:@font-face{font-family:---:src:url(---)}     如果要使用粗体,必须新添加另一 ...

  5. C# 刷新当前窗体

    在有多个窗体时,刷新当前激活的窗体 在MainForm.cs中: private void m_reflashtoolStripButton1_Click(object sender, EventAr ...

  6. C# 调用load事件

    在一个函数或者事件中调用另外的事件,例如调用Load事件 private void EventForm_Load(object sender, EventArgs e) { //相关内容 } priv ...

  7. OpenCV2学习笔记03:Qt中配置OpenCV环境

    在Qt中开发基于OpenCV的应用时,需要配置对应函数库到环境变量,这时候我们需要使用到qmake能够识别的变量来指定环境变量. INCLUDEPATH: 用于指定搜索头文件到文件夹路径. LIBS: ...

  8. checked

    <!doctype html><html lang="en"> <head> <meta charset="UTF-8" ...

  9. mysql触发器的例子--插入前更新数据

    本文介绍下,一个mysql触发器的例子,在数据插入前更新相关内容,有需要的朋友参考下. mysql触发器的例子,如下: view source print? 001 mysql> CREATE  ...

  10. 关于NRW算法(Quorum算法)

    在分布式系统中,冗余数据是保证可靠性的手段,因此冗余数据的一致性维护就非常重要.一般而言,一个写操作必须要对所有的冗余数据都更新完成了,才能称为成功结束.比如一份数据在5台设备上有冗余,因为不知道读数 ...