SpringBoot——Thymeleaf中的四种字面量(文本数字布尔null)字符串拼接运算符

Posted 张起灵-小哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot——Thymeleaf中的四种字面量(文本数字布尔null)字符串拼接运算符相关的知识,希望对你有一定的参考价值。

1.四种字面量

首先写一个User类、以及控制层UserController类, 其中有一个请求方法。

package com.songzihao.springboot.model;

/**
 *
 */
public class User {

    private Integer id;
    private String username;

    //getter and setter
}
package com.songzihao.springboot.controller;

import com.songzihao.springboot.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @RequestMapping(value = "/literal")
    public String literal(Model model) {
        model.addAttribute("sex",1);
        model.addAttribute("data","SpringBoot Thymeleaf");
        model.addAttribute("flag",true);

        User user=new User();
        user.setId(1001);
        user.setUsername("张起灵");
        model.addAttribute("user",user);

        User userDetail=new User();
        model.addAttribute("userDetail",userDetail);

        return "literal";
    }
}

然后是这个请求方法对应的html页面。(其中包含了四种字面量的声明与使用)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>字面量</title>
</head>
<body>
    <h3>文本字面量,用单引号 '......' 的字符串就是字面量</h3>
    <a th:href="@{'/user/literal?sex=' + ${sex}}">查看性别</a>
    <hr/>
    <h3>数字字面量</h3>
    今年是 <span th:text="2020">1945</span>年<br/>
    20年后是 <span th:text="2020+20">1965</span>年<br/>
    <hr/>
    <h3>boolean字面量</h3>
    <div th:if="${flag}">
        执行成功!!!
    </div>
    <div th:unless="${flag}">
        执行失败。。。
    </div>
    <hr/>
    <h3>null字面量</h3>
    <span th:if="${user ne null}">用户不为空</span>
    <div th:unless="${userDetail eq null}">
        对象已创建,不为空
    </div>
    <div th:if="${userDetail.id eq null}">
        userDetail的id为空
    </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.字符串拼接

使用 | 进行字符串拼接。


3.运算符

三元运算:表达式?” 正确结果”:” 错误结果”

算术运算: :+ , - , * , / , %

关系比较:> , < , >= , <= ( gt , lt , ge , le )

相等判断:== , != ( eq , ne )

以上是关于SpringBoot——Thymeleaf中的四种字面量(文本数字布尔null)字符串拼接运算符的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot系列教程web篇Servlet 注册的四种姿势

运行SpringBoot工程的四种方法

springboot 中使用thymeleaf

Springboot 解决跨域的四种姿势

springboot的四种拦截机制

解决springboot2.6和swagger冲突的四种方法