2023年3月

spring boot(四):thymeleaf使用详解 - 纯洁的微笑 - 博客园
https://www.cnblogs.com/ityouknow/p/5833560.html

在上篇文章
springboot(二):web综合开发
中简单介绍了一下thymeleaf,这篇文章将更加全面详细的介绍thymeleaf的使用。thymeleaf 是新一代的模板引擎,在spring4.0中推荐使用thymeleaf来做前端模版引擎。

thymeleaf介绍

简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点:

  • 1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

  • 2.Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

  • 3.Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

标准表达式语法

它们分为四类:

  • 1.变量表达式
  • 2.选择或星号表达式
  • 3.文字国际化表达式
  • 4.URL表达式

变量表达式

变量表达式即OGNL表达式或Spring EL表达式(在Spring术语中也叫model attributes)。如下所示:
${session.user.name}

它们将以HTML标签的一个属性来表示:

<spanth:text="${book.author.name}">  
<lith:each="book : ${books}">  

选择(星号)表达式

选择表达式很像变量表达式,不过它们用一个预先选择的对象来代替上下文变量容器(map)来执行,如下:
*{customer.name}

被指定的object由th:object属性定义:

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

文字国际化表达式

文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties),用Key索引Value,还可以提供一组参数(可选).

    #{main.title}  
    #{message.entrycreated(${entryId})}  

可以在模板文件中找到这样的表达式代码:

    <table>  
      ...  
      <thth:text="#{header.address.city}">...</th>  
      <thth:text="#{header.address.country}">...</th>  
      ...  
    </table>  

URL表达式

URL表达式指的是把一个有用的上下文或回话信息添加到URL,这个过程经常被叫做URL重写。
@{/order/list}
URL还可以设置参数:
@{/order/details(id=${orderId})}
相对路径:
@{../documents/report}

让我们看这些表达式:

    <formth:action="@{/createOrder}">  
    <ahref="main.html"th:href="@{/main}">

变量表达式和星号表达有什么区别吗?

如果不考虑上下文的情况下,两者没有区别;星号语法评估在选定对象上表达,而不是整个上下文
什么是选定对象?就是父标签的值,如下:

  <divth:object="${session.user}">
    <p>Name: <spanth:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <spanth:text="*{lastName}">Pepper</span>.</p>
    <p>Nationality: <spanth:text="*{nationality}">Saturn</span>.</p>
  </div>

这是完全等价于:

  <divth:object="${session.user}">
      <p>Name: <spanth:text="${session.user.firstName}">Sebastian</span>.</p>
      <p>Surname: <spanth:text="${session.user.lastName}">Pepper</span>.</p>
      <p>Nationality: <spanth:text="${session.user.nationality}">Saturn</span>.</p>
  </div>

当然,美元符号和星号语法可以混合使用:

  <divth:object="${session.user}">
      <p>Name: <spanth:text="*{firstName}">Sebastian</span>.</p>
      <p>Surname: <spanth:text="${session.user.lastName}">Pepper</span>.</p>
      <p>Nationality: <spanth:text="*{nationality}">Saturn</span>.</p>
  </div>

表达式支持的语法

字面(Literals)

  • 文本文字(Text literals):
    'one text', 'Another one!',…
  • 数字文本(Number literals):
    0, 34, 3.0, 12.3,…
  • 布尔文本(Boolean literals):
    true, false
  • 空(Null literal):
    null
  • 文字标记(Literal tokens):
    one, sometext, main,…

文本操作(Text operations)

  • 字符串连接(String concatenation):
    +
  • 文本替换(Literal substitutions):
    |The name is ${name}|

算术运算(Arithmetic operations)

  • 二元运算符(Binary operators):
    +, -, *, /, %
  • 减号(单目运算符)Minus sign (unary operator):
    -

布尔操作(Boolean operations)

  • 二元运算符(Binary operators):
    and, or
  • 布尔否定(一元运算符)Boolean negation (unary operator):
    !, not

比较和等价(Comparisons and equality)

  • 比较(Comparators):
    >, <, >=, <= (gt, lt, ge, le)
  • 等值运算符(Equality operators):
    ==, != (eq, ne)

