我试图在电话号码输入中添加验证,但我坚持解决访问索引时的错误。
错误消息
由以下原因引起:org.attoparser.ParseException:执行期间出错 处理器 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (模板:“索引”-第76行,第73行)
由于:java.lang.IllegalStateException:既没有BindingResult也没有 Bean名称“ phonenumber”的简单目标对象可作为请求提供 属性
index.html
D
控制器
A
电话簿
<div class="myForm">
<form th:action="@{/save}" method="post" th:object="${phonebook}">
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Update or Create</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<input type="hidden" class="form-control" id="id" name="id" value=""/>
</div>
<div class="form-group">
<label for="surname" class="col-form-label">Surname:</label>
<input type="text" class="form-control" id="surname" name="surname" value=""/>
</div>
<div class="form-group">
<label for="firstname" class="col-form-label">First Name:</label>
<input type="text" class="form-control" id="firstname" name="firstname" value=""/>
</div>
<div class="form-group">
<label for="phonenumber" class="col-form-label">Phone Number:</label>
<input type="text" class="form-control" th:field="*{phonenumber}" id="phonenumber" name="phonenumber" value=""/>
<span th:if="${#fields.hasErrors('phonenumber')}" class="help-block" th:errors="*{phonenumber}"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save"/>
</div>
</div>
</div>
</div>
</form>
答案 0 :(得分:1)
我有2种方法可以解决此问题:-
1。)使用@RequestParam获得像这样的电话簿对象:-
@PostMapping("/save")
public String save(@Valid @RequestParam("phonenumber")String phonenumber, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "redirect:/";
}else {
phonebookRepository.save(p);
}
return "redirect:/";
}
OR-使用@ModelAttribute来获取表单的值,就像这样:-
1。)创建一个新的Phonebook对象并添加model属性:-
@RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String showPage(Model model, @RequestParam(defaultValue = "0") int page) {
//your code
model.addAttribute("phoneBook", new Phonebook());
return "index";
}
2。)Thymeleaf / HTML页面中的更改(提交后使用 th:object 发送电话簿对象):-
<form th:action="@{/save}" method="post" th:object="${phoneBook}">
// your code
</form>
3。)然后使用@ModelAttribute绑定这样的值:-
@PostMapping("/save")
public String save(@Valid @ModelAttribute("phoneBook")Phonebook p, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "redirect:/";
}else {
phonebookRepository.save(p);
}
return "redirect:/";
}
4。)最后是使用getter和setter方法的Phonebook类。