Spring 6、Spring Boot 3升级后Thymeleaf中UUID调用equals方法受限问题
Spring Boot 3 + Thymeleaf 3.1 中UUID比较的权限问题解决方案
升级Spring 6、Spring Boot 3 GA版本后,使用Thymeleaf生成表单下拉选择框时,th:selected表达式中调用UUID的equals()方法触发权限拦截异常,原因是Thymeleaf Spring6版本默认禁止调用java.util.*包下类的方法,而UUID不在预设的允许类列表中。
原报错代码片段:
<option th:each="bankAccount : ${bankAccounts}" th:value="${bankAccount.getId()}" th:text="${bankAccount.getName()}" th:selected="${bankAccount.getId().equals(bankAccountId)}"> BANK_ACCOUNT_NAME </option>
解决方案推荐
1. 直接使用表达式==比较(最优解)
Thymeleaf的Spring EL表达式中,==用于对象比较时会自动调用对象的equals()方法,无需显式调用,完美规避权限限制:
<option th:each="bankAccount : ${bankAccounts}" th:value="${bankAccount.getId()}" th:text="${bankAccount.getName()}" th:selected="${bankAccount.getId() == bankAccountId}"> BANK_ACCOUNT_NAME </option>
2. 实体类新增字符串ID属性
在BankAccount实体中添加返回UUID字符串的方法,通过字符串比较绕过方法调用限制:
public class BankAccount { private UUID id; // 原有属性、getter/setter public String getIdAsString() { return id != null ? id.toString() : null; } }
模板中修改为字符串比较:
<option th:each="bankAccount : ${bankAccounts}" th:value="${bankAccount.idAsString}" th:text="${bankAccount.name}" th:selected="${bankAccount.idAsString == #strings.toString(bankAccountId)}"> BANK_ACCOUNT_NAME </option>
注:#strings.toString()是Thymeleaf内置工具方法,属于允许调用的范围,可将UUID转为字符串。
3. 自定义Spring Bean工具类
创建一个管理UUID比较的Bean,通过Thymeleaf表达式调用Bean方法:
import org.springframework.stereotype.Component; import java.util.UUID; @Component("uuidHelper") public class UUIDHelper { public boolean isEqual(UUID first, UUID second) { if (first == null && second == null) return true; return first != null && first.equals(second); } }
模板中调用方式:
<option th:each="bankAccount : ${bankAccounts}" th:value="${bankAccount.getId()}" th:text="${bankAccount.getName()}" th:selected="${@uuidHelper.isEqual(bankAccount.getId(), bankAccountId)}"> BANK_ACCOUNT_NAME </option>
4. 修改Thymeleaf权限配置(不推荐)
若必须调用UUID原生方法,可将java.util.UUID加入Thymeleaf允许调用的类列表,但会降低安全性,不建议生产环境使用:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.thymeleaf.spring6.expression.ThymeleafEvaluationContext; import java.util.UUID; @Configuration public class ThymeleafCustomConfig { @Bean public ThymeleafEvaluationContext thymeleafEvaluationContext() { ThymeleafEvaluationContext context = new ThymeleafEvaluationContext(); context.addAllowedClass(UUID.class); return context; } }
内容的提问来源于stack exchange,提问作者jspetrak
相关产品推荐
相关产品推荐