条件运算符(Conditional operators)

  • If-then:
    (if) ? (then)
  • If-then-else:
    (if) ? (then) : (else)
  • Default: (value) ?:
    (defaultvalue)

所有这些特征可以被组合并嵌套:

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))



常用th标签都有那些?

关键字 功能介绍 案例
th:id 替换id <input th:id="'xxx' + ${collect.id}"/>
th:text 文本替换 <p th:text="${collect.description}">description</p>
th:utext 支持html的文本替换 <p th:utext="${htmlcontent}">conten</p>
th:object 替换对象 <div th:object="${session.user}">
th:value 属性赋值 <input th:value="${user.name}" />
th:with 变量赋值运算 <div th:with="isEven=${prodStat.count}%2==0"></div>
th:style 设置样式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick 点击事件 th:onclick="'getCollect()'"
th:each 属性赋值 tr th:each="user,userStat:${users}">
th:if 判断条件 <a th:if="${userId == collect.userId}" >
th:unless 和th:if判断相反 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href 链接地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch 多路选择 配合th:case 使用 <div th:switch="${user.role}">
th:case th:switch的一个分支 <p th:case="'admin'">User is an administrator</p>
th:fragment 布局标签,定义一个代码片段,方便其它地方引用 <div th:fragment="alert">
th:include 布局标签,替换内容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace 布局标签,替换整个标签到引入的文件 <div th:replace="fragments/header :: title"></div>
th:selected selected选择框 选中 th:selected="(${xxx.id} == ${configObj.dd})"
th:src 图片类地址引入 <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline 定义js脚本可以使用变量 <script type="text/javascript" th:inline="javascript">
th:action 表单提交的地址 <form action="subscribe.html" th:action="@{/subscribe}">
th:remove 删除某个属性 <tr th:remove="all"> 1.all:删除包含标签和所有的孩子。2.body:不包含标记删除,但删除其所有的孩子。3.tag:包含标记的删除,但不删除它的孩子。4.all-but-first:删除所有包含标签的孩子,除了第一个。5.none:什么也不做。这个值是有用的动态评估。
th:attr 设置标签属性,多个属性可以用逗号分隔 比如
th:attr="src=@{/image/aa.jpg},title=#{logo}"
,此标签不太优雅,一般用的比较少。

还有非常多的标签,这里只列出最常用的几个,由于一个标签内可以包含多个th:x属性,其生效的优先级顺序为:
include,each,if/unless/switch/case,with,attr/attrprepend/attrappend,value/href,src ,etc,text/utext,fragment,remove。



几种常用的使用方法

1、赋值、字符串拼接

 <pth:text="${collect.description}">description</p>
 <spanth:text="'Welcome to our application, ' + ${user.name} + '!'">

字符串拼接还有另外一种简洁的写法

<spanth:text="|Welcome to our application, ${user.name}!|">

2、条件判断 If/Unless

Thymeleaf中使用th:if和th:unless属性进行条件判断,下面的例子中,
<a>
标签只有在
th:if
中条件成立时才显示:

<ath:if="${myself=='yes'}"> </i> </a>
<ath:unless=${session.user!=null}th:href="@{/login}">Login</a>

th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。

也可以使用
(if) ? (then) : (else)
这种语法来判断显示的内容

3、for 循环

  <trth:each="collect,iterStat : ${collects}"> 
     <thscope="row"th:text="${collect.id}">1</th>
     <td>
        <imgth:src="${collect.webLogo}"/>
     </td>
     <tdth:text="${collect.url}">Mark</td>
     <tdth:text="${collect.title}">Otto</td>
     <tdth:text="${collect.description}">@mdo</td>
     <tdth:text="${terStat.index}">index</td>
 </tr>

iterStat称作状态变量,属性有:

  • index:当前迭代对象的index(从0开始计算)
  • count: 当前迭代对象的index(从1开始计算)
  • size:被迭代对象的大小
  • current:当前迭代变量
  • even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算)
  • first:布尔值,当前循环是否是第一个
  • last:布尔值,当前循环是否是最后一个

4、URL

