一、spring 自带validator验证
validator类:
public class AccountValidator implements Validator{
public boolean supports(Class<?> clazz) {
return AccountModel.class.isAssignableFrom(clazz);
// return false;
}
Logger log = Logger.getLogger(AccountValidator.class);
public void validate(Object target, Errors errors) {
// TODO Auto-generated method stub
AccountModel account = (AccountModel)target;
ValidationUtils.rejectIfEmpty(errors, "userName", "account.userName.required","用户名不能为空~");
int length= account.getUserName().length();
if (length>10){
errors.rejectValue("userName", "account.userName.toolong",new Object[] {"10"},"用户名不能超过10个字符");
log.info("---------------->用户名验证失败超过长度10");
}
}
}
控制器:
第一种:在controll类内new 上述验证类
@RequestMapping("/addSubmit")
public ModelAndView create(
@ModelAttribute("accountModel") AccountModel accountModel,BindingResult bindingResult,
HttpServletRequest request, HttpServletResponse response) {
AccountValidator validator = new AccountValidator();
validator.validate(accountModel, bindingResult);
ModelAndView view = null;
if (bindingResult.hasErrors()){
view = new ModelAndView("/add.jsp","accountModel", accountModel);
}else{
AccountService as = (AccountService) ac.getBean("accountService");
int result = as.insertUser(accountModel);
view = result==0?new ModelAndView("/success.jsp"):new ModelAndView("/add.jsp","accountModel", accountModel);
}
return view;
}
第二种:通过dispatcher-servlet.xml配置文件指定全局验证类
<mvc:annotation-driven validator="accountValidator"/>
<bean id="accountValidator" class="com.hoo.Validator.AccountValidator"></bean>
control类直接使用:
@RequestMapping("/addSubmit")
public ModelAndView create(
@ModelAttribute("accountModel") @Valid AccountModel accountModel,BindingResult bindingResult,
HttpServletRequest request, HttpServletResponse response) {
// validator = new AccountValidator();
// validator.validate(accountModel, bindingResult);
ModelAndView view = null;
if (bindingResult.hasErrors()){
view = new ModelAndView("/add.jsp","accountModel", accountModel);
Log.info("------------------------>error occour~");
}else{
AccountService as = (AccountService) ac.getBean("accountService");
int result = as.insertUser(accountModel);
view = result==0?new ModelAndView("/success.jsp"):new ModelAndView("/add.jsp","accountModel", accountModel);
}
return view;
}
第三种:通过dispatcher-servlet.xml的WebBindingInitializer的initBinder方法来设定
control类中添加@InitBinder,其余参考第二种control类
@InitBinder
public void initBinder(DataBinder binder) {
binder.setValidator(new AccountValidator());
}
二、JSR-303验证框架注解验证
包:maven导入hibernate-validator包:hibernate-validator-4.3.1.Final-1.0.0.jar
配置文件:
<mvc:annotation-driven validator="validator"/>
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
</bean>
<bean id="webBindingInitializer"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="messageSource" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="basename" value="messages" />
</bean>
模型类:
public class AccountModel implements Serializable {
private static final long serialVersionUID = -7970848646314840509L;
// ユーザー名
@NotBlank(message="{account.username.not.empty}")
private String userName;
省略get set方法
消息文件:messages_zh_CN.properties
account.username.not.empty = \u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A\u3002
本文详细介绍了Spring框架中如何使用自定义验证器进行表单验证,包括三种不同的实现方式:在Controller中直接创建验证器实例、通过配置文件指定全局验证器以及在WebBindingInitializer中初始化验证器。同时,文章还讲解了如何利用JSR-303注解进行模型验证,包括必要的Maven依赖、配置文件设置及模型类上的注解使用。
2288

被折叠的 条评论
为什么被折叠?



