Spring Boot,合成类的Thymeleaf验证

时间:2019-05-03 04:39:52

标签: java spring spring-boot thymeleaf

如何在Thymeleaf / Spring Boot中验证构图关系。我有一个简单的FundTrf类,该类​​具有“数据”类。问题是当我验证表单输入时,FundTrf类相关的字段得到验证,但是与数据类相关的字段没有得到验证。这些课程之间是否需要进行其他出价。下面是我尝试过的。

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>HNB CEFT | Test Bed</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
        <h1>Form</h1>
        <form action="#" th:action="@{/ceft/fundTrf}" th:object="${fundTrf}" method="post">
            <table>
                <tr><td>Version </td><td><input type="text" th:field="*{version}" /></td>
                    <td th:if="${#fields.hasErrors('version')}" th:errors="*{version}">Version Error</td>
                </tr>
                <tr><td>Bank Code </td><td><input type="text" th:field="*{data.dest_bank_code}" /></td>
                    <td th:if="${#fields.hasErrors('data.dest_bank_code')}" th:errors="*{data.dest_bank_code}">Bank Code Error</td>
                </tr>
                <tr><td>Amount </td><td><input type="text" th:field="*{data.amount}" /></td>
                    <td th:if="${#fields.hasErrors('data.amount')}" th:errors="*{data.amount}">Amount Error</td>
                </tr>
            </table>
            <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
        </form>
    </body>
</html>

下面是我的控制器类。

@Controller
public class Hello  implements WebMvcConfigurer{

    @GetMapping("/ceft/welcome")
    public String welcomeForm(Model model) {
        model.addAttribute("fundTrf", new FundTrf());
        return "welcome";
    }

    @PostMapping("/ceft/fundTrf")
    public String ceftTransaction(@ModelAttribute @Valid FundTrf fundTrf,  BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "welcome";
        } else {
            return "result";
        }
    }
}

下面是我的FundTrf课程

public class FundTrf {

    @NotEmpty
    private String version;
    private Data data;

    ..Getters and Setters
}

这是Data类。

public class Data {

    @NotEmpty
    private String reqId;
    @NotEmpty
    private String frm_hnb_account;
    @NotEmpty
    private String dest_bank_account;
    @NotEmpty
    private String benificiary_name;
    @NotEmpty
    private String dest_bank_code;
    @NotEmpty
    @Size(min = 2, max = 30)
    private String amount;

    ..Getters and Setters
}

问题是,当我提交带有空值的表单时,出现消息“版本不能为空”,但是金额验证不起作用。我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

您必须在对象Data上设置@Valid才能使您的Data属性也得到验证。

public class FundTrf {

    @NotEmpty
    private String version;
    @Valid //ADDED VALID HERE
    private Data data;

    ..Getters and Setters
}

javax.validation.Valid的Javadoc说:

  

标记属性,方法参数或方法的返回类型   验证级联。在对象及其上定义的约束   当属性,方法参数或   方法返回类型已验证。此行为是递归应用的。