@initbinder not working for specific model attribute

后端 未结 2 686
迷失自我
迷失自我 2021-02-09 13:07

I am using @valid and @initbinder for validation of the data being passed to the service but I am facing an issue that @InitBinder is working only globally,i.e.

相关标签:
2条回答
  • 2021-02-09 13:49

    Looking at the signature of your method it has to be

    @InitBinder("loginRequest")
    

    with a small l

    The value of @InitBinder can be one of the following

    • The name of a model attribute
    • The name of a request parameter
    • If none of the above apply, then the name of the class can be used, but starting with a small letter. That's how Spring exposes unnamed attributes to the model.
    0 讨论(0)
  • 2021-02-09 13:54

    @a-better-oliver's answer is great, but below is an another approach to the same problem with Spring, more verbose but typesafe:

    @InitBinder
    protected void initBinder(WebDataBinder binder){
      if (binder.getTarget() != null 
          && LoginRequest.class.equals(binder.getTarget().getClass())) {
        binder.setValidator(new LoginRequestValidator());
      }
    }
    

    This way we do not rely on the hard-coded string and also do not care how Spring exposes unnamed attributes.

    0 讨论(0)
提交回复
热议问题