gpt4 book ai didi

spring - Thymeleaf 和 #fields.hasErrors

转载 作者:行者123 更新时间:2023-12-01 15:28:59 26 4
gpt4 key购买 nike

我有这个任务,我正在为学校工作。使用 SpringMVC、Hibernate JPA 和 Thymeleaf。下面的代码涉及一个名为“stringGrade ”的特定属性。我想使用 Hibernate Validator 验证该字段中的输入。我似乎无法让 Thymeleaf 读取表达式。在 View 中循环的 arrayList 有一个 name 属性“deliverables[0].stringGrade”等等,这取决于有多少。我曾尝试使用“交付物[ ${stat.index} ].name ”,这会导致 Thymeleaf 失败并出现以下错误:

HTTP 状态 500 - 请求处理失败;嵌套异常是 org.thymeleaf.exceptions.TemplateProcessingException:评估 SpringEL 表达式的异常:“#fields.hasErrors('deliverables[0].stringGrade')”(menuItems/inputGrades:33)

我想要做的就是让 Thymeleaf 能够使用 #fields.HasErrors 和 #fields.error 读取值。下面是相关的代码:

成绩计算器型号:

public class GradeCalculator {

private ArrayList<Deliverable> deliverables;

交付模型:
@Entity
@Table(name="Deliverables")
public class Deliverable implements Serializable {


@NotEmpty(message = "Required")
@Size(min = 1, max = 100, message = "Must be between 1 and 100")
@Digits(integer = 3, fraction = 0, message = "Must be a numeric value")
private String stringGrade; // String version of the grade ( Used for view input fields )

thymeleaf View :
<form th:object="${gradeCalculator}" action="#" th:action="@{/process/inputGrades}" method="POST" class="form-horizontal" role="form">

<div th:each="deliverable,stat : ${grades.deliverables}">
<div class="form-group">
<p>Deliverable Name<span th:text="${grades.deliverables[__${stat.index}__].name}" name="name" id="name" class="badge tab-space"></span></p>
<p>Deliverable Weight<span th:text="${grades.deliverables[__${stat.index}__].weight}" name="weight" id="weight" class="badge tab-space"></span></p>

<h3><span class="label">Grade:</span></h3>

<input type="text" th:field="${grades.deliverables[__${stat.index}__].stringGrade}" class="form-control" />
<ul class="help-inline" th:if="${#fields.hasErrors('deliverables[__${stat.index}__].stringGrade')}">
<li class="error" th:each="err : ${#fields.errors('deliverables[__${stat.index}__].stringGrade')}" th:text="${err}">Input is incorrect</li>
</ul>
</div>
</div>

<div class="form-group">
<div class="text-center col-sm-10 col-sm-offset-2 col-md-4 col-md-offset-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>

</form>

最佳答案

找到了答案。我没有通过使用 Thymeleaf 变量表达式正确处理“交付物[ ${stat.index} ].stringGrade”。我应该这样做:

<ul class="help-inline" th:if="${#fields.hasErrors('${grades.deliverables[__${row.index}__].stringGrade}')}">
<li
class="error"
th:each="err : ${#fields.errors('${grades.deliverables[__${row.index}__].stringGrade}')}"
th:text="${err}">
Input is incorrect
</li>
</ul>

关于spring - Thymeleaf 和 #fields.hasErrors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33715938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com