关于java8中LocalDateTime与thymeleaf整合时产生的问题

一开始使用springboot与thymeleaf整合时,发现java8中关于时间的字段LocalDateTime在前台使用dates.format会报错。
前端代码如下:

<td style=""th:text="${#dates.format(data.updateDate,'yyyy-MM-dd HH:mm:ss')}"></td>

报错信息:

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method format(java.time.LocalDateTime,java.lang.String) cannot be found on type org.thymeleaf.expression.Dates
	at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:225) ~[spring-expression-5.1.6.RELEASE.jar:5.1.6.RELEASE]
	at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:134) ~[spring-expression-5.1.6.RELEASE.jar:5.1.6.RELEASE]
	at org.springframework.expression.spel.ast.MethodReference.access$000(MethodReference.java:54) ~[spring-expression-5.1.6.RELEASE.jar:5.1.6.RELEASE]
	at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:390) ~[spring-expression-5.1.6.RELEASE.jar:5.1.6.RELEASE]
	at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:90) ~[spring-expression-5.1.6.RELEASE.jar:5.1.6.RELEASE]
	at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:109) ~[spring-expression-5.1.6.RELEASE.jar:5.1.6.RELEASE]
	at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:328) ~[spring-expression-5.1.6.RELEASE.jar:5.1.6.RELEASE]
	at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:263) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
	... 79 common frames omitted

查找相关资料,发现thymeleaf对于此类报错,增加了一个增强包,maven工程中需要在pom中引入如下包:

<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-java8time</artifactId>
		</dependency>

然后在前端代码改为:

<td style=""th:text="${#temporals.format(data.updateDate,'yyyy-MM-dd HH:mm:ss')}"></td>

这样就能够正常使用了。


版权声明:本文为weixin_42031557原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。