我是Java新手。使用Thymeleaf和Spring-Boot。
尝试在错误的输入上显示验证消息。
"电话"属性必须在7到13个字符之间。如果不遵守规则,将显示验证消息。
请注意,验证有效,但未显示消息。
这是模型
@Entity
public class Author {
@Column(name = "phone")
@Size(min=7, max = 13, message = "The category name must be {min} to {max} characters in length.")
private String phone;
}
控制器
@Controller
@RequestMapping("/author")
public class AuthorController extends WebMvcConfigurerAdapter {
@Autowired
AuthorService authorService;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/new-author").setViewName("newauthor");
}
@RequestMapping(value="/new-author", method = RequestMethod.GET)
public String newAuthor(Model model){
Author author = new Author();
model.addAttribute("addNewAuthor", author);
return "newauthor";
}
@RequestMapping(value="/new-author", method = RequestMethod.POST)
public String newAuthor(@Valid Author author, BindingResult bindingResult, Model model){
model.addAttribute("addNewAuthor", author);
if (bindingResult.hasErrors()) {
return "newauthor";
}
try{
authorService.createAuthor(author);
model.addAttribute("statusReport", "Author Saved");
}
catch (Exception e){
model.addAttribute("statusReport", "Author not Saved");
}
return "newauthor";
}
}
这是视图
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Add Author</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../public/bootstrap-3.3.6- dist/css/bootstrap.css" th:href="@{/bootstrap-3.3.6-dist/css/bootstrap.css}"/>
</head>
<body>
<h1>Add New Author</h1>
<div class="col-lg-3" >
<form role="form" action="#" th:action="@{/author/new-author}" th:object="${addNewAuthor}" method="post">
<div th:class="form-group" th:classappend="${#fields.hasErrors('phone')}? 'has-error'">
<label>Phone</label>
<input class="form-control" type="text" th:field="*{phone}" placeholder="Enter author's phone number"/>
<p th:if="${#fields.hasErrors('phone')}" class="label label-danger" th:errors="*{phone}">Phone Error</p>
</div>
<button type="submit" class="btn btn-default">Add</button>
<button type="reset" class="btn btn-default">Reset</button>
<p th:text="${statusReport}" > </p>
</form>
</div>
</body>
</html>
答案 0 :(得分:2)
您的addNewAuthor
应该有@ModelAttribute
注释
它应该是:
public String newAuthor(
@Valid @ModelAttribute("addNewAuthor") Author author,
BindingResult bindingResult,
Model model) {
// ...
}
答案 1 :(得分:1)
我认为这样做更好,
首先,从message
约束
Size
@Column(name = "phone")
@Size(min=7, max = 13)
private String phone;
其次,将消息添加到本地化文件(message.properties
)。
Size.author.phone=The category name must be {1} to {2} characters in length.
另一种方式:
@Column(name = "phone")
@Size(min=7, max = 13, message="{phone.size}")
private String phone;
在message.properties
:
phone.size=The category name must be {1} to {2} characters in length.