2

我有一个用 jaxb 和 spring webservice 构建的 java web 服务应用程序。

我在 xsd 中有一个复杂的类型,如下所示:

...

<complexType name="GetRecordsRequest">
    <sequence>
        <element name="maxRecords" type="int" maxOccurs="1" minOccurs="1"/>
    </sequence>
</complexType>

...

使用xjc,我得到了从 xsd 生成的 jaxb 类:

public class GetRecordsRequest {
    protected int maxRecords;

    public int getMaxRecords() {
        return maxRecords;
    }

    public void setMaxRecords(int value) {
        this.maxRecords = value;
    }
}

我在 spring context.xml 中使用了 PayloadValidatingInterceptor来确保用户不能为 maxRecords 输入除整数以外的任何内容:

<bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">
    <property name="interceptors">
        <list>
            <ref local="validatingInterceptor" />
        </list>
    </property>
</bean>

<bean id="validatingInterceptor" class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
    <property name="schema" value="/WEB-INF/schemas/webservice.xsd" />
    <property name="validateRequest" value="true" />
    <property name="validateResponse" value="true" />
</bean>

当我在 Soap UI 中输入这个肥皂请求 xml 时:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.test.com/ns1">
   <soapenv:Header/>
   <soapenv:Body>
      <ns1:GetRecordsRequest>
         <ns1:maxRecords></ns1:maxRecords>
      </ns1:GetRecordsRequest>
   </soapenv:Body>
</soapenv:Envelope>

我得到的回复信息是:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <SOAP-ENV:Fault>
         <faultcode>SOAP-ENV:Client</faultcode>
         <faultstring xml:lang="en">Validation error</faultstring>
         <detail>
            <spring-ws:ValidationError xmlns:spring-ws="http://springframework.org/spring-ws">cvc-datatype-valid.1.2.1: '' is not a valid value for 'integer'.</spring-ws:ValidationError>
            <spring-ws:ValidationError xmlns:spring-ws="http://springframework.org/spring-ws">cvc-type.3.1.3: The value '' of element 'cis:maxRecords' is not valid.</spring-ws:ValidationError>
         </detail>
      </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

您可以看到结果是仅针对一个字段的两行神秘消息。我可以通过只写一行来使响应消息更漂亮吗?有没有办法自定义验证错误响应消息?

4

2 回答 2

2

您可以使用AbstractValidatingInterceptor(PayloadValidatingInterceptor 是这个抽象类的实现)的方法来自定义验证错误响应,即:

  • setDetailElementName(QName detailElementName)
  • setFaultStringOrReason(String faultStringOrReason)

部分示例:

public final class MyPayloadValidatingInterceptor
extends PayloadValidatingInterceptor {

    @Override
    protected Source getValidationRequestSource(WebServiceMessage webSerMessage_) {
        _source = webSerMessage_.getPayloadSource();
        validateSchema(_source);
        return _source;
    }

    private void validateSchema(Source source_) throws Exception {
        SchemaFactory _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema _schema = _schemaFactory.newSchema(getSchemas()[0].getFile());

        Validator _validator = _schema.newValidator();
        DOMResult _result = new DOMResult();
        try {
            _validator.validate(source_, _result);
        } catch (SAXException _exception) {
            // modify your soapfault here                
        }
    }
}
于 2013-04-01T13:08:47.207 回答
2

您可以通过扩展 PayloadValidatingInterceptor 并覆盖 handleRequestValidationErrors 来自定义验证错误消息。我们可以在 messageContext 的正文中设置自定义错误消息。

1) 代替请求验证错误的 SOAP 错误,您可以返回带有验证错误消息的自定义 xml 响应。

2) SAXParseException[] 错误包含请求验证错误。您可以选择仅返回一个错误作为响应。(或) 对于某些预定义的错误,您可以返回自定义错误消息,而不是 SAXParseException 中返回的错误消息。

/**
* The Class CustomValidatingInterceptor.
*/
public class CustomValidatingInterceptor extends PayloadValidatingInterceptor{

/* (non-Javadoc)
 * @see org.springframework.ws.soap.server.endpoint.interceptor.AbstractFaultCreatingValidatingInterceptor#handleRequestValidationErrors(org.springframework.ws.context.MessageContext, org.xml.sax.SAXParseException[])
 */
@Override
protected boolean handleRequestValidationErrors(MessageContext messageContext, SAXParseException[] errors) throws TransformerException {
    JAXBContext jaxbContext;
    StringWriter stringWriter = new StringWriter();
    ResponseTransactionDetail transactionDetail = null;

    for (SAXParseException error : errors) {
        logger.debug("XML validation error on request: " + error.getMessage());
    }
    if (messageContext.getResponse() instanceof SoapMessage) {

        /**
         * Get SOAP response body in message context (SOAP Fault)
         */

        SaajSoapMessage soapMessage = (SaajSoapMessage)messageContext.getResponse();
        SoapBody body = soapMessage.getSoapBody();

        // marshal custom error response to stringWriter

        /**
        * Transform body
        */
        Source source = new StreamSource(new StringReader(stringWriter.toString()));
        identityTransform.transform(source, body.getPayloadResult());
        stringWriter.close();
    }
    return false;
}
于 2015-11-05T04:11:18.960 回答