【发布时间】:2019-05-03 04:39:51
【问题描述】:
如何在 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
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
}
问题是当我提交带有空值的表单时,出现“版本不能为空”的消息,但金额验证不起作用。我在这里做错了什么?
【问题讨论】:
标签: java spring spring-boot thymeleaf