使用Hibernate_Validator进行数据校验,好处不言而喻:规范统一,低耦合度。
1、pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency> <dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-validator-provider-11</artifactId>
<version>3.0.9.Final</version>
</dependency>
2、添加约束注解,目标元素可以是字段(变量)、属性(getter方法)或者类型等
在需要进行校验的变量或者属性(domain里面的)添加约束注解
UserService.java
@Path("UserService")
public class UserService { @Size(min = 2, max = 4)
@PathParam("s")
String s; @POST
@Path("{s}/user")
@Produces("application/json;charset=UTF-8")
public String adduser(@Valid User user) {
//System.out.print(VALIDATION_HEADER);
return user.getEmail();
}
}
User.java
@XmlRootElement(name = "User")
public class User { @NotNull
@Pattern(regexp="[0-9]+",message="id必须为数字")
@Size(min = 2, max = 4)
private String name; private String pwd; @Email
private String email;
getset略
}
3、捕获检验异常和message并输出
resteasy框架为api的异常处理,提供了一个统一的接口,ExceptionMapper<Exception>,我们可以定义一个handler来实现这个接口,就可以捕获resteasy api的异常。如下面的代码:
ValidationExceptionHandlerREST.java
@Provider
public class ValidationExceptionHandlerREST implements ExceptionMapper<ResteasyViolationException >
{ @Override
public Response toResponse(ResteasyViolationException exception)
{
//获取校验失败的反馈信息
Map<String, String> violations = new HashMap<String, String>(); for (ResteasyConstraintViolation violation : exception.getViolations()) {
violations.put(violation.getPath(), violation.getMessage());
}
System.out.print("Violation error");
return Response.status(Status.BAD_REQUEST).entity(violations).build();
}
}
另外我们需要使用此handler,所以我们在web.xml中启用它。如下面的配置:
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>cn.itcast.ValidatorException.ValidationExceptionHandlerREST</param-value>
</context-param>
4、最后
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>cn.itcast.service.test,cn.itcast.service.UserService</param-value>
</context-param>
5、测试
源码下载