私はJavaで新しいです。 ThymeleafとSpring-Bootを使用する。Thymeleafで検証メッセージが機能しない
誤った入力で検証メッセージを表示しようとしています。
「電話」プロパティの長さは、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";
}
}
ビューはあなたのaddNewAuthor
が@ModelAttribute
注釈を持っている必要があり
<!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>
それは魔法のように働いた:)。ありがとう。 – Tareq