1.写在前面
th:if、th:unless、th:switch、th:case 这几个属性,其实和JSP里面的那些标签都是类似的,含义就可以理解为Java语言中的if、else、switch-case这些条件判断一样,所以这里就不再详细叙述了,下面就直接给出例子!!!
2.应用举例
首先写一个控制层, 其中有一个请求方法。
package com.songzihao.springboot.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * */ @Controller public class UserController { @RequestMapping(value = "/condition") public String condition(Model model) { model.addAttribute("sex","男"); model.addAttribute("flag",true); model.addAttribute("status",0); return "condition"; } }
然后是对应的html页面。
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>条件判断</title> </head> <body> <h2>th:if 用法:如果满足条件显示(执行),否则相反</h2> <div th:if="${sex eq '男'}"> man </div> <div th:if="${sex eq '女'}"> woman </div> <hr/> <h2>th:unless 用法:与th:if相反</h2> <div th:unless="${status != 1}"> 状态为0,不太行 </div> <div th:unless="${status ne 0}"> 状态为1,真不错 </div> <hr/> <h2>th:switch/th:case 用法</h2> <div th:switch="${flag}"> <span th:case="true">真</span> <span th:case="false">假</span> <span th:case="*">无此布尔值</span> </div> </body> </html>
最后是我们的核心配置文件(只有一行:关闭Thymeleaf的页面缓存)、项目启动入口类。
spring.thymeleaf.cache=false
package com.songzihao.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }