
上QQ阅读APP看书,第一时间看更新
3.6 内置对象操作支持
在模板页面中,最为常用的功能就是输出控制器传递的属性。为了方便用户开发,Thymeleaf支持内置对象的直接使用,也可以直接调用内置对象所提供的处理方法。
在通过控制器传递属性到Thymeleaf操作的时候,默认支持的属性获取范围为request(${属性名称})。如果要接收其他属性范围的内容,则需要指明范围,如session范围(${session.属性名称})、application范围(${application.属性名称})。
1.【mldnboot-thymeleaf项目】修改ThymeleafController控制器程序类,追加属性传递。本程序将传递request、session和application 3种属性范围的信息。

2.【mldnboot-thymeleaf项目】定义src/main/view/templates/message/message_attr.html页面,进行属性内容输出。

本程序在Thymeleaf模板页面中输出了控制器中传递的不同范围的属性内容。可以发现,只有request范围的属性可以直接通过表达式语法输出,而session与application范围的属性输出时,必须要有相应的范围标记,否则获取的内容就是null。本程序的执行结果如图3-8所示。

图3-8 Thymeleaf输出不同属性范围的信息
3.【mldnboot-thymeleaf项目】在Thymeleaf中也支持对内置对象的直接处理。修改message_attr.html页面,增加内置对象的方法调用。

本程序利用内置对象提供的方法获取了IP地址、request属性、sessionId以及项目真实路径,程序运行结果如图3-9所示。

图3-9 直接调用内置对象方法