Tutorial: Thymeleaf + Spring
本教程中的代码示例和示例应用程序使用spring4.x及其相应的Thymeleaf集成,但本文的内容也适用于spring3.x。如果您的应用程序使用spring3.x,则只需在代码示例中将org.Thymeleaf.spring4包替换为org.Thymeleaf.spring3。
1 Integrating Thymeleaf with Spring
Thymeleaf提供了一组Spring集成,允许您在Spring MVC应用程序中使用它作为JSP的完全功能替代品。
这些集成将允许您:
- 让Spring MVC@Controller对象中的映射方法转发给由Thymeleaf管理的模板,就像使用jsp一样。
- 在模板中使用Spring表达式语言(Spring EL)而不是OGNL。
- 在模板中创建与表单备份bean和结果绑定完全集成的表单,包括使用属性编辑器、转换服务和验证错误处理。
- 显示来自Spring管理的消息文件的国际化消息(通过通常的消息源对象)。
- 使用Spring自己的资源解析机制解析模板。
请注意,为了完全理解本教程,您应该首先完成“使用Thymeleaf”教程,该教程深入解释了thymeleaf标准语言【the SpringStandard Dialect】。
2 The SpringStandard Dialect
为了实现更容易和更好的集成,Thymeleaf提供了一种方言,它专门实现了所有需要的特性,以便能够正确地与Spring一起工作。
此特定语言基于Thymeleaf标准语言,并在名为org.Thymeleaf.spring4.dialect.SpringStandardDialect的类中实现,该类实际上扩展自org.Thymeleaf.Standard.StandardDialect。
除了标准方言中已经存在并因此继承的所有特性之外,The SpringStandard Dialect还引入了以下具体特征:
- 使用 Spring表达式语言(Spring EL或SpEL) 作为变量表达式语言,而不是OGNL。因此,所有的**${…}和*{…}表达式都将由Spring的表达式语言引擎计算。还要注意,也同样支持Spring EL编译器**(Spring 4.2.4+)。
- 使用SpringEL的语法访问应用程序上下文中的任何bean:${@myBean.doSomething()}
- 表单处理的新属性:th:field、th:errors和th:errorclass,此外还有一个新的th:object实现,允许它用于表单命令选择。
- 表达式对象和方法**#themes.code(…)**,相当于spring:theme JSP自定义标记。
- 表达式对象和方法**#mvc.uri(…)**,相当于spring:mvcUrl(…)JSP自定义函数(仅在spring 4.1+中)。
请注意,在大多数情况下,您不应该在普通的TemplateEngine对象中直接使用此方言作为其配置的一部分。除非您有非常具体的Spring集成需求,否则您应该创建一个新模板引擎类的实例,该类自动执行所有必需的配置步骤:org.thymeleaf.spring4.SpringTemplateEngine。
bean配置示例:
@Bean
public SpringResourceTemplateResolver templateResolver(){
// SpringResourceTemplateResolver automatically integrates with Spring's own
// resource resolution infrastructure, which is highly recommend