我尝试创建了一个验证注解:
@Size(min = 6, message = "至少需要6个字符")
private String name;
现在,当我使用带有以下参数的方法(该方法标注了 POST
)时:
@Valid LoginDetails loginDetails
当验证失败(在表单中输入的字符少于6个)时,错误消息并未显示。但是,如果我将参数改为:
@Valid @ModelAttribute("logindetails") LoginDetails loginDetails
此时错误消息就会被显示出来。我想了解为什么会发生这种情况。
以下是可重现此问题的最小代码示例:
package com.example.validationspring;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class LoginDetails {
@NotNull(message = "用户名不能为空")
@Size(min = 6, message = "用户名至少需要6个字符")
private String userName;
// 标准的getter和setter方法
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
package com.example.validationspring;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import jakarta.validation.Valid;
@Controller
@RequestMapping("/login")
public class LoginController {
@GetMapping
public String showLoginForm(Model model) {
model.addAttribute("logindetails", new LoginDetails());
return "loginpage";
}
@PostMapping
public String submitLoginForm(@Valid @ModelAttribute("logindetails") LoginDetails loginDetails, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "loginpage"; // 如果有错误,则再次显示带有验证消息的表单
}
// 处理数据并重定向(假设验证已通过)
return "redirect:/success";
}
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<form th:action="@{/login}" th:object="${logindetails}" method="post">
<div>
<label for="userName">用户名:</label><br>
<input type="text" th:field="*{userName}" id="userName" />
<span th:if="${#fields.hasErrors('userName')}" th:errors="*{userName}">用户名错误</span>
</div>
<div>
<button type="submit">提交</button>
</div>
</form>
</body>
</html>