2017-03-01 17 views
1

我想了解@InitBinder。 我试图用多个InitBinder超过一个验证@ InitBinder的值元素的用途是什么?

@InitBinder("Validator1") 
protected void initBinder1(WebDataBinder binder) { 
    binder.setValidator(userFormValidator); 
} 

@InitBinder("Validator2") 
protected void initBinder2(WebDataBinder binder) { 
    binder.setValidator(costcenterFormValidator); 
} 

它不为我工作,因为该模型同时嵌套在一个包装类,我会进行验证做同样的

所以@InitBinder的值是什么时候是个好主意?

回答

2

根据javadoc,@InitBinder中的值是此init-binder方法应用于的命令/表单属性和/或请求参数的名称。默认是应用于所有的命令/表单属性和所有由注释处理程序类处理的请求参数。在这里指定模型属性名称或请求参数名称将init-binder方法限制为那些特定的属性/参数,其中不同的init-binder方法通常应用于不同的属性或参数组。

就你而言,你需要将@InitBinder注解的值设置为你希望它验证的模型属性的名称而不是验证器的某个名称。对于userFormValidator,如果你的模型属性名是用户,则initbinder应该是:

@InitBinder("user") 
protected void initBinder1(WebDataBinder binder) { 
    binder.setValidator(userFormValidator); 
} 

如果costcenterFormValidator是用于验证模型属性命名costcenter那么initbinder应该是:

@InitBinder("costcenter") 
protected void initBinder2(WebDataBinder binder) { 
    binder.setValidator(costcenterFormValidator); 
} 
0
// For multiple validations use annotations in the initBinder and give proper name of the ModelAttribute in the initBinder. 

@Controller 
public class Controller { 
private static final Logger logger = LoggerFactory.getLogger(Controller.class); 

@InitBinder("ModelattributeName1") 
private void initBinder(WebDataBinder binder) { 
    binder.setValidator(validator); 

} 

@Autowired 
MessageSource messageSource; 

@Autowired 
@Qualifier("FormValidatorID1") 
private Validator validator1; 


@InitBinder("ModelattributeName2") 
private void initBinder1(WebDataBinder binder) { 
    binder.setValidator(validator2); 
} 

@Autowired 
@Qualifier("FormValidatorID2") 
private Validator validator2; 


@RequestMapping(value = "/submit_form1", method = RequestMethod.POST) 
public String handleGetSubmission1(@Validated @ModelAttribute("ModelattributeName1") GetFormModel1 getFormModel1, 
     BindingResult result, Model model) { 

    model.addAttribute("getFormModel1", getFormModel1); 
    if (result.hasErrors()) { 
     return "get_Form1"; 
    } 

    return "get_Complete1"; 
} 


@RequestMapping(value = "/submit_form2", method = RequestMethod.POST) 
public String handleGetJavaAppletSubmission(@Validated @ModelAttribute("ModelattributeName2") GetFormModel2 getFormModel2, 
     BindingResult result, Model model) { 

    System.out.println(result); 
    model.addAttribute("getFormModel2", getFormModel2); 

    if (result.hasErrors()) { 
     return "get_Form2"; 
    } 

    return "get_Complete2"; 
} 
} 
相关问题