gpt4 book ai didi

java - Spring Boot、Thymeleaf 组合类验证

转载 作者:行者123 更新时间:2023-11-30 05:39:27 26 4
gpt4 key购买 nike

如何验证 Thymeleaf/Spring Boot 中的组合关系。我有一个简单的 FundTrf 类,它“有一个”数据类。问题是当我验证表单输入时,FundTrf 类相关字段得到验证,但 Data 类相关字段没有得到验证。这些类别之间是否需要进行额外的投标?以下是我尝试过的。

<!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 类。

@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 类(class)

public class FundTrf {

@NotEmpty
private String version;
private Data data;

..Getters and Setters
}

这是数据类。

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
}

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

最佳答案

您必须在数据对象上设置@Valid,以便您的数据属性也得到验证。

public class FundTrf {

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

..Getters and Setters
}

javax.validation.Valid 的 javadoc 说:

Marks a property, method parameter or method return type for validation cascading. Constraints defined on the object and its properties are be validated when the property, method parameter or method return type is validated. This behavior is applied recursively.

关于java - Spring Boot、Thymeleaf 组合类验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55963384/

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