spring mvc 数据校验(bean实体注解实现)

spring mvc 数据校验

1.添加个jar (jar与一版本会冲突)

<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>

 

2.配置springmvc.xml

<!-- 配置springMVC数据校验 -->
<mvc:annotation-driven validator="validator"/>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
</bean>

3.测试,注解用法,(@Valid,BindingResult,@pattern regexp) (课时3:29分)

 

@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public ResultMessage login(@Valid Login login,BindingResult errorResult){
boolean flag= errorResult.hasErrors();
String sb = "";
if(flag) {
List<FieldError> errorList = errorResult.getFieldErrors();
for(FieldError fieldError: errorList) {
//String field = fieldError.getField();
String fieldErrorMessage=fieldError.getDefaultMessage();
sb=fieldErrorMessage+",";
}
return Utils.renderResultMessageError(sb);
}

@Valid Bean

BindingResult errorResult

/**
* @Eamil(message="对不起邮箱输入有误")
* @Pattern(regexp="[\\u4e00-\\u9fa5]{4,10}",message="名称必须是4-10位的汉字")
* @Max(value=100,message="")
* @Min(value=1,message="")
*/

/**
* 登录名
*/
@NotNull(message="不能为Null")
@NotBlank(message="不能为空格")
@NotEmpty(message="不能为空")
@Pattern(regexp="[\\w{2,10}]",message="输入的登录名有误2-10位,请重新输入")
private String loginId;

/**
* 密码
*/
@NotNull(message="不能为Null")
@NotBlank(message="不能为空格")
@NotEmpty(message="不能为空")
@Pattern(regexp="[\\w{3,6}]",message="密码必须为3-6数字或字母或下划线的组合")
private String pass;

posted @ 2018-08-17 12:51  A汉克先生  阅读(604)  评论(0编辑  收藏  举报