标签:user 用户 创建 str port not framework prope ogg
1.导包
校验器分别导的包有:hibernate-validator-4.3.0.Final.jar,validation-api-1.0.0.GA.jar,jboss-logging-3.1.0.CR2.jar
2.在springmvc.xml配置文件中配置
2.1.配置校验器
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- 指定配置的校验器提供类为HibernateValidator -->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
<!--对应的错误信息-->
<property name="validationMessageSource" ref="messageSource"/>
</bean>
2.2.配置错误信息配置文件
<!-- 加载错误信息定义的资源文件的类为org.springframework.context.support.ReloadableResourceBundleMessageSource-->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 指定资源文件名为basenames -->
<property name="basenames">
<list>
<!--添加资源文件的配置信息-->
<value>classpath:ProductValidationMessages</value>
</list>
</property>
<!--指定文件编码为utf-8-->
<property name="fileEncodings" value="utf-8"/>
<!--指定内容缓存时间为120s-->
<property name="cacheSeconds" value="120"/>
</bean>
2.3.为处理器适配器添加校验器
<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
3. 创建ProductValidationMessages.properties配置文件
user.name.length.error=请输入1-10个字符的用户名称
user.password.input.error=请输入正确的密码
4. 添加校验注解信息
public class User {
@Size(min=1,max=5,message="{user.name.length.error}" )
private String username;
@NotEmpty(message="{user.password.input.error}")
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
}
5. 在Controller类中加入校验器
@Controller
public class UserController {
@RequestMapping("userLogin.action")
public String userLogin(Model model,@Validated(value=UserGroup2.class) User user,BindingResult bindingResult){
List<ObjectError> allErrors = null;
if(bindingResult.hasErrors()){
allErrors = bindingResult.getAllErrors();
for(ObjectError error:allErrors){
System.out.println(error.getDefaultMessage());
}
return "index";
}
System.out.println(user);
model.addAttribute("user", user);
return "user";
}
}
标签:user 用户 创建 str port not framework prope ogg
原文地址:https://www.cnblogs.com/lihaitao33/p/8908518.html