我尝试对thymeleaf上的input
字段进行验证,一切正常,直到我在th:field
添加验证
导致java.lang.IllegalStateException:既不是BindingResult也不是 bean名称的普通目标对象' person1'可根据要求提供 属性
另外,我不知道是什么原因引起的 我的实体:
@Entity
@Table(name="person")
public class Person implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@NotNull(message = "cannot be null")
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "person")
private List<PhoneNumber> phoneNumber;
public Person() {
super();
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<PhoneNumber> getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(List<PhoneNumber> phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
我的控制器:
@Controller
public class PersonController {
@Autowired
PersonService personService;
@RequestMapping(value = "/All", method = RequestMethod.GET)
public String getAllPerson(Model model) {
ArrayList<Person> listPerson = personService.getAll();
model.addAttribute("listPerson",listPerson);
return "/All";
}
@RequestMapping(value = "/Edit", method = RequestMethod.POST)
public String editPerson(@Valid @ModelAttribute(value="person1") PersonRequest person, BindingResult result) {
if(result.hasErrors()) {
return "/All";
}
else {
personService.update(person.getId(), person.getName());
return "redirect:All";
}
}
}
我的表格:
<div id ="EditModal" class="modal fade" role="dialog">
<form class="modal-dialog" th:action="@{/Edit}" th:object="${person1}" method="POST">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<input type="hidden" id="edit-modal-person-id" name="id" value=""/>
<input type="text" th:field="*{name}" placeholder="Name" id="edit-modal-person-name" name="name" value=""/>
<p th:if="${#fields.hasErrors('name')}" class="label label-danger" th:errors="*{name}">Name Error</p>
<div>
<a class="btn btn-default pull-right" id="PhoneNumberEdit">Edit Phone Number</a>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="SubmitEdit" class="btn btn-default" >Submit</button>
<button type="button" class = "btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function(){
$(".buttonEdit").click(function(e){
e.preventDefault();
var id = $(this).attr('data-id');
$.ajax({
type: "GET",
url : "/GetOnePerson",
data : 'id=' + id,
datatype : "text",
success : function(result){
$('#edit-modal-person-id').val(result.id);
$('#edit-modal-person-name').val(result.name);
$('#PhoneNumberEdit').prop('th:attr','data-id='+id);
},
error : function(){
alert("ERROR");
}
});
});
});
</script>
无论如何都要避免使用th:field?或任何其他验证字段的方法?