SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-006- 使用thymeleaf(TemplateResolver、SpringTemplateEngine、ThymeleafViewResolver、th:include、th:object、th:field="*{firstName}")
一、在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 © 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}")的更多相关文章
- 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 ...
- SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-003- SPRING的GENERAL TAG LIBRARY简介及用<s:message>和ReloadableResourceBundleMessageSource实现国际化
一. SPRING支持的GENERAL TAG LIBRARY 1. 二.用<s:message>和ReloadableResourceBundleMessageSource实现国际化 1 ...
- 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 ...
- 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 ...
- 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 ...
- 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 ...
- 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- ...
- 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 ...
- 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 ...
随机推荐
- Android Studio依赖dependencies和Eclipse加上lib包解决重复编译某些项目的问题
android运行时编译,可以在android的dependencies里面加语句, 一般是compile 'com.android.support:appcompat-v7:22.2.1' comp ...
- Java中内存空间的分配及回收
Java中内存分为: 栈:存放简单数据类型变量(值和变量名都存在栈中),存放引用数据类型的变量名以及它所指向的实例的首地址. 堆:存放引用数据类型的实例. Java的垃圾回收: 由一个后台线程GC(G ...
- Meteor:用户账号管理添加密码和微博weibo账号系统支持
Meteor账户系统构建与accounts-base包之上,并为publish和methods提供userId的顶层支持.核心包提供的功能有:数据库中的用户记录支持:额外的包提供密码安全验证:第三方登 ...
- 解决自定义BackItem与Pop Gesture冲突的问题
在做项目的时候遇到的这个问题, 一开始项目要求自定义导航栏返回按钮,结果发生了没法手势返回的问题,以为是需要添加拖拽手势呢,结果折腾了一下午没有实现想要的效果.接着一直百度问题,才发现跑偏了,犯了一个 ...
- IOS开发之NSPredicate谓词的用法
编程的人员不管是上过大学还是从培训机构出来的或做后台的.前端的都应该SQL语句有所了解,我们知道,在SQL语句当中 where 条件表达式可以对二维关系表的数据做条件筛选.微软的C# .net中也实现 ...
- 用Python进行语音信号处理
1.语音信号处理之时域分析-音高追踪及其Python实现 2.语音信号处理之时域分析-音高及其Python实现 参考: 1.NumPy
- mysql innodb 数据打捞(四)innodb 簇不连续页扫描提取(试验)
一,用winhex把正常页有意做成不连续的两部分,把后8K向后移动4K,中间隔开4K,启动第一次扫描; 扫描结果是,没有提取到有效页面,但在输出目录生成两个文件:upper.pages和upper.l ...
- 超强的ACM题目类型总结
转:初期: 一.基本算法: (1)枚举. (poj1753,poj2965) (2)贪心(poj1328,poj2109,poj2586) (3)递归和分治法. ...
- sgu 105 Div 3
一个数能整除3当且仅当各位数之和能整除3. 有了这个规律就好办了, 但是呢,仔细一看, n太大了, 都到 2^31 了.所以简单的模拟肯定不行. 这种貌似像数论的题,一时找不到好办法,就打表! 打表出 ...
- CSS3 基本知识
1.CSS3 简介 CSS 指层叠样式表 (Cascading Style Sheets),用于控制网页的样式和布局,CSS3 是最新的 CSS 标准. 在网页制作时采用层叠样式表,可以有效的对页面的 ...