Kev*_*ave 3 java error-handling binding ejb resteasy
假设我使用传递给REST调用的参数定义POJO
class MyVO {
@NotNull
@PathParam("name")
private String name;
@NotNull
@PathParam("age")
private Integer age;
// getters and setters
}
public class RESTclass {
public postData( @Form MyVO vo ) {
}
}
Run Code Online (Sandbox Code Playgroud)
它会自动绑定MyVO中的对象.但是我在哪里得到验证错误?它是否在绑定期间触发验证?如果没有,如何触发验证?
Spring做得很好.它有BindingResult参数,你可以注入.这里的等价物是什么?
任何的想法?
gre*_*ker 13
对于bean验证1.0,Resteasy有一个自定义验证提供程序,它使用hibernate的bean验证器实现.
要在Resteasy中启动并运行验证,您需要执行以下操作:
将resteasy-hibernatevalidator-provider依赖项添加到项目中.如果您使用maven,这是maven pom条目:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-hibernatevalidator-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)使用注释对要进行验证的资源类进行@ValidateRequest注释.
@Named
@Path("/users")
@ValidateRequest
public class UserResource extends BaseResource
{
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response createUser(@Valid User user)
{
//Do Something Here
}
}
Run Code Online (Sandbox Code Playgroud)
Resteasy将自动检测HibernateValidatorAdapter类路径并开始调用bean验证.
创建一个ExceptionMapper<MethodConstraintViolationException>实现来处理验证错误.
与在Spring中你必须检查BindingResult不同,当在Resteasy中遇到验证错误时,hibernate验证器会抛出一个MethodConstraintViolationException.在MethodConstraintViolationException将包含其中的所有验证错误的.
@Provider
public class MethodConstraintViolationExceptionMapper extends MyBaseExceptionMapper
implements ExceptionMapper<MethodConstraintViolationException>
{
@Override
public Response toResponse(MethodConstraintViolationException exception)
{
//Do Something with the errors here and create a response.
}
}
Run Code Online (Sandbox Code Playgroud)最新版本的Resteasy现在支持bean验证规范1.1并且已经改变了抛出的api和异常.
而不是resteasy-hibernatevalidator-provider你将需要resteasy-validator-provider-11依赖.
您不需要添加@ValidateRequest到资源类,因为默认情况下启用了验证测试
resteasy-validator-provider-11.
MethodConstraintViolationException检测到违规的时候不会抛出,而是抛出一个实例RESTEasyViolationException
.
文档: 3.0.1.最终验证文档
| 归档时间: |
|
| 查看次数: |
3718 次 |
| 最近记录: |