URL在Web应用模板中占据着十分重要的地位,
需要特别注意的是Thymeleaf对于URL的处理是通过语法@{
...}来处理的。
如果需要Thymeleaf对URL进行渲染,那么务必使用th:href,th:src等属性,下面是一个例子

<!-- Will produce 'http://localhost:8080/standard/unread' (plus rewriting) -->
 <ath:href="@{/standard/{type}(type=${type})}">view</a>

<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<ahref="details.html"th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

设置背景

<divth:style="'background:url(' + @{/<path-to-image>} + ');'"></div>

根据属性值改变背景

 <divclass="media-object resource-card-image"th:style="'background:url(' + @{(${collect.webLogo}=='' ? 'img/favicon.png' : ${collect.webLogo})} + ')'"></div>

几点说明:

  • 上例中URL最后的
    (orderId=${o.id})
    表示将括号内的内容作为URL参数处理,该语法避免使用字符串拼接,大大提高了可读性
  • @{...}
    表达式中可以通过
    {orderId}
    访问Context中的orderId变量
  • @{/order}
    是Context相关的相对路径,在渲染时会自动添加上当前Web应用的Context名字,假设context名字为app,那么结果应该是/app/order

5、内联js

内联文本:[[...]]内联文本的表示方式,使用时,必须先用th:inline="text/javascript/none"激活,th:inline可以在父级标签内使用,甚至作为body的标签。内联文本尽管比th:text的代码少,不利于原型显示。

<script th:inline="javascript">
/*<![CDATA[*/
...
var username = /*[[${sesion.user.name}]]*/ 'Sebastian';
var size = /*[[${size}]]*/ 0;
...
/*]]>*/
</script>

js附加代码:

/*[+var msg = 'This is a working application';+]*/

js移除代码:

/*[- */
var msg = 'This is a non-working template';
/* -]*/

6、内嵌变量

为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#直接访问:

  • dates :
    java.util.Date的功能方法类。
  • calendars :
    类似#dates,面向java.util.Calendar
  • numbers :
    格式化数字的功能方法类
  • strings :
    字符串对象的功能类,contains,startWiths,prepending/appending等等。
  • objects:
    对objects的功能类操作。
  • bools:
    对布尔值求值的功能方法。
  • arrays:
    对数组的功能类方法。
  • lists:
    对lists功能类方法
  • sets
  • maps
    ...

下面用一段代码来举例一些常用的方法:

dates

/*
 * Format date with the specified pattern
 * Also works with arrays, lists or sets
 */
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}

/*
 * Create a date (java.util.Date) object for the current date and time
 */
