且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 CXF Web 服务进行服务器端 XML 验证

更新时间:2023-10-01 14:07:28

您可以使用自定义 ValidationEventHandler 覆盖验证错误消息,插入行号:

You can override validation error messages, inserting a line number, by using a custom ValidationEventHandler:

package example;

import javax.xml.bind.ValidationEvent;
import javax.xml.bind.helpers.DefaultValidationEventHandler;

public class MyValidationEventHandler extends DefaultValidationEventHandler {    
    @Override
    public boolean handleEvent(ValidationEvent event) {
        if (event.getSeverity() == ValidationEvent.WARNING) {
            return super.handleEvent(event);
        } else {
            throw new RuntimeException(event.getMessage()
                + " [line:"+event.getLocator().getLineNumber()+"]");
        }
    }
}

如果您将端点配置为使用此处理程序:

If you configure your endpoint to use this handler:

<jaxws:endpoint id="someEndpoint" implementor="#someImpl" address="/impl">
    <jaxws:properties>
        <entry key="schema-validation-enabled" value="true" />
        <entry key="jaxb-validation-event-handler">
            <bean class="example.MyValidationEventHandler" />
        </entry>
    </jaxws:properties>
</jaxws:endpoint>

然后你会得到如下所示的 SOAP 错误:

Then you will get SOAP faults that look like this:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <soap:Fault>
            <faultcode>soap:Client</faultcode>
            <faultstring>Unmarshalling Error: Not a number: xyz [line: 6]</faultstring>
        </soap:Fault>
    </soap:Body>
</soap:Envelope>

jaxb-validation-event-handler 属性最近才添加到 CXF,因此您需要确保使用的是最新版本 - 我在 2.2.5 中对此进行了测试.

The jaxb-validation-event-handler property was only added to CXF pretty recently, so you need to make sure you're using the latest version - I tested this with 2.2.5.