这是我使用的代码示例:
@Stateless
@Path("/rest")
public class MyResouce{
@POST
@Path("/test")
public Response test(@Valid Test t){
return Response.ok().build();
}
}
public class Test {
@Size(max = 3)
private String val;
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
}
我传递无效的对象(val的长度大于3)时期望ValidationException,但不会发生异常。当我注入验证器并以编程方式进行验证时:
@Path("/rest")
public class MyResouce{
@Resource
private Validator validator;
@POST
@Path("/test")
public Response test(@Valid Test t){
Set<ConstraintViolation<Test>> violations = validator.validate(t); // size = 1, means t object is invalid
return Response.ok().build();
}
}
验证的结果具有1 ConstraintViolation项,这意味着该对象无效,并且看起来@Valid注释已被忽略。如何以编程方式验证对象?这是我的validation.xml描述符:
<?xml version="1.0" encoding="UTF-8"?>
<validation-config
xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration validation-configuration-1.0.xsd">
</validation-config>
Websphere版本8.5.5.11,JAX-RS 1.1
JAX-RS 1.1不会自动与Bean验证集成,因此您将需要执行自己的验证(如您在第二个示例中所做的一样。
JAX-RS 2.0(在WebSphere v9中可用)或2.1(在WebSphere Liberty中可用)都支持与bean验证的自动集成。您可以在this post中找到更多信息。
希望这会有所帮助,安迪