Spring MVC - REST Web服务。 Bean验证消息

时间:2013-04-22 04:51:45

标签: java rest spring-mvc error-handling bean-validation

我试图找到在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对象获取文件名。

我搜索了一个例子。但是我得到了各种各样的例子,但不是我需要做的事情。

My Exception Handler方法:

@ExceptionHandler(Exception.class)
@ResponseBody
public String handleException( Exception e ) {
    return e.getMessage();
}

1 个答案:

答案 0 :(得分:1)

getAllErrors()返回List<ObjectError>。你应该迭代这些。

将您的方法更改为类似的方法

@RequestMapping(value="/persons", method = RequestMethod.POST, headers="Accept=*/*", 
                consumes="application/json")
public String getAllPersons(@RequestBody @javax.validation.Valid Person p, BindingResult br){
    if (br.hasErrors()) {
        List<ObjectError> errors = br.getAllErrors();
        for (ObjectError error : errors) { // iterate through all the errors
            System.out.println(error.getDefaultMessage()); // or log it somewhere else
        }
        return "redirect:error.htm"; // some error page
    } else {
        personService.savePerson(p);
        return "redirect:persons.htm";
    }
}

某些约束如@Max有一个message字段,可用于设置上面使用的默认消息。

@Id
@Max(value=500, message = "The person id cannot be larger than 500.")
@Column (name="id")
public Integer getPerson_id() {
    return person_id;
}

使用此选项添加自定义消息。

BindingResult类有其他方法可用于查找导致验证错误的实际字段。 Take a look here