SpringBoot——Thymeleaf中的条件判断(th:if、th:unless、th:switch、th:case)

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);
    }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

★★光亭★★

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值