我尝试使用Apache CXF的BeanValidation功能。现在卡住了因为没有任何线索如何处理和解析验证器抛出的异常。 我有网络服务界面:
@WebService
@SOAPBinding(style=SOAPBinding.Style.DOCUMENT, use=SOAPBinding.Use.LITERAL, parameterStyle=SOAPBinding.ParameterStyle.BARE)
public interface TestWSInterface {
@WebMethod
@WebResult(name = "helloResponse")
@Valid
public Hello.Response hello(@WebParam(name = "helloRequest") @Valid Hello.Request request) throws TestWSException;
}
Hello.Request注释:
@XmlType(name = "HelloRequest")
public static class Request extends Command.Request {
@NotNull(message = "not null required")
@Size(min = 1, max = 5, message = "[1..5] characters")
public String name;
}
在cfx-servlet.xml中进行以下配置:
<jaxws:endpoint id="testWS" implementor="#test" address="/TestWS">
<jaxws:features>
<ref bean="commonValidationFeature"/>
</jaxws:features>
</jaxws:endpoint>
<bean id="commonValidationFeature" class="org.apache.cxf.validation.BeanValidationFeature"/>
所以,然后我用SoapUI运行我的请求并传递包含例如6个字符的名字,我有以下回复:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Fault occurred while processing.</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>
所以我的主要问题是 - 如何捕获ConstraintViolationException并使用注释约束中的详细消息扩展生成的错误响应?来自Apache CXF - Bean Validation Feature的文档对我来说看起来不是很有帮助。所以我真的需要这样的例子。
答案 0 :(得分:1)
我遇到了同样的问题,我使用AbstractSoapInterceptor修复了它。 要注册自定义拦截器,您必须将以下注释添加到Web服务中。
@OutFaultInterceptors(interceptors = { "com.saqi.config.FaultInterceptor" })
之后,您必须按如下方式编写自定义FaultInterceptor。
public class FaultInterceptor extends AbstractSoapInterceptor {
public FaultInterceptor() {
super(Phase.MARSHAL);
}
@Override
public void handleMessage(SoapMessage soapMessage) throws Fault {
Fault fault = (Fault) soapMessage.getContent(Exception.class);
if (fault.getCause() != null && fault.getCause() instanceof ConstraintViolationException) {
ConstraintViolationException constraintViolationException = (ConstraintViolationException) fault.getCause();
if (!constraintViolationException.getConstraintViolations().isEmpty()) {
Set<ConstraintViolation<?>> constraintViolations = constraintViolationException
.getConstraintViolations();
for (ConstraintViolation constraintViolation : constraintViolations) {
fault.setMessage(constraintViolation.getMessage());
}
}
}
}
}
这将显示您的ConstraintViolationException消息,如下所示。
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Id should follow the pattern!</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>
注意:我使用的是cxf 3.1.6版本