1.导包
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
2.配置
<mvc:annotation-driven validator="validator" />
<!-- 配置资源文件 -->
<bean id="hibernateMessages" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="basenames">
<list>
<value>ValidationMessages</value>
</list>
</property>
</bean>
<!-- 配置验证器 -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
<property name="validationMessageSource" ref="hibernateMessages"></property>
</bean>
<!-- 如果要在控制器方法的参数上直接使用验证注解进行修饰,需要该配置 -->
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>
3.设置验证器(validator = "validator")
<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
4.异常注解的使用
@Validated 如果要在方法的参数上使用验证注解,需要在控制器类中使用该注解
@Controller
@Validated
public class LoginController {
@Autowired(required = false)
private LoginService loginService;
@RequestMapping("/login.do")
@ResponseBody
public JsonResult login(@NotEmpty(message = "用户名不能为空") String username, @Size(min=3,max = 12,message = "密码长度不符合要求") String password, HttpSession session) {
Map<String, String> map = new HashMap<>();
map.put("username",username);
map.put("password", password);
Admin admin = loginService.login(map);
admin.getUsername();
session.setAttribute("admin", admin);
JsonResult jsonResult = new JsonResult(0, null);
return jsonResult;
}
}
5.异常捕获
在方法参数上使用验证注解,报异常是try-catch无法捕获到异常,需要自定义一个,此处定义的是一个全局的异常处理类
// 全局的异常处理类
// 控制器的增强
@ControllerAdvice // 该注解也需要扫描
@ResponseBody // 修饰类,类中的所有方法,相当于都使用该注解修饰
public class CommonException {
@ExceptionHandler(ConstraintViolationException.class)
// @ResponseBody
public JsonResult constraintViolationException(ConstraintViolationException ex){
// 验证不通过的信息
Iterator<ConstraintViolation<?>>
iterator = ex.getConstraintViolations().iterator();
String message = null;
if (iterator.hasNext()) {
message = iterator.next().getMessage();
System.out.println(message);
}
return new JsonResult(1, "验证异常");
}
// 处理那些没有预料到的异常
@ExceptionHandler
// @ResponseBody
public JsonResult commonException(Exception ex){
return new JsonResult(1, ex.getMessage());
}
}
6.注解扫描(@ControllerAdvice 该注解需要扫描)
自定义的CommonException在common包下
<context:component-scan base-package="com.sjm.controller,com.sjm.common"></context:component-scan>
注:JsonResult
public class JsonResult {
private int code; // 0 正常 1 异常
private Object info; // 返回前端的数据
public JsonResult() {
}
public JsonResult(int code, Object info) {
this.code = code;
this.info = info;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getInfo() {
return info;
}
public void setInfo(Object info) {
this.info = info;
}
}