JAX-RS资源中的IBM Websphere 8.5 bean验证问题

这是我使用的代码示例:

@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

changquan71 回答:JAX-RS资源中的IBM Websphere 8.5 bean验证问题

JAX-RS 1.1不会自动与Bean验证集成,因此您将需要执行自己的验证(如您在第二个示例中所做的那样)。

JAX-RS 2.0(在WebSphere v9中可用)或2.1(在WebSphere Liberty中可用)都支持与bean验证的自动集成。您可以在this post上找到更多信息。

希望这会有所帮助,安迪

本文链接:https://www.f2er.com/2682749.html

大家都在问