Thymeleaf和#fields.hasErrors

问题描述 投票:3回答:1

我有这项任务,我正在上学。使用SpringMVC,Hibernate JPA和Thymeleaf。下面的代码涉及一个名为“stringGrade”的特定属性。我想使用Hibernate Validator验证该字段中的输入。我似乎无法让Thymeleaf读到这个表达。在视图中循环的arrayList的名称属性为“deliverrables [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读取值。以下是相关的代码:

GradeCalculator型号:

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 Viev:

<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>
spring thymeleaf spring-el
1个回答
2
投票

找到了答案。我没有使用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>
© www.soinside.com 2019 - 2024. All rights reserved.