Thymeleaf入门第二弹

Thymeleaf中的变量


Thymeleaf类似其他编程语言,也有变量的概念,在我们在前后端进行交互时,通过变量可以使我们很好地进行信息传递,

全局变量

一般我们在前后端进行交互时,可以通过 org.springframework.ui.Model 和 HttpServletRequest 来进行参数传递与赋值,如下所示

package com.caigentan.thymeleaf;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
//注意:@Controller注解的类需要放在 SpringBasicApplication.java 同级或者下层才有作用,否则会 404
@Controller
public class VariableProgram {
    @GetMapping("/variable")
    public String ariableProgram(Model model, HttpServletRequest request) {
        model.addAttribute("variable1", "变量1");
        request.setAttribute("variable2", "变量2");
        return "variable";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:utext="${variable1}"></p>
    <p th:utext="${variable2}"></p>
</body>
</html>

结果:
在这里插入图片描述

局部变量

package com.caigentan.spring.thymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LocalVariableProgram {
    @RequestMapping("localVar")
    public String localVariable(Model model) {
        String[] countries = new String[]{"中国", "越南", "古巴", "朝鲜"};
        model.addAttribute("countries", countries);
        return "localvariable";
    }
}

localvariable.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table border="1">
        <tr>
            <th>No</th>
            <th>Name</th>
        </tr>
        <tr th:each="country,iter:${countries}">
            <td th:utext="${iter.count}"></td>
            <td th:utext="${country}"></td>
        </tr>
    </table>
</body>
</html>

效果:
在这里插入图片描述
当然我们也可以使用Thymeleaf进行参数赋值(th:with),以构成自定义局部变量,如下所表示,在localvariable.html中新添:

	<div th:with="country0=${countries[0]}">
        <h2>th:with</h2>
        <p th:utext="${country0}"></p>
    </div>

运行效果如下:
th:with
注:th:with的赋值不可跨域
其他的变量叙述请查阅

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值