简体   繁体   中英

Spring MVC - REST Webservices. Bean Validation Messages

I am trying to find out the way to show proper validation messages in my Spring MVC application.

This is the Example 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();
    }
}

My controller methods:

    //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;
 }

This is working fine. But when there is a validation error. I just get plain message:

  validation failed for: com.springmvcsample.controller.Person

It does not the field and the failed validation.

How to get the field name that failed the validation? I don't think I can get filed names from BindingResults object.

I have searched for an example. But I get varied examples, but not anything like what I need to do.

My Exception Handler method:

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

getAllErrors() returns a List<ObjectError> . You should iterate over those.

Change your method to something similar

@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";
    }
}

Some constraints like @Max have a message field you can use to set the default message used above.

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

Use this to add custom messages.

The BindingResult class has other methods you can use to find the actual field causing the validation error. Take a look here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM