1

为什么以下 Thymeleafth:if测试对字符串“0”、“1”和“9”失败?

我有一个Java数组如下:

String[] arrayData = {"x", "-1", "0", "1", "9", "10", "11"};

包括"x"在内是为了阐明此数组可以包含字母值和数值。

我有一个 Thymeleaf 模板,其中包含以下内容:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Test</title>
        <meta charset="UTF-8">
    </head>

    <body>
        
        <div th:if="${#arrays.contains(arrayData, '-1')}"
             th:text="'found array string \'-1\''"></div>
                
        <div th:if="${#arrays.contains(arrayData, '0')}"
             th:text="'found array string \'0\''"></div>
                
        <div th:if="${#arrays.contains(arrayData, '1')}"
             th:text="'found array string \'1\''"></div>
                
        <div th:if="${#arrays.contains(arrayData, '9')}"
             th:text="'found array string \'9\''"></div>
        
        <div th:if="${#arrays.contains(arrayData, '10')}"
             th:text="'found array string \'10\''"></div>
        
        <div th:if="${#arrays.contains(arrayData, '11')}"
             th:text="'found array string \'11\''"></div>
                
    </body>

</html>

我希望这会在浏览器中生成以下输出:

found array string '-1'
found array string '0'
found array string '1'
found array string '9'
found array string '10'
found array string '11'

但我实际上得到以下信息:

found array string '-1'
found array string '10'
found array string '11'

问题:为什么对字符串"0","1"和的测试会失败"9"?我究竟做错了什么?

对十个字符串值“0”到“9”的所有此类测试都失败了。超出该范围的任何内容都按预期工作。

ArrayList<String>如果我将, 与 Thymeleaf运算符一起使用,也会发生同样的事情#lists.contains()

Thymeleaf 版本是:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>

据我所知,我认为实现该#arrays.contains()功能的 Thymeleaf 代码在这里- 它看起来很简单。

我的 Java 版本是 AdoptOpenJDK 14。

在这种特定情况下,我没有使用 Spring。


更新,提供答案后

如果我使用任何单个字符(例如x)进行测试,则会发生与0through相同的问题9。所以这个标题在这方面有点误导。

4

1 回答 1

2

我怀疑如果您不使用Spring,Thymeleaf 表达式正在使用OGNLinsteald of进行解释SPeL——这似乎将单个字符常量视为类型char而不是类型String,因此#arrays.contains表达式无法匹配。

我没有测试 OGNL 的设置,但根据这篇文章,这应该可以:

<div th:text="${#arrays.contains(arrayData, &quot;0&quot;)}" />

(或者也许#arrays.contains(arrayData, '' + '0')会工作?)

于 2020-09-18T21:38:53.783 回答