Thymeleaf 计数器变量不递增

Sam*_*Sam 1 spring counter increment thymeleaf spring-boot

我想在使用 thymeleaf 渲染我的 html 时有一个整数类型的计数器变量,但计数器变量意外增加。下面是我的代码。请帮忙。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en"
      xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div th:with="mycounter = 0">
    <div th:with="mycounter=${mycounter + 1}">
        <span th:text="${mycounter}"></span> <!-- result: 1 -->
    </div>
    <div th:with="mycounter=${mycounter + 1}">
        <span th:text="${mycounter}"></span> <!-- result: 1 , expected: 2-->
    </div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

mic*_*czy 5

您可以使用以下方法实现它:

在服务器端实现一个名为 Counter 的简单类:

public class Counter
{
    private int count;

    public Counter()
    {
        count = 0;
    }

    public Counter(int init)
    {
        count = init;
    }

    public int get()
    {
        return count;
    }

    public void clear()
    {
        count = 0;
    }

    public int incrementAndGet()
    {
        return ++count;
    }

    public String toString()
    {
        return ""+count;
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的 servlet 代码中添加:

context.addAttribute("counter", new Counter());
Run Code Online (Sandbox Code Playgroud)

在您的模板中,您可以像这样使用和增加它:

<div th:with="mycounter = ${counter.get()}">
    <div th:with="mycounter=${counter.incrementAndGet()}">
        <span th:text="${mycounter}"></span> <!-- result: 1 -->
    </div>
    <div th:with="mycounter=${counter.incrementAndGet()}">
        <span th:text="${mycounter}"></span> <!-- result: 2 , expected: 2-->
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • @jonasheinisch 你是对的,谢谢你提到它。我修好了它。 (2认同)