转--Spring MVC : Java模板引擎 Thymeleaf (三)

时间:2023-03-09 21:58:50
转--Spring MVC : Java模板引擎 Thymeleaf (三)

原文:http://www.csdn.com/html/topnews201408/49/1349.htm

下面以构造一个表单开始,讲解 Thymeleaf的用法。为了演示方便,还是以经典的注册为例。

这是Thymeleaf的form的形式,

   <form action="#" th:action="@{/register}" th:object="${person}" method="post">

    </form>

action="#"是固定部分,因为action是由th:action指出。@符号是Thymeleaf对URL表达的方式。这是本文的第一个知识点。

  • URL表达式

首先是绝对路径,

<a th:href="@{http://www.baidu.com}">

但最常用的肯定是相对路径。很多朋友把上下文相对路径和服务器相对路径混为一谈,其实它们是不同的。上下文相对路径都是以 / 开头的,比如是你的一个应用myapp部署在tomcat下,你可以用http://localhost:8080/myapp访问它,这里的myapp就是上下文名称。这时,

<a th:href="@{/login}">

解析后就是,

<a href="/myapp/login">

服务器相对路径和它区别是,服务器相对路径不会假设你的资源在应用上下文内,(你可能部署多个应用),也就是它允许你访问在同一个服务器的其他上下文。比如,

<a th:href="@{~/other-app/hello.html}" >

解析后就是,

<a href="/other-app/showDetails.htm">

当然还有一种相对路径(相对协议的),实际上是绝对路径,

<a th:href="@{<span style="font-family: Arial, Helvetica, sans-serif;">//code.jquery.com/jquery-1.10.2.js</span><span style="font-family: Arial, Helvetica, sans-serif;">}" ></span>

解析后就是,

<a href="//code.jquery.com/jquery-1.10.2.js">

接下来是URL的添加参数问题,

<a th:href="@{/order/details(id=3)}">

解析后,

<a href="/order/details?id=3">

多个参数可以在()内用逗号隔开。

下面的形式也是支持的,请细细体会,

<a th:href="@{/order/{id}/details(id=3,action='show_all')}">

解析后,

<a href="/order/3/details?action=show_all">

还有一个概念,叫URL fragment,什么是URL Fragment呢?

转--Spring MVC : Java模板引擎 Thymeleaf (三)

转--Spring MVC : Java模板引擎 Thymeleaf (三)

上面两张图基本说明了url fragment是什么了。

<a th:href="@{/home#all_info(action='show')}">

解析后,

<a href="/home?action=show#all_info">

下一个知识点是th:object,

  • th:object

该属性在Thymeleaf很常见,但form会强制要求你写这个。为了整合Spring,它对form里面的th:object规定如下:

  1. 必须是变量表达式(${...}),代表模型的名字,且不能向模型的属性导航,就是${a}合法,但${a.b}不合法
  2. form内不能有其他th:object,也就是HTML的表单不能嵌套
你可能猜到,这个object就是向后台传递数据的。
在*有个提问,"send datas from html to controller in thymeleaf?",采纳的答案是这样的:
controller:
@RequestMapping(value = "/processForm", method=RequestMethod.POST)
public String processForm(@ModelAttribute(value="foo") Foo foo) {
...
}

html:

<form action="#" th:action="@{/processForm}" th:object="${foo}" method="post">
<input type="text" th:field="*{bar}" />
<input type="submit" />
</form>

Foo.java

public class Foo {
private String bar; public String getBar() {
return bar;
} public void setBar(String bar) {
this.bar = bar;
}
}

看完之后,你肯定就能豁然开朗了。

还有个知识点是 th:field。
  • th:field

这个属性在Spring-mvc里很重要,承担着绑定后台Bean属性的重任,这和JSP标签里的path很像。

对不同类型的input,th:field有些差异。这个之后再说。
要记住的是,th:field必须是选择表达式(*{...})。
最后,你可能对前面提到的表达式有疑问了。
变量表达式 ${...}就是OGNL表达式。如果你使用springstandard,就是Spring表达式(SpEL)。
给个例子你就明白了,
<span th:text="${book.author.name}">

选择表达式*{...}很像变量表达式,不同在于,它执行的是前面选择的对象。

<div th:object="${book}">
...
<span th:text="*{title}">...</span>
...
</div>

前面选择了book,接下来就按照它求值。

还有一个表达式,前面没有出现。国际化表达式#{...},顾名思义是处理国际化的。
<table>
...
<th th:text="#{header.address.city}">...</th>
<th th:text="#{header.address.country}">...</th>
...
</table>

国际化资源一般是在.properties文件定义。