
3.2 Thymeleaf编程起步
Thymeleaf需要按照传统MVC设计模式的方式来进行处理,所以在定义控制器的时候必须使用@Controller注解来完成。通过控制器的Model类对象,可以传递相应属性到页面中显示。
1.【mldnboot-thymeleaf项目】建立ThymeleafController程序类,该类将跳转到Thyemelaf模板页面。

2.【mldnboot-thymeleaf项目】ThymeleafController控制器会跳转到message目录下的message_show.html页面进行显示,而该页面一定要在CLASSPATH路径下配置。为了结构清晰,本程序将建立一个src/main/view的源文件,并且必须建立templates目录,随后在这个目录下创建所需要的子目录(本程序需要创建message子目录)。项目最终的目录结构如图3-1所示。

图3-1 Thymeleaf模板目录结构
提示:修改Thymeleaf的默认配置。
SpringBoot项目中Thymeleaf的动态页面需要保存在templates目录中,页面的扩展名默认使用的是*.html,如果开发者觉得这样的设计不合理,也可以通过application.yml配置文件自行修改。
范例:修改Thyemeleaf的配置项。

虽然SpringBoot中可以修改Thymeleaf的默认配置项,但是在实际开发中不建议修改,还是遵从默认配置比较合理。
3.【mldnboot-thymeleaf项目】编写message_show.html页面,实现控制层传递属性输出。

本程序使用<p>元素设定了要输出的内容。要想使用Thymeleaf的功能,必须以“th:属性”的形式处理,th:text的主要作用是进行文本输出。而要想输出request属性中的内容,则需要采用“${属性名称}”的语法格式完成。随后启动程序,输入访问地址http://localhost/view?mid=mldnjava,页面运行效果如图3-2所示。

图3-2 Thymeleaf模板运行
提示:传递HTML元素信息。
在本程序中,如果控制器传递的是一个HTML元素,那么对于Thymeleaf页面而言,就需要使用th:utext来显示HTML元素内容。
范例:【mldnboot-thymeleaf项目】修改ThymeleafController控制器,传递HTML元素。

范例:【mldnboot-thymeleaf项目】修改message_show.html页面。

本程序为了说明问题,特意使用了th:text和th:utext来输出url属性内容,程序执行结果如图3-3所示。

图3-3 传递HTML元素
另外需要注意的是,在Thymeleaf语法里面也可以直接使用各种运算符。

此时,Thyemeleaf模板页面会自动根据运算的数据类型和运算符进行计算。