spring mvc使用注解后的校验和绑定处理

spring mvc使用注解后,依然可以使用自带的Validator接口。比如这样一个Validator实现:

  
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> @Component( " productValidator " ) public class ProductValidator implements Validator { @SuppressWarnings( " unchecked " ) @Override public boolean supports(Class clazz) { return Product. class .isAssignableFrom(clazz); } @Override public void validate(Object object, Errors errors) { ValidationUtils.rejectIfEmpty(errors, " name " , " field.required " ); }

 

在Controller中通过注解获取:

  
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> @Resource(name = " productValidator " ) private Validator validator; ... @RequestMapping( " /save.htm " ) public ModelAndView save(Product product, BindingResult result) { this .validator.validate(product, result); if (result.hasErrors()) { return new ModelAndView( " input " ); } ...

如果是绑定相关的,比如只是检查不能为空,可以用下面方式替代,在Controller中增加:

  
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> @InitBinder public void initDataBinding(WebDataBinder binder) { binder.setRequiredFields( new String[] { " name " }); }

在错误信息的属性文件中增加:

required={0}不能为空
product.name=名称

上述两种方式使用共同的属性文件配置方法,在spring的配置文件中:

  
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> < bean id ="messageSource" class ="org.springframework.context.support.ResourceBundleMessageSource" > < property name ="basenames" > < list > < value > errors </ value > </ list > </ property > </ bean >

在jsp页面中通过spring的form标签显示:

 

  
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> <% @ taglib prefix = " form " uri = " http://www.springframework.org/tags/form " %> ...... <% @ taglib prefix = " form " uri = " http://www.springframework.org/tags/form " %> ......

另外,如果InitBinder注解不加参数,将检查所有控制器方法调用的入参,可能有些类型入参不需要检查,这时可以:

  
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> @InitBinder( " product " ) public void initDataBinding(WebDataBinder binder) { binder.setRequiredFields( new String[] { " name " }); }

你可能感兴趣的:(spring,mvc,bean,jsp)