${#dates.createNow()}

/*
 * Create a date (java.util.Date) object for the current date (time set to 00:00)
 */
${#dates.createToday()}

strings

/*
 * Check whether a String is empty (or null). Performs a trim() operation before check
 * Also works with arrays, lists or sets
 */
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}

/*
 * Check whether a String starts or ends with a fragment
 * Also works with arrays, lists or sets
 */
${#strings.startsWith(name,'Don')}                  // also array*, list* and set*
${#strings.endsWith(name,endingFragment)}           // also array*, list* and set*

/*
 * Compute length
 * Also works with arrays, lists or sets
 */
${#strings.length(str)}

/*
 * Null-safe comparison and concatenation
 */
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}

/*
 * Random
 */
${#strings.randomAlphanumeric(count)}



使用thymeleaf布局

使用thymeleaf布局非常的方便

定义代码片段

<footerth:fragment="copy"> 
&copy; 2016
</footer>

在页面任何地方引入:

<body> 
  <divth:include="footer :: copy"></div>
  <divth:replace="footer :: copy"></div>
 </body>

th:include 和 th:replace区别,include只是加载,replace是替换

返回的HTML如下:

<body> 
   <div> &copy; 2016 </div> 
  <footer>&copy; 2016 </footer> 
</body>

下面是一个常用的后台页面布局,将整个页面分为头部,尾部、菜单栏、隐藏栏,点击菜单只改变content区域的页面

<bodyclass="layout-fixed">
  <divth:fragment="navbar"class="wrapper"role="navigation">
    <divth:replace="fragments/header :: header">Header</div>
    <divth:replace="fragments/left :: left">left</div>
    <divth:replace="fragments/sidebar :: sidebar">sidebar</div>
    <divlayout:fragment="content"id="content"></div>
    <divth:replace="fragments/footer :: footer">footer</div>
  </div>
</body>

任何页面想使用这样的布局值只需要替换中见的 content模块即可

 <htmlxmlns:th="http://www.thymeleaf.org"layout:decorator="layout">
   <body>
      <sectionlayout:fragment="content">
    ...

也可以在引用模版的时候传参

<headth:include="layout :: htmlhead"th:with="title='Hello'"></head>

layout 是文件地址,如果有文件夹可以这样写 fileName/layout:htmlhead
htmlhead 是指定义的代码片段 如
th:fragment="copy"

源码案例

这里有一个开源项目几乎使用了这里介绍的所有标签和布局,大家可以参考:
cloudfavorites

Thymeleaf
是现代化服务器端的Java模板引擎,不同与JSP和FreeMarker,Thymeleaf的语法更加接近HTML,并且也有不错的扩展性。详细资料可以浏览
官网
。本文主要介绍Thymeleaf模板的使用说明。

模板(template fragments)

定义和引用模板

日常开发中,我们经常会将导航栏,页尾,菜单等部分提取成模板供其它页面使用。

在Thymeleaf 中,我们可以使用
th:fragment
属性来定义一个模板。

我们可以新建一个简单的页尾模板,如:/WEB-INF/templates/footer.html,内容如下:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">

<body>
<div th:fragment="copyright">
© 2016 xxx
</div>
</body>
</html>

上面定义了一个叫做
copyright
的片段,接着我们可以使用
th:include
或者
th:replace
属性来使用它:

<body>
...
<div th:include="footer :: copyright"></div>
</body>

其中th:include中的参数格式为templatename::[domselector],
其中templatename是模板名(如footer),domselector是可选的dom选择器。如果只写templatename,不写domselector,则会加载整个模板。

当然,这里我们也可以写表达式:

<div th:include="footer :: (${user.isAdmin}? #{footer.admin} : #{footer.normaluser})"></div>

模板片段可以被包含在任意
th:*
属性中,并且可以使用目标页面中的上下文变量。

不通过th:fragment引用模板

通过强大的dom选择器,我们可以在不添加任何Thymeleaf属性的情况下定义模板:

...
<div id="copy-section">
&copy; xxxxxx
</div>
...

通过dom选择器来加载模板,如id为copy-section

<body>
...
<div th:include="footer :: #copy-section">
</div>
</body>

th:include 和 th:replace区别

th:include 是加载模板的内容,而th:replace则会替换当前标签为模板中的标签

例如如下模板:

<footer th:fragment="copy"> 
&copy; 2016
</footer>

我们通过th:include 和 th:replace来加载模板

<body> 
<div th:include="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
</body>

返回的HTML如下:

<body> 
   <div> &copy; 2016 </div> 
  <footer>&copy; 2016 </footer> 
</body>

模板参数配置

th:fragment定义模板的时候可以定义参数:

<div th:fragment="frag (onevar,twovar)"> 
<p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>

在 th:include 和 th:replace中我们可以这样传参:

<div th:include="::frag (${value1},${value2})">...</div>
<div th:include="::frag (onevar=${value1},twovar=${value2})">...</div>

此外,定义模板的时候签名也可以不包括参数:
<div th:fragment="frag">
,我们任然可以通过
<div th:include="::frag (onevar=${value1},twovar=${value2})">...</div>
这种方式调用模板。这其实和
<div th:include="::frag" th:with="onevar=${value1},twovar=${value2}">
起到一样的效果

th:assert 断言

我们可以通过th:assert来方便的验证模板参数
<header th:fragment="contentheader(title)" th:assert="${!#strings.isEmpty(title)}">...</header>

th:remove 删除代码

假设我们有一个产品列表模板:

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    <td>
      <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
      <a href="comments.html" 
th:href="@{/product/comments(prodId=${prod.id})}"
th:unless="${#lists.isEmpty(prod.comments)}">
view</a> </td> </tr> </table>

这时一个很常规的模板,但是,当我们直接在浏览器里面打开它(不(不使用Thymeleaf ),它实在不是一个很好的原型。因为它的表格中只有一行,而我们的原型需要更饱满的表格。

如果我们直接添加了多行,原型是没有问题了,但通过Thymeleaf输出的HTML又包含了这些事例行。

这时通过th:remove属性,可以帮我们解决这个两难的处境,

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    <td>
      <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
      <a href="comments.html" 
th:href="@{/product/comments(prodId=${prod.id})}"
th:unless="${#lists.isEmpty(prod.comments)}">
view</a> </td> </tr> <tr class="odd" th:remove="all"> <td>Blue Lettuce</td> <td>9.55</td> <td>no</td> <td> <span>0</span> comment/s </td> </tr> <tr th:remove="all"> <td>Mild Cinnamon</td> <td>1.99</td> <td>yes</td> <td> <span>3</span> comment/s <a href="comments.html">view</a> </td> </tr> </table>

其中th:remove的参数有如下几种:

  • all 删除当前标签和其内容和子标签
  • body 不删除当前标签,但是删除其内容和子标签
  • tag 删除当前标签,但不删除子标签
  • all-but-first 删除除第一个子标签外的其他子标签
  • none 啥也不干

当然,我们也可以通过表达式来传参,
<a href="/something" th:remove="${condition}? tag : none">Link text not to be removed</a>


以上为Thymeleaf中模板的一些用法,各位看官请点赞。

<htmlxmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org">
<body>
    <divth:fragment="crudmodal"> //主要是这里
        <!--modify modal-->
        <divclass="modal fade"id="crudmodal_modify"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"aria-hidden="true">

<htmlxmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org">
<body>
    <!--crudmodal-->
    <!--add modal-->
    <divth:fragment="crudmodal">

        <!--modify modal-->
        <divclass="modal fade"id="crudmodal_modify"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"aria-hidden="true">
            <divstyle="width: 900px;"class="modal-dialog">
                <divclass="modal-content">
                    <divclass="modal-header">
                        <buttontype="button"class="close"data-dismiss="modal"aria-hidden="true">&times;</button>
                        <h4id="modaltitle"class="modal-title">送检人员</h4>
                    </div>
                    <divclass="modal-body">
                        <divclass="panel panel-default">
                            <formclass="form-horizontal"style="width: 60%;">

                                <divclass="form-group">
                                    <divclass="col-sm-2 control-label">姓名</div>
                                    <divclass="col-sm-10">
                                        <inputid="xingMing"type="text"class="form-control"placeholder="姓名" />
                                    </div>
                                </div>
                                <divclass="form-group">
                                    <divclass="col-sm-2 control-label">性别</div>
                                    <divclass="col-sm-10">
                                        <selectclass="col-sm-10 form-control"id="xbSelect"style="float: left;">
                                            <optionvalue="男"></option>
                                            <optionvalue="女"></option>
                                        </select>
                                    </div>
                                </div>
                                <divclass="form-group">
                                    <divclass="col-sm-2 control-label">身份证号码</div>
                                    <divclass="col-sm-10">
                                        <inputid="shenFenZhengHaoMa"type="text"class="form-control"placeholder="身份证号码" />
                                    </div>
                                </div>

                                <divclass="form-group">
                                    <divclass="col-sm-2 control-label">电话号码</div>
                                    <divclass="col-sm-10">
                                        <inputid="dianHuaHaoMa"type="text"class="form-control"placeholder="电话号码" />
                                    </div>
                                </div>
                                <!--<div class="form-group">
<div class="col-sm-2 control-label">地区</div>
<div class="col-sm-10">
<input id="quYuMingCheng" type="text" class="form-control"
placeholder="地区" />
</div>
</div>
--> <divclass="form-group"> <divclass="col-sm-2 control-label">区域</div> <divclass="col-sm-10"> <selectclass="form-control"id="quyuSelect"> <optionth:each="quyuguanli:${quyuguanlis}"th:value="${quyuguanli.id}"th:text="${quyuguanli.quYuMingCheng}"th:attr="phone=${quyuguanli.quYuBianMa}"></option> </select> </div> </div> <!--<div class="form-group">
<div class="col-sm-2 control-label">人员状态ID</div>
<div class="col-sm-10">
<input id="renYuanZhuangTaiId" type="text"
class="form-control" placeholder="人员状态ID" />
</div>
</div>
--> <divclass="form-group"> <divclass="col-sm-2 control-label">人员状态</div> <divclass="col-sm-10"> <selectclass="form-control"id="ryztSelect"> <optionth:each="ryztadd:${renyuanzhuangtais}"th:value="${ryztadd.renYuanZhuangTaiId}"th:text="${ryztadd.renYuanZhuangTai}"></option> </select> </div> </div> </form> </div> </div> <divclass="modal-footer"> <buttontype="button"class="btn btn-default"data-dismiss="modal">取消</button> <buttontype="button"class="btn btn-primary"data-dismiss="modal"modifyid=""AddorModify=""onclick="addorModifySubmit(this);"></button> </div> </div> <!--/.modal-content--> </div> <!--/.modal--> </div> <!--delete modal--> <divclass="modal fade"id="crudmodal_delete"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"aria-hidden="true"> <divclass="modal-dialog"> <divclass="modal-content"> <divclass="modal-header"> <buttontype="button"class="close"data-dismiss="modal"aria-hidden="true">&times;</button> <h4class="modal-title">作废订单</h4> </div> <divclass="modal-body">是否确定作废该订单吗?</div> <divclass="modal-footer"> <buttontype="button"class="btn btn-default"data-dismiss="modal"></button> <buttontype="button"class="btn btn-primary"data-dismiss="modal"deleteid="0"onclick="delSubmit(this);"></button> </div> </div> <!--/.modal-content--> </div> <!--/.modal--> </div> <!--operation result modal--> <divclass="modal fade"id="crudmodal_result"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"aria-hidden="true"> <divclass="modal-dialog"> <divclass="modal-content"> <divclass="modal-header"> <buttontype="button"class="close"data-dismiss="modal"aria-hidden="true">&times;</button> <h4class="modal-title">操作结果</h4> </div> <divid="crudmodal_result_operateResult"class="modal-body"> </div> <divclass="modal-footer"> <buttontype="button"class="btn btn-default"data-dismiss="modal"onclick="refresh();">确定</button> </div> </div> <!--/.modal-content--> </div> <!--/.modal--> </div> <!--loading modal--> <divclass="modal fade"id="crudmodal_loading"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"data-backdrop='static'> <divclass="modal-dialog"role="document"> <divclass="modal-content"> <divclass="modal-header"> <h4class="modal-title">提示</h4> </div> <divclass="modal-body">请稍候。。。</div> </div> </div> </div> </div> </body> </html>

完整版

functioninitModifyModal(obj) {
jQuery.ajax({
url:
'/sjr/' + $(obj).attr('whatever'),
type:
'GET',
beforeSend:
function() {
$(
'#crudmodal_loading').modal('show'); 弹出对应的界面块
},
error:
function(request) {
$(
'#crudmodal_loading').modal('hide');
$(
'#crudmodal_result #crudmodal_result_operateResult').html('操作失败');
$(
'#crudmodal_result').modal('show');
},
success:
function(data) {if (data.code == 200) {
$(
'#crudmodal_loading').modal('hide');
$(
'#crudmodal_modify #xbSelect').val(data.data.xingBie);$('#crudmodal_modify .btn-primary').attr('AddorModify',2); //1是添加 2 修改 $('#crudmodal_modify .btn-primary').html("修改");
$(
'#crudmodal_modify #modaltitle').html("送检人员-修改");
$(
'#crudmodal_modify').modal('show');
}
else{
$(
'#crudmodal_loading').modal('hide');
$(
'#crudmodal_result #crudmodal_result_operateResult').html('操作失败:' +data.code);
$(
'#crudmodal_result').modal('show');
}
}
});
}

但是网上很多网友的做法不是这样的,

---------以下都看不懂

thymeleaf中fragment 的layout布局 - CSDN博客
http://blog.csdn.net/shanshan_blog/article/details/65630607

=========

thymeleaf中include fragment使用

(2016-07-20 20:25:06)

thymeleaf是一个前端模板,最近做的项目是通过springboot,angularjs,thymeleaf结合完成的。

其中thymeleaf很多功能在有js的支持下angularjs同样可以完成,比如ng-show ng-class就能达到更好的效果,而且由于angularjs是双向数据绑定的,在数据实时显示方面也表现得更好。
但是在离开js的时候纯页面交互方面使用thymeleaf就比较方便了
例如在页面中使用共同的模板:
thymeleaf提供了
div th:include="common/test:: test2"></</span>div>include指令来加载共同模板test.html
div th:fragment="test2">对应其id名test2

<</span>div th:include="common/test:: test2(value1,value2)"></</span>div> 
<</span>div th:fragment="test2(valueOne,valueTwo)"> 

Sql Server (MSSQLSERVER) 服务无法启动 - 晓菜鸟 - 博客园  http://www.cnblogs.com/52XF/p/4230578.html  --摘抄如下:

一、是否修改了操作系统密码?

修改操作系统密码,导致SQL不能启动的解决办法:

1.我的电脑
--控制面板--管理工具--服务--右键MSSQLSERVER--属性--登陆--登陆身份--选择"本地系统帐户"

或者:

2.我的电脑
--控制面板--管理工具--服务--右键MSSQLSERVER--属性--登陆--登陆身份--选择"此帐户"--密码和确认密码框中输入你修改后的Administrator密码。

我们服务器的系统是 Windows Server 2008 R2 Enterprise,所以对应的是:我的电脑--控制面板--系统和安全--管理工具--服务--右键MSSQLSERVER--属性--登陆--登陆身份--选择上面两种任意一种方式。

两者的区别:

选择第一种方式,以后修改了Administrator密码,不用再调整(但要求登陆操作系统的是系统管理员)。

选择第二种方式,以后修改了Administrator密码,还要再重复做上面的操作。

JS里设定延时:

使用SetInterval和设定延时函数setTimeout 很类似。setTimeout 运用在延迟一段时间,再进行某项操作。

setTimeout
("function",time) 设置一个超时对象
setInterval
("function",time) 设置一个超时对象

SetInterval为自动重复,               setTimeout不会重复。

clearTimeout
(对象) 清除已设置的setTimeout对象
clearInterval
(对象) 清除已设置的setInterval对象

举例 1、:放到js代码中,页面加载完就设定了,时间到就刷新整个页面,缺点是无法动态更改刷新间隔。

functionmyrefresh() { window.location.reload(); } 
setTimeout(
'myrefresh()',5000); //指定5秒刷新一次

方法二、 :<head><meta http-equiv="refresh" content="60"></head>

====为了实现可以更改动态修改刷新间隔【上面的方法是做不到的】

分析:因为本页面是用jsp 方式,没有用到异步刷新填充数据,目前很有局限性。

改造:方法1、不要刷新整个页面,定时触发ajax请求数据回来 动态创建表格填充数据;

方法2、用iframe的方式,弄成多页面的感觉,js 定时刷新 iframe里面的页面

方法3、还是采用目前方式,变通一下。动态参数通过请求地址参数 传递。js代码如下:

$(function() {//先定义一个静态方法getUrlParam(拓展工具)的方式
    (function($) {
$.getUrlParam
= function(name) {var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");var r = window.location.search.substr(1).match(reg);if (r != null)return unescape(r[2]);return null;
}
})(jQuery);
var xx = $.getUrlParam('pn');//获取参数 大于0才设定,如果为0视为停止刷新 if (xx > 0) {
setTimeout(
'myrefresh1(' + xx + ')', xx);//设定本次定时间隔}

});
functionqueryItems() {
document.itemsForm.action
= "${pageContext.request.contextPath }/coins/list.action";
document.itemsForm.submit();
}
functionmyrefresh1(interval) {//window.location.reload();改用下方方法 self.location = 'list?pn=' + interval;//将时间间隔作为请求参数,controller中并不使用它 }varst;functionStartReflesh() {var time = document.getElementById("selectTime").value;//js获取值 st = setInterval('myrefresh1(' + time + ')', time);//设定定时间隔,并把 间隔传参给地址}functionEndReflesh() {//clearInterval(st); self.location = 'list?pn=0';//停止刷新时参数 pn是为0}

其实不断刷新页面是很不好的,最好异步请求数据 填充。 后续改善,待更新.....

http://caniuse.com/#index     //Can I use... Support tables for HTML5, CSS3, etc-支持h5和css3的情况列表

JS包含: DOM  ECMA   BOM

==历史管理

方法一:用onhashchange:改变hash值来管理

产生7个随机数显示,产生一串数据数字昨晚 obj 对象的key,number作为值;关键赋值给hash

当前进后退是 hash改变,触发,取值显示到页面。

产生多少个随机数的方法。

方法二:

目前上面前进后退 地址栏是不会变化的,如若要变化,可以在 pushState函数第三个参数每次传一个递增的数据:var inow=1; 传 inow++;

==DOM

==JS跨域问题:jsonp

window.name, 内容是写到name上的,不会被暴露出来,《==不是很理解

【原创】说说JSON和JSONP,也许你会豁然开朗,含jQuery用例 - 随它去吧 - 博客园
http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html

JSONP是如何工作的? | Melon---没有太细看
http://blog.bpzufang.com/blog/2014/08/08/how-jsonp-really-works/

==闭包:


上面的a是局部变量,执行aaa()后a并没有被回收,通过调用b();a会不断累加。但是执行alert(a)会报错,因为a是局部的。

在JS中如果在函数的两边加上括号(),此函数就有函数声明变成了函数表达式,再在后面加上()像这样(function(){})();函数就会自执行。


模块化代码的一个模型


1、什么是闭包?2、闭包有什么好处?应用在哪里?
闭包好处:
1、希望一个变量长期驻扎在内存当中;2、模块化代码,避免全局变量的污染;3、私有函数,私有成员。3、闭包需要注意的地方?
IE下 可能会引发内存泄漏,解决方法 两个:
window.onload
= function(){var oDiv = document.getElementById('div1');
oDiv.onclick
= function(){
alert(oDiv.id);
};
window.onunload
= function(){
oDiv.onclic
= null;
};
}
===window.onload= function(){var oDiv = document.getElementById('div1');var id =oDiv.id;
oDiv.onclick
= function(){
alert(id);
};
oDiv
= null;
}

学习Javascript闭包(Closure) - 阮一峰的网络日志
http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html

===操作Iframe

防止被嵌套,被钓鱼

var oIframe = document.getElementById('iframe1');
oIframe.
contentWindow
.document.getElementById('div1').style.color='red'; 所有浏览器都可以

IE浏览器没有问题,在crome下直接打开不可以(在服务器下可以,为了安全)
oIframe.
contentDocument
.getElementById(); ie6 ie7是不支持的

==对象操作-浅拷贝 深拷贝

==快速排序

==枚举算法


obj.inertBefore(oLi,aLi[0]);

obj.appenChild(oLi)

obj.inertBefore(aLi[i],aLi[0]);//这样起到交互的效果?

==函数声明和函数表达式

函数声明和函数表达式

区别:

1、函数表达式可以直接在后面添加括号执行,而函数声明不可以。

2、函数声明可以提前被解析出来  (预编译)

以为预编译,所以与IF没有什么关系了,并不是想象的编译第一个。

==事件委托

本来是自己做的事情 ,却给了别人替你做这件事情

:利用冒泡的原理,把事件加到父级上,触发执行效果

window.onload = function(){var oUl =document.getElementById(‘ull‘);var aLi =document.getElementsByTagName(‘li‘);

oUl.onmouseover
= function(ev){var event = ev||window.event; //获取event对象 var target = ev.target || ev.srcElement; //获取触发事件的目标对象 if(target.nodeName.toLowerCase() == ‘li‘){ //判断目标对象是不是li target.style.background =‘red‘;
}

}
代码中加了一个标签名的判断,主要原因是如果不加判断,当你鼠标移入到父级oUL上面的时候,整个列表就会变红,这不是我们想要的结果,所以要判断一下。
target.nodeName 弹出的名字是大写的,所以需要转换大小写再比较。