Bobo
Bobo

Reputation: 9163

spring validation how do I get validation results?

code as follows:

....
@RequestMapping( "/test")
    @ResponseBody
    public ResponseTO test(
            @Valid  @RequestBody RequestTO to, HttpServletResponse resp)
    {
           //how do I get validation results here?
        return new ResponseTO("111");
    }

  @InitBinder
  protected void initBinder(WebDataBinder binder) {
      binder.setValidator(new TestValidator());
  }




class TestValidator implements Validator {

    /**
    * This Validator validates just Person instances
    */
    public boolean supports(Class clazz) {
        return RequestTO.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        RequestTO tx = (RequestTO) obj;
        if (tx.getName().equals("buy")) {
            e.rejectValue("feature", "NOT BUY");
        } 
    }
}   

The part I could not figure out is how do I can get the validation results in the controller? Thanks!

Upvotes: 1

Views: 1788

Answers (1)

Ajinkya
Ajinkya

Reputation: 22720

As Sunil have mentioned you are mixing two approaches

If you want to use JSR303 Bean validations, you can define constraints of bean fields like

public class Customer {

    @NotEmpty //make sure name is not empty
    String name;

    @Range(min = 1, max = 150) //age need between 1 and 150
    int age;
 } 

@valid is used to validate bean fields and you can get the errors using BindingResult like

@RequestMapping(value = "/signup", method = RequestMethod.POST)
    public String addCustomer(@Valid Customer customer, BindingResult result) {

        if (result.hasErrors()) {
            return "SignUpForm";
        } else {
            return "Done";
        }
    }  

Check this link for more details.

Or you can implement Validator and define validate method (As you have mentioned in your question).
Then you have to invoke the validate method, pass BindingResult object and add erros if present. Then you can check the BindingResult object for any errors.
For ex.

new TestValidator ().validate(requestTO , bindingResult); // invoking validate method     

and check for errors

if (bindingResult.hasErrors()) {
  // Errors are present do something here
}
else
{
  // All is well!!
}

Or you can define validator to particular bean spring config file. Check this link for details.

Upvotes: 1

Related Questions