我试图找出在我的 Spring MVC 应用程序中显示正确验证消息的方法。
这是示例 Bean:
@Entity
@Table(name="employees")
public class Person {
private Integer person_id;
private String name;
private String name2;
private String email;
private double phone;
private String desc;
@Id
@Max(value=500)
@Column (name="id")
public Integer getPerson_id() {
return person_id;
}
public void setPerson_id(Integer person_id) {
this.person_id = person_id;
}
@NotNull
@NotEmpty
@Column (name="fn")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="ln")
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
@Email
@Column (name="em", unique = true)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name="phone")
public double getPhone() {
return phone;
}
public void setPhone(double phone) {
this.phone = phone;
}
@Column (name="de")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String toString() {
return getName() + " - " + getName2() + " - " + getEmail();
}
}
我的控制器方法:
//POST
@RequestMapping(value="/persons", method = RequestMethod.POST, headers="Accept=*/*",
consumes="application/json")
public String getAllPersons(@RequestBody @javax.validation.Valid Person p, BindingResult br){
System.out.println( br.getAllErrors());
personService.savePerson(p);
return "redirect:persons.htm"; // redirects to the method below.
}
//GET
@RequestMapping(value="/persons", method = RequestMethod.GET, headers="Accept=*/*",
produces="application/json")
@ResponseBody
public List<Person> getAllPersons(){
List<Person> persons = personService.listPersons();
for (Person person : persons) {
System.out.println(person.getEmail());
}
if ( persons == null ) {
return null;
}
return persons;
}
这工作正常。但是当出现验证错误时。我只是得到简单的信息:
validation failed for: com.springmvcsample.controller.Person
它没有字段和失败的验证。
如何获取未通过验证的字段名称?我不认为我可以从BindingResults
对象中获取归档名称。
我已经搜索了一个例子。但是我得到了各种各样的例子,但没有像我需要做的那样。
我的异常处理程序方法:
@ExceptionHandler(Exception.class)
@ResponseBody
public String handleException( Exception e ) {
return e.getMessage();
}