java - 当 SOAP XML 中没有输入任何值时,如何使 xsd 中的整数元素值不为零?

标签 java soap xsd jaxb spring-ws

我有一个使用 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;
    }
}

现在,问题是如果我在来自 SoapUI 应用程序的 SOAP 请求 xml 中为 maxRecords 输入空值,如下所示:

<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>

我在 webservice 端点类方法中得到 ma​​xRecords 的值为 0。我预计应用程序会抛出错误或异常,因为我在 xsd 中设置了 minOccurs="1",我认为这意味着强制。

@PayloadRoot(namespace="http://www.test.com/ns1", localPart = "GetRecordsRequest")
public JAXBElement<GetRecordsResponse> GetRecordsRequest(JAXBElement<GetRecordsRequest> jaxbGetListMessage){
    GetRecordsRequest request = jaxbGetListMessage.getValue();

    System.out.println(request.getMaxRecords());    // print 0 value

    ...
}

我什至将 xsd 中的 minOccurs 更改为 0,因此类型变为 Integer,但 maxRecords 值仍然为 0,我预计它将为 null。

我知道的唯一方法是将 maxRecords 的类型更改为字符串或 token ,但我更喜欢是否有另一种解决方案仍然保持其整数类型。

那么,当我在soap xml中输入空值时,如何使maxRecords值为空或发生异常?

注意:我通过删除不相关的部分来简化上面的代码/xml,以使代码更易于阅读。如果您发现语法错误,请在评论部分告诉我,因为我手动输入了大部分代码。

最佳答案

我按照其他人的建议使用PayloadValidatingInterceptor,并在应用程序中添加了类似的内容。 context xml 及其工作原理:

<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>

感谢所有建议使用 PayloadValidatingInterceptor 的人。

关于java - 当 SOAP XML 中没有输入任何值时,如何使 xsd 中的整数元素值不为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15544762/

相关文章:

python - 如何使用 xmlsec(或其他更合适的包)对 XML 进行签名

java - 添加不带命名空间的 SOAP header 元素

php - 如何使用 symfony 获取完整的帖子正文?

xml - 限制 XSD 中嵌套元素的深度

java - Git Config 命令通过 java 失败。 $HOME 未设置

java - 进行 XML 转换时获取 "UTFDataFormatException: encoded string too long"

代码中出现 java.classCastException

Java BufferedWriter 导出文件/目录列表 .replaceAll 替代方案?

android - 真的有办法在 Android 上验证 XML 文档吗?

Maven Jaxb2 xjc 插件错误没有找到模式