thymeleaf 怎么在没数据库时间默认值时显示默认值

1715人阅读
springboot(4)
Spring Boot学习记录(二)–thymeleaf模板
标签(空格分隔): spring-boot
自从来公司后都没用过jsp当界面渲染了,因为前后端分离不是很好,反而模板引擎用的比较多,thymeleaf最大的优势后缀为html,就是只需要浏览器就可以展现页面了,还有就是thymeleaf可以很好的和spring集成.下面开始学习.
1.引入依赖
maven中直接引入
&org.springframework.boot&
&spring-boot-starter-thymeleaf&
可以查看依赖关系,发现spring-boot-starter-thymeleaf下面已经包括了spring-boot-starter-web,所以可以把spring-boot-starter-web的依赖去掉.
2.配置视图解析器
spring-boot很多配置都有默认配置,比如默认页面映射路径为
classpath:/templates/*.html
同样静态文件路径为
classpath:/static/
在application.properties中可以配置thymeleaf模板解析器属性.就像使用springMVC的JSP解析器配置一样
#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#thymeleaf end
具体可以配置的参数可以查看
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties这个类,上面的配置实际上就是注入到该类中的属性值.
3.编写DEMO
@Controller
public class HelloController {
private Logger logger = LoggerFactory.getLogger(HelloController.class);
* 测试hello
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String hello(Model model) {
model.addAttribute("name", "Dear");
return "hello";
2.view(注释为IDEA生成的索引,便于IDEA补全)
&!DOCTYPE HTML&
xmlns:th="http://www.thymeleaf.org"&
http-equiv="Content-Type" content="text/ charset=UTF-8" /&
th:text="'Hello!, ' + ${name} + '!'" &3333&
4.基础语法
回味上面的DEMO,可以看出来首先要在改写html标签
&html xmlns:th="http://www.thymeleaf.org"&
这样的话才可以在其他标签里面使用th:*这样的语法.这是下面语法的前提.
1.获取变量值
&p th:text="'Hello!, ' + ${name} + '!'" &3333&/p&
可以看出获取变量值用&符号,对于javaBean的话使用变量名.属性名方式获取,这点和EL表达式一样.
另外$表达式只能写在th标签内部,不然不会生效,上面例子就是使用th:text标签的值替换p标签里面的值,至于p里面的原有的值只是为了给前端开发时做展示用的.这样的话很好的做到了前后端分离.
Thymeleaf对于URL的处理是通过语法@{…}来处理的
th:href="@{http://blog.csdn.net/u}"&绝对路径&
th:href="@{/}"&相对路径&
th:href="@{css/bootstrap.min.css}"&Content路径,默认访问static下的css文件夹&
类似的标签有:th:href和th:src
3.字符串替换
很多时候可能我们只需要对一大段文字中的某一处地方进行替换,可以通过字符串拼接操作完成:
&span th:text="'Welcome to our application, ' + ${user.name} + '!'"&
一种更简洁的方式是:
&span th:text="|Welcome to our application, ${user.name}!|"&
当然这种形式限制比较多,|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等。
在表达式中可以使用各类算术运算符,例如+, -, *, /, %
th:with="isEven=(${prodStat.count} % 2 == 0)"
逻辑运算符&, &, &=,&=,==,!=都可以使用,唯一需要注意的是使用&,&时需要用它的HTML转义符:
th:if="${prodStat.count} & 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
Thymeleaf中使用th:if和th:unless属性进行条件判断,下面的例子中,标签只有在th:if中条件成立时才显示:
&a th:href="@{/login}" th:unless=${session.user != null}&Login&/a&
th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。
Thymeleaf同样支持多路选择Switch结构:
&div th:switch="${user.role}"&
&p th:case="'admin'"&User is an administrator&/p&
&p th:case="#{roles.manager}"&User is a manager&/p&
默认属性default可以用*表示:
th:switch="${user.role}"&
th:case="'admin'"&User is an administrator&
th:case="#{roles.manager}"&User is a manager&
th:case="*"&User is some other thing&
渲染列表数据是一种非常常见的场景,例如现在有n条记录需要渲染成一个表格,该数据集合必须是可以遍历的,使用th:each标签:
&Product list&
&IN STOCK&
th:each="prod : ${prods}"&
th:text="${prod.name}"&Onions&
th:text="${prod.price}"&2.41&
th:text="${prod.inStock}? #{true} : #{false}"&yes&
href="../home.html" th:href="@{/}"&Return to home&
可以看到,需要在被循环渲染的元素(这里是)中加入th:each标签,其中th:each=”prod : ${prods}”意味着对集合变量prods进行遍历,循环变量是prod在循环体中可以通过表达式访问。
7.Utilities
为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#直接访问:
#calendars
下面用一段代码来举例一些常用的方法:
* Format date with the specified pattern
* Also works with arrays, lists or sets
* Create a date (java.util.Date) object for the current date and time
* Create a date (java.util.Date) object for the current date (time set to 00:00)
* 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)}
${#strings.randomAlphanumeric(count)}
快速的学习还是直接写例子最快,后期写Demo遇到问题再加上去
整合项目地址:
在spring-boot1.4之后,支持thymeleaf3,可以更改版本号来进行修改支持.
3相比2极大的提高了效率,并且不需要标签闭合,类似的link,img等都有了很好的支持,按照如下配置即可
&3.0.0.RELEASE&
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:179234次
积分:2086
积分:2086
排名:第14400名
原创:52篇
评论:50条
好好学习,天天向上
文章:44篇
阅读:110552
阅读:10310
阅读:12508
(2)(4)(6)(1)(6)(8)(4)(6)(23)Thymeleaf模板的使用
Thymeleaf模板的使用
[摘要:th:href = “@{/css/main.css}” 链接 th:src=”@{/js/main.js}” th:if判别 Thymeleaf 模板的应用 应用模板的要面: 页里主体布局流动,详细参数可变,尽量让参数静态化,才干进步模板的复用性]
th:href = “@{/css/main.css}”&&&&&&& 链接
th:src=”@{/js/main.js}”&&&&&&&&&&&
th:if&&判断
Thymeleaf模板的使用
使用模板的要点:
&&&页面主体结构固定,具体参数可变,尽可能让参数动态化,才能提高模板的复用性
===================================================================
Thymeleaf'score& is a DOM processing engine
Processor:An Object which applies some logic to a DOM node
StandardDialect: a set of processor,provided by Thymeleaf core library
TemplateEngine :& can be configured several dialects at a time,called&process chain
================================================================
TemplateResolver
TemplateResolvers are objects& that& implement an& interface&from& the Thymeleaf API called org.thymeleaf.templateresolver.ITemplateResolver
publicTemplateResolution resolveTemplate(finalTemplateProcessingParameters&&& templateProcessingParameters);
Allimplementaion class :
&&&-ClassLoaderTemplateResolver
&&&-FileTemplateResolver
&&&-ServletContextTemplateResolver
&&&-UrlTemplateResolver
InitialTemplate Engine use ServletContextTemplateResolver
&&&private static void initializeTemplateEngine() {
&&&&&&&ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
&&&&&&&// XHTML is the default mode, but we will set it anyway for betterunderstanding of code
&&&&&&&templateResolver.setTemplateMode(&XHTML&);
&&&// This will convert &home& to &/WEB-INF/templates/home.html&
&&&// 设置模板的前置路径
&&&&&&&templateResolver.setPrefix(&/WEB-INF/templates/&);
&&&//设置模板统一的后缀名
&&&&&&&templateResolver.setSuffix(&.html&);
&&&&&&&// Set template cache TTL to 1 hour. If not set, entries would live in cacheuntil expelled by LRU
&&&&&&&templateResolver.setCacheTTLMs(Long.valueOf(3600000L));
&&&&&&&// Cache is set to true by default. Set to false if you want templates to
&&&&&&&// be automatically updated when modified.
&&&&&&&templateResolver.setCacheable(true);
&&&&&&&templateEngine = new TemplateEngine();
&&&&&&&templateEngine.setTemplateResolver(templateResolver);
1.newone TemplateResolver instance
2.configthe resolver
3.newTemplate engine
4.setresolver to this engine
5.invokeengine's process method to work
============================================================================
&!DOCTYPEhtml SYSTEM&http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-3.dtd&&
&htmlxmlns=&http://www.w3.org/1999/xhtml& xmlns:th=&http://www.thymeleaf.org&&
或者使用下面的文档声明也可以,这样就没有Thymeleaf对文档的校验功能了,因为没有引入对应的DTD,而且IDE可能会提示错误,但是不影响对模板的解析。
&!DOCTYPEhtml PUBLIC &-//W3C//DTD XHTML 1.0 Strict//EN&&http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&&
============================================================================
specify&that a& text should correspond& to a specific message
引用外部文件(message)中的内容,进行替换
首先,需要指定外部文件的位置,如果没有指定,则使用默认的StandardMessage Resolver
会到/WEB-INF/templates/下寻找properties文件
home_en.properties文件是如何被定为到的呢?
通过WebContext ctx = newWebContext(request, response, servletContext, request.getLocale());
其中,request.getLocale()就说明了当前系统的所在地,就能确定读取en/zh_CN了。
当然,可以配置外部文件的位置!
th:text=&#{home.welcome}&
Theth:text attribute, which evaluates its value expression and sets the result ofthis evaluation as the body of& the& tag& it is& in
th:text计算表达式的结果,并使用这个结果来替换当前标签中的内容
============================================================================
publicvoid process(
&&&final HttpServletRequest request, final HttpServletResponse response,
&&&final ServletContext servletContext, final TemplateEngine templateEngine)&
&&&throws Exception {
&&&WebContext ctx = new WebContext(request, response, servletContext,request.getLocale());
&&&ctx.setVariable(&today&, Calendar.getInstance());
&&&templateEngine.process(&home&, ctx, response.getWriter());
Thymeleaf中提供了2个实现IContext的实现类
&&&org.thymeleaf.context.Context&& implements& IContext
&&&org.thymeleaf.context.WebContext&& implements& IWebContext
WebContext提供了更多的方法可用
=============================================================================
UnescapedText
照原样对文本进行输出,不对& & 进行转义
th:utext=&&b&BigCharacter&/b&& 将输出为:&b&BigCharacter&/b&
=============================================================================
Using and displaying variables
1.设置变量
&&&SimpleDateFormat dateFormat = new SimpleDateFormat(&dd MMMM yyyy&);
&&&Calendar cal = Calendar.getInstance();
&&&WebContext ctx = new WebContext(request, servletContext, request.getLocale());
&&&ctx.setVariable(&today&, dateFormat.format(cal.getTime()));
&&&templateEngine.process(&home&, ctx, response.getWriter());
2.在模板中使用变量
&&&th:text=&${today}&
3.使用Thymeleaf提供的内置变量,不用提前设置,直接在模板中使用
&&&th:text=&${#calendars.format(today,'dd MMMM yyyy')}&
==============================================================================
&Thymeleaf Standard Dialect:& the Thymeleaf StandardExpression syntax
&Thymeleaf支持的运算符和表达式的应用
&所有的操作符都可以嵌套使用,非常强大!
&1.Text literals: '...'
&2.Number literals: 0,1.0,12.3,etc
&Simpleexpression: 表达式语法
&&&&1.Message expression :&#{}
&&&&2.Variable expression :&${}
&&&&3.Link URL expression:&@{}
&&&&4.Selection Variable expression:&*{}
&&&&&&&结合th:object使用,在某个范围内进行变量的查找,而不是在context中查找,缩小了查询的范围,效率如何呢?
&&& &&& 如何没有与th:object结合使用,*{}与${}效果一样,因为其范围自动扩展到context。
&Binary operations:& 运算符
&&&&1.String concatenation: +
&&&&2.Arithetic operatiors : +, -, *, /, %
&&&&parators: &, &, &=, &=
&&&&4.Boolean operators: and, or
&&&&5.Equality operators: ==, !=
&Unary operations:
&&&&1.Minus sign(): -& 负号
&&&&2.Boolean negation: !, not 否定符
&Conditional operators: 条件表达式
&&&&1.If-then-else: (if)?(then):else 三元运算符
&&&&2.If-then: (if) ? (then) ,省略了else部分,如果条件不成立,返回null
&&&&3.Default: (value)?:(defaultValue) , use second value only first is null&
All&this operations can be combined and nested:&
&&&'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?:'Unknown')
=================================================================================
Message& 在模板中获取消息
&&&动态指定message的内容/甚至可以动态指定访问哪个message
&&&th:utext=&#{home.welcome(${session.user.name})}&,其中${session.user.name}作为参数,替换home.welcome的映射文本中的{0}
&&&th:utext=&#{${welcomeMsgKey}(${session.user.name})}&,其中${welcomeMsgKey}动态指定message文件中的key
==================================================================================
Variables& 在模板中获取数据
&&&&${...}& expressions are& in& fact OGNL& (Object-GraphNavigation Language) expressions executed
on&the map of variables contained& in& the context.
&&&&模板中获取变量值的方式,使用${},针对不同类型数据,用法如下:
&&&* Access to properties using the point (.). Equivalent to calling propertygetters.
&&&* 通过.进行导航,相当于调用getters()
&&&&${person.father.name}
&&&* Access to properties can also be made by using brackets ([]) and writing
&&&* the name of the property as a variable or between single quotes.
&&&* 使用[]等效于使用. ,但是[]在某些场合能完成.不能完成的任务
&&&&${person['father']['name']}
&&&* If the object is a map, both dot and bracket syntax will be equivalent to
&&&* executing a call on its get(...) method.
&&&* 访问Map集合
&&&${countriesByCode.ES}
&&&&${personsByName['Stephen Zucchini'].age}
&&&* Indexed access to arrays or collections is also performed with brackets,
&&&* writing the index without quotes.
&&&* 访问数组
&&&${personsArray[0].name}
&&&* Methods can be called, even with arguments.
&&&* 调用对象的方法
&&&${person.createCompleteName()}
&&&&${person.createCompleteNameWithSeparator('-')}
=======================================================================================
Expression utility objects& 在模板中使用内置对象
内置对象,提供了很多方便的功能,日期格式化,字符串处理,数字格式化等
&&&#dates, formatting,component extraction,etc
&&&&#calendars
&&&&#numbers, formatting numeric objects.
&&&#strigns, contains,startsWith,prepending/appending,etc
&&&#arrays
&&&&#lists
&&&#aggregates, creating aggregates on arrays or collections
&&&#messages, equal to using #{}
&&&#ids, deal with id attributes, eg: as a result of an iteration
&&& #ctx等等,还有很多!
======================================================================================
Link URLs& 在模板中使用URL链接
Severaltypes of URLs:
&&&1.Absolute URL,like http://localhost:8080/thymeleaf
&&&2.Relative URL,which can be:
&&&&&& Page-relative,like: user/login.html 页面相对定位
&&&&&& Context-relative,like:&/itemdetails?id=1&(context name in server will be addedautomatically)&项目根路径定位,模板解析时会自动加上应用程序的名称作为前缀
&&&&&& Server-relative,like: ~/billing/processInvoice (allowcalling URLs in another context in the same server) 相同服务器根目录下的定位
&&&&如何要使用相对定位,必须指定一个实现了IWebcontext接口的对象,因为需要从其中获取httprequest对象,从而得到应用程序的根路径,才能处理相对路径
&&&相对路径,并且在URL上使用OGNL表达式取参数,而且themeleaf会自动对URL进行编码:
&&&&&& &a href=&details.html& th:href=&@{/order/details(orderId=${o.id})}&&view&/a&
&&&&&& &ath:href=&@{'/details/'+${user.login}(orderId=${o.id})}&&view&/a&
=======================================================================================
Literals&&& 模板中使用简单文本
&&&字符串/数字
&&&&&& a.原样输出
&&&&&& &&& &p&The year is &spanth:text=&&/span&.&/p&
&&&&&& b.字符串拼接
&&&&&& &&& th:text=&'The name of the user is '+ ${user.name}&
========================================================================================
Arithmetic operations 模板中对变量进行算数运算&
+- * / %
有两种计算方式,都可以。
&&&1.使用Thymeleaf进行运算---&先OGNL表达式取到变量值,然后thymeleaf再进行运算
&&&&&& th:with=&isEven=(${prodStat.count} % 2 == 0)&
&&&2.使用OGNL进行运算---&直接在OGNL表达式中进行运算
&&&&&& th:with=&isEven=${prodStat.count % 2 == 0}&
========================================================================================
Comparators and Equality 模板中使用比较符和等号
&&&模板中不能直接使用 & & &= &=
&&&需要进行转义:
&&&th:text=&'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' :'Production')&
=======================================================================================
Conditional expressions 三元运算,第一个表达式的结果为boolean类型
&&&if ? then : else ---& A ? B : C
&&&&tr th:class=&${row.even}? 'even' : 'odd'&& 设置tr的class属性,用来控制行的显示效果很方便
&&&嵌套使用条件表达式:
&&&&tr th:class=&${row.even}? (${row.first}? 'first' : 'even') :'odd'&& 灵活控制首行,偶数行,奇数行的class属性值,便于进行css样式定义
&&&还可以省略else部分,当表达式结果为false,返回null,否则返回'alt'
&&&&tr th:class=&${row.even}? 'alt'&&
&&&&&& ...
======================================================================================
Default Expression 具有默认值的表达式,第一个表达式的结果只要不为null,就取第一个表达式的结果
&&&being& the second one evaluated only& in& the case of& thefirst one& returning null .
&&&A ?: B& ---& A不为null,则取A,否则取B
&&&如果第一个表达式的计算结果为null,则取第二个表达式的结果
&&&&div th:object=&${session.user}&&
&&&&&& ...
&&&&&& &p&Age: &span th:text=&*{age}?: '(no agespecified)'&&27&/span&.&/p&
&&&等效于:
&&&&p&Age: &span th:text=&*{age != null}? *{age} : '(no agespecified)'&&27&/span&.&/p&
&&&条件表达式嵌套:
&&&&p&Name: &span th:text=&*{firstName} ?: (*{admin} ? 'Admin' :#{default.username})&&Sebastian&/span&.&/p&
=========================================================================================
静态方法的调用
&&&&pth:text=&${@myapp.translator.Translator@translateToFrench('textVar')}&&Sometext here...&/p&
==========================================================================================
******************************************************************************************
Setting the value of any attribute
在模板中对目标设置任何属性,action, class, value, etc
非常强大,不仅处理HTML模板方便,处理FO-XSL(PDF模板)一样通用。
&&&设置action属性
&&&&form action=&subscribe.html&th:attr=&action=@{/subscribe}&&
&&&设置value属性
&&&&input type=&submit& value=&Subscribe me!&th:attr=&value=#{subscribe.submit}&/&
&&&一次设置多个属性
&&&&img src=&../../images/gtvglogo.png&th:attr=&src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}&/&
&&&模板处理后的结果---&& &imgsrc=&/gtgv/images/gtvglogo.png& title=&Logo de Good Thymes&alt=&Logo de Good Thymes& /&
&&&设置属性更优雅的方式(仅在HTML模板中有效,处理PDF模板,只能用th:attr=&&来实现,因为PDF模板中的属性在Thymeleaf中好像没有定义)
&&&&&& &input type=&submit& value=&Subscribeme!& th:value=&#{subscribe.submit}&/&
&&&&&& &form action=&subscribe.html&th:action=&@{/subscribe}&&
&&&&&& &li&&a href=&product/list.html&th:href=&@{/product/list}&&Product List&/a&&/li&
&&&&&& Themeleaf支持HTML中几乎所有的属性定义,使用时具体参考Thymeleaf的手册
&&&&&& th:bgcolor,th:border,th:cellpadding,th:cellspacing,th:colspan,th:align,th:src,th:width,th:size 等等
控制样式:
&&&第一种方式直接在tr上定义css样式,如bgcolor,border等
&&&第二种方式,在tr上定义class属性,通过外部css样式进行控制。(复杂样式,采用第二种方案)
============================================================================================
Appending and prepending 在已有属性上追加属性
&&&th:attrappend& 追加
&&&th:attrprepend 放到前面
&&&&input type=&button& value=&Do it!&class=&btn& th:attrappend=&class=${' ' + cssStyle}& /&
&&&---& &input type=&button& value=&Do it!&class=&btn warning& /&
&&&遍历prods集合,每次生成一行
&&&&tr th:each=&prod : ${prods}& class=&row&th:classappend=&${prodStat.odd}? 'odd'&&
&&&&&& &td&${prod.name}&/td&
=============================================================================================
Fixed-value boolean attributes&
设置某些具有固定值的属性
XHTML/HTML5中,有一些特殊的属性,要么没有值,要么为某个固定的值
&&&checked
&&&selected
&&&disabled
&&&mutiple
&&&readonly
如果计算结果为true,则使用它的固定值,否则不处理。
&inputtype=&checkbox& name=&active&th:checked=&${user.active}& /&
&&&th:autofocus
&&&th:default
&&&th:hidden
===============================================================================================
***********************************************************************************************
Iteration 循环遍历
th:each=&obj: ${objList}&& 循环所在标签的片段,每次片段中用到的都是当前遍历到的对象
&&&后台准备数据
&&&public void process(
&&&&&& HttpServletRequest request, HttpServletResponse response,
&&&&&& ServletContext servletContext, TemplateEnginetemplateEngine) {
&&&&&& ProductService productService = new ProductService();
&&&&&& List&Product& allProducts = productService.findAll();
&&&&&& WebContext ctx = new WebContext(request, servletContext,request.getLocale());
&&&&&& ctx.setVariable(&prods&, allProducts);
&&&&&& templateEngine.process(&product/list&, ctx,response.getWriter());
&&&模板中进行遍历,每次遍历生成一个tr,td列取到的对象为当前遍历到的对象
&&&&tr th:each=&prod : ${prods}&&
&&&&&& &td th:text=&${prod.name}&&Onions&/td&
&&&&&& &td th:text=&${prod.price}&&2.41&/td&
&&&&&& &td th:text=&${prod.inStock}? #{true} :#{false}&&yes&/td&
Keeping&&& iteration status 跟踪迭代过程中的状态变化
&&&遍历过程中,提供了如下属性:
&&&&&& index&&& starting with 0
&&&&&& count&&& starting with 1
&&&&&& size&&& total amount of elements in theiterated variables
&&&&&& current&&& current object
&&&&&& even/odd&&& boolean value,第偶数个/奇数个
&&&&&& first/last&&& boolean value.第1个/最后1个
&&&在th:each中,在iter variable变量后面,定义一个status variable,通过该变量来获取遍历过程中的状态
&&&&tr th:each=&prod,iterStat : ${prods}&th:class=&${iterStat.odd}? 'odd'&&
prefix&&&前缀
suffix&&&后缀
&&&If you don't explicitly set an& iteration variable, Thymeleaf will&always create one& for you by suffixing 'Stat' to& the name of&the iter variable。
&&&如果没有定义statusvariable,thymeleaf会自动为我们提供一个来使用,通过在itervariable后面添加后缀Stat来使用。
&&&&&trth:each=&prod : ${prods}& th:class=&${prodStat.odd}?'odd'&&
================================================================================================
************************************************************************************************
Conditional evaluation 条件语句
Simpleconditionals: &if& and &unless&
&&&在某种条件成立时,对某个fragment进行处理:
&&&当th:if条件成立时,该标签中其它th:*标签才会发挥作用,如果条件不成立,则th:*不会执行
&&&&a href=&comments.html&
&&&th:href=&@{/product/comments(prodId=${prod.id})}&
&&&&th:if=&${not #lists.ments)}&&view&/a&
&&&&th:if判断表达式结果是否为真的规则:
&&&If value is not null:
&&&&&&&value is a
&&& &&& value is a number and isnon-
&&& &&& value is a character and isnon-
&&& &&& value is a String and is not&false&, &off& or &no&;
&&& &&& value is not a boolean, anumber, a character or a S
&&&If value is null, th:if wi
&&&另外,还可以用th:unless,进行条件控制。如果条件为真,则不执行。
&&&&a href=&comments.html&
&&&th:href=&@{/comments(prodId=${prod.id})}&
&&&th:unless=&${#lists.ments)}&&view&/a&
====================================================================================
Switch statement&&& Switch选择语句
Note&that as soon as one& th:case& attribute& is evaluated as&true , every other& th:case& attribute& in& the same switchcontext is evaluated as& false .
Thedefaul t option& is speci fied as& th:case=&*& :
&&&&div th:switch=&${user.role}&&
&&&&&& &p th:case=&'admin'&&User is anadministrator&/p&
&&&&&& &p th:case=&#{roles.manager}&&User is amanager&/p&
&&&&&& &p th:case=&*&&User is some otherthing&/p&
======================================================================================
Template Layout& 模板布局/模板重用
Includingtemplate fragments
&&&th:fragment&&
&&&th:include&&&&
&&&&&& 在某个标签中使用th:fragment属性定义一个变量名,然后在其他模板中通过th:include,即可引入。
&&&a.html&
&&&&&& &div th:fragment=&hello&&&& 定义一个fragment,并取名为&hello&
&&&&&& &&& include me.!
&&&&&& &/div&
&&&&&& &div th:include=&a ::hello&&what?&/div& 从名称为a.html的模板中引入名称为&hello&的fragment
&&&***还可以不使用th:fragment属性进行引入,通过DOMSelector
&&&&templatename::[domselector]&&&& like XPathexpressions.
&&&***将模板整个引入
&&&&templatename&&
&&&th:include中同样可以嵌套使用表达式
&&&&div th:include=&footer :: (${user.isAdmin}? #{footer.admin} :#{footer.normaluser})&&&/div&
&&&th:include&
&&&&&& 引入fragment中定义的内容
&&&th:substituteby&
&&&&&& 引入fragment所在标签和内容,并替换当前的标签
&&&footer.html
&&&&footer th:fragment=&copy&&
&&&&&& & 2011 The Good Thymes Virtual Grocery
&&&&/footer&
&&&main.html
&&&--------------------------------------------& th:include只引入内容
&&&&div th:include=&footer :: copy&&&/div&
&&&result:
&&&&&& & 2011 The Good Thymes Virtual Grocery
&&&--------------------------------------------& 整个引入,并替换掉host tag
&&&&div th:substituteby=&footer :: copy&&&/div&
&&&result:
&&&&footer&
&&&&&& & 2011 The Good Thymes Virtual Grocery
&&&&/footer&
============================================================================
Removing template fragments
&&&th:remove 为了静态显示时提供充分的数据,但是在模板被解析后,又不需要这些模拟的数据,需要将其删除
&&&可选属性:
&&&&&& th:remove=&all&, 删除所有
&&&&&& th:remove=&all-but-first&,删除所有,但保留第一个
&&&&&& th:remove=&body&, 删除内容,但保留标签
&&&&&& th:remove=&tag&, 删除标签,但保留内容
=============================================================================
Local variables& 模板中自定义变量
&&&&th:with=&fisrtPerson=${persons[0]}&
&&&使用自定义的变量:
&&&&span th:text=&${firstPer.name}&&
&&&&div&th:with=&firstPer=${persons[0]},secondPer=${persons[1]}&&
&&&&&& &p&The name of the first person is &spanth:text=&${firstPer.name}&&Julius Caesar&/span&.&/p&
&&&&&& &p&But the name of the second person is &spanth:text=&${secondPer.name}&&MarcusAntonius&/span&.&/p&
&&&原理:定义的变量将被添加到context的map中,这样就能像其它变量一样被使用到了。
&&&自定义变量的有效范围:仅在被定义的标签内有效,比如,上面的firstPerson,仅在当前div中有效
&&&另一个用途:
&&&定义变量存放message中的配置
&&&然后在表达式中用
&&&如,从message中获取date.format的配置,然后复制给变量df,然后在其它地方(自定义变量所在标签内)进行使用
&&&&p th:with=&df=#{date.format}&&
&&&&&& Today is: &spanth:text=&${#calendars.format(today,df)}&&13 february2011&/span&
&&&也可以直接:
&&&&&& Today is: &span th:with=&df=#{date.format}&th:text=&${#calendars.format(today,df)}&&13 february2011&/span&
&&&优先级的问题:
&&&th:with 优先级高于 th:text&
&&&th:each 优先级高于 th:*
==============================================================================================
Attribute precedence 属性的优先级问题
Thymeleafattributes have a numeric precedence:
&&&1& fragment inclusion&&& &&&&&& th:include
&&&2& fragment iteration&&& &&&&&& th:each
&&&3& condition evaluation&&& &&&&&& th:if/th:unless/th:switch/th:case
&&&4& Local variable definition&&& &&&th:object, th:with
&&&5& General attribute modification&&& th:attr,th:attrprepend, th:attrappend
&&&6& Specific attribute modification&&& th:value, th:href,th:src, etc
&&&7& Text&&& &&& &&&&&& &&& th:text, th:utext
&&&8& Fragment specification&&& &&& th:fragment
&&&9& Fragment removal&&& &&&&&& th:remove&&&&
&&&&ul th:each=&item : ${items}&&
&&&&&& &li th:text=&${item.description}&&Itemdescription here...&/li&
&&&由于th:each的优先级高于其它th:*,所以可以简写为:
&&&&&& &li th:each=&item : ${items}&th:text=&${item.description}&&Item description here...&/li&
&&&还可以这样写,将循环放到后面,只是阅读性不好,但不影响结果:
&&&&&& &li th:text=&${item.description}&th:each=&item : ${items}&&Item description here...&/li&
=======================================================================================
Text inlining
&&&好处:简化书写
&&&弊端:以prototype呈现(静态地打开网页),将原样显示
&&&用法,在标签上定义th:inline=&text&
&&&该标签中任意地方都可以使用内联样式获取数据
&&&&p&Hello, &spanth:text=&${session.user.name}&&Sebastian&/span&!&/p&
&&&简化为:
&&&&p&Hello, [[${session.user.name}]]!&/p&
&&&parent tag中定义
&&&&&bodyth:inline=&text&&
&&&&&& ...
&&&&&& &p&hello:[[${session.user.name}]]&/p&
&&&&&& ...
JavaScript inlining
&&&&script th:inline=&javascript&&
&&&&&& /*&![CDATA[*/
&&&&&& ...
&&&&&& var username = [[${session.user}]];
&&&&&& ...
&&&&&& /*]]&*/
&&&&/script&
&&&thymeleaf将自动对user对象进行转换,而且转换为javascript中的user对象
&&&&script th:inline=&javascript&&
&&&&&& /*&![CDATA[*/
&&&&&& ...
&&&&&& var user ={'age':null,'firstName':'John','lastName':'Apricot','name':'JohnApricot','nationality':'Antarctica'};
&&&&&& ...
&&&&&& /*]]&*/
&&&&/script&
=================================================================================
Validation and Doctypes
Validatingtemplates&
&&&使用Thymeleaf的DTD进行校验和声明Thymeleaf的命名空间
&&&&!DOCTYPE html SYSTEM &http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-3.dtd&&
&&&&html xmlns=&http://www.w3.org/1999/xhtml&xmlns:th=&http://www.thymeleaf.org&&
Doctypetranslation& Thymeleaf对模板处理完成后,会自动将DOCTYPE转换为正确的类型,这样浏览器端就能正常解析了!
&&&&!DOCTYPE html SYSTEM &http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-3.dtd&&
&&&After Thymeleaf process the template, will automatically transformate theDOCTYPE to:
&&&&!DOCTYPE html PUBLIC &-//W3C//DTD XHTML 1.0 Strict//EN&&http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&&
===================================================================================
Template Resolver
org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
&&&returnThread.currentThread().getContextClassLoader().getResourceAsStream(templateName);
org.thymeleaf.templateresolver.FileTemplateResolver
&&&return new FileInputStream(new File(templateName));
org.thymeleaf.templateresolver.UrlTemplateResolver&
&&&return (new URL(templateName)).openStream();
Prefixand suffix:
&&&templateResolver.setPrefix(&/WEB-INF/templates/&);
&&&templateResolver.setSuffix(&.html&);
Encoding&to be appl ied when& reading& templates:
&&&templateResolver.setEncoding(&UTF-8&);
Default& template mode, and patterns& for defining other modes& forspeci fic& templates:
&&&// Default is TemplateMode.XHTML
&&&templateResolver.setTemplateMode(&HTML5&);
&&&templateResolver.getXhtmlTemplateModePatternSpec().addPattern(&*.xhtml&);
Default mode& for& template cache, and patterns& for defining whetherspeci fic& templates are cacheable or not:
&&&// Default is true
&&&templateResolver.setCacheable(false);
&&&templateResolver.getCacheablePatternSpec().addPattern(&/users/*&);
TTL&in mi l l iseconds& for parsed& template cache entriesoriginated& in& this& template& resolver.& If notset,& the only way& to
removean entry& from& the cache wi l l& be LRU& (cache max sizeexceeded and& the entry& is& the oldest).
&&&// Default is no TTL (only LRU would remove entries)
&&&&templateResolver.setCacheTTLMs(60000L);
Also,a Template Engine can be set several&& template&resolvers,& in which case an order can be establ ished between&them& for
template&resolution so& that,& if& the& first one& is notable& to& resolve& the& template,& the secondone& is asked, and so on:
Whenseveral&& template& resolvers are applied,& it&is& recommended& to specify patterns& for each&template& resolver so& that
Thymeleafcan quickly discard& those& template& resolvers& that arenot meant& to& resolve& the& template, enhancingperformance.
Doing&this& is not a& requi rement, but an optimization:
&&&&ClassLoaderTemplateResolverclassLoaderTemplateResolver = new ClassLoaderTemplateResolver();
&&&classLoaderTemplateResolver.setOrder(Integer.valueOf(1));
&&&// This classloader will not be even asked for any templates not matching thesepatterns
&&&classLoaderTemplateResolver.getResolvablePatternSpec().addPattern(&/layout/*.html&);
&&&classLoaderTemplateResolver.getResolvablePatternSpec().addPattern(&/menu/*.html&);
&&&ServletContextTemplateResolver servletContextTemplateResolver = newServletContextTemplateResolver();
&&&&servletContextTemplateResolver.setOrder(Integer.valueOf(2));
===================================================================================
MessageResolver&
&&&The implementation being used was anorg.thymeleaf.messageresolver.StandardMessageResolver object as default in webapplication.
&&&you can create your own by& just& implementing& the&org.thymeleaf.messageresolver.IMessageResolver interface.
&&&And why would you want& to have more& than one message&resolver?& for& the same& reason as& template&resolvers:&
&&&message resolvers are ordered and& if& the& first onecannot& resolve a specific message, the second one will be asked, then thethird, etc.
&&&// For setting only one
&&&&templateEngine.setMessageResolver(messageResolver);
===================================================================================
TemplateCache 模板缓存管理
&&&// Default is 50
&&&&StandardCacheManager cacheManager = new StandardCacheManager();
&&&cacheManager.setTemplateCacheMaxSize(100);
&&&&templateEngine.setCacheManager(cacheManager);
&&&// Clear the cache completely
&&&&templateEngine.clearTemplateCache();
&&&// Clear a specific template from the cache
&&&&templateEngine.clearTemplateCacheFor(&/users/userList&);
感谢关注 Ithao123JS频道,是专门为互联网人打造的学习交流平台,全面满足互联网人工作与学习需求,更多互联网资讯尽在 IThao123!
Hadoop是一个由Apache基金会所开发的分布式系统基础架构。
用户可以在不了解分布式底层细节的情况下,开发分布式程序。充分利用集群的威力进行高速运算和存储。
Hadoop实现了一个分布式文件系统(Hadoop Distributed File System),简称HDFS。HDFS有高容错性的特点,并且设计用来部署在低廉的(low-cost)硬件上;而且它提供高吞吐量(high throughput)来访问应用程序的数据,适合那些有着超大数据集(large data set)的应用程序。HDFS放宽了(relax)POSIX的要求,可以以流的形式访问(streaming access)文件系统中的数据。
Hadoop的框架最核心的设计就是:HDFS和MapReduce。HDFS为海量的数据提供了存储,则MapReduce为海量的数据提供了计算。
随着国内互联网的发展,产品经理岗位需求大幅增加,在国内,从事产品工作的大部分岗位为产品经理,其实现实中,很多从事产品工作的岗位是不能称为产品经理,主要原因是对产品经理的职责不明确,那产品经理的职责有哪些,本专题将详细介绍产品经理的主要职责
Swift是Apple在WWDC2014所发布的一门编程语言,用来撰写OS X和iOS应用程序[1]。在设计Swift时.就有意和Objective-C共存,Objective-C是Apple操作系统在导入Swift前使用的编程语言
Swift是供iOS和OS X应用编程的新编程语言,基于C和Objective-C,而却没有C的一些兼容约束。Swift采用了安全的编程模式和添加现代的功能来使得编程更加简单、灵活和有趣。界面则基于广受人民群众爱戴的Cocoa和Cocoa Touch框架,展示了软件开发的新方向。
PHP(外文名:PHP: Hypertext Preprocessor,中文名:“超文本预处理器”)是一种通用开源脚本语言。语法吸收了C语言、Java和Perl的特点,利于学习,使用广泛,主要适用于Web开发领域。PHP 独特的语法混合了C、Java、Perl以及PHP自创的语法。它可以比CGI或者Perl更快速地执行动态网页。用PHP做出的动态页面与其他的编程语言相比,PHP是将程序嵌入到HTML(标准通用标记语言下的一个应用)文档中去执行,执行效率比完全生成HTML标记的CGI要高许多;PHP还可以执行编译后代码,编译可以达到加密和优化代码运行,使代码运行更快。
IThao123周刊

我要回帖

更多关于 数据库设置默认值 的文章

 

随机推荐