我有一个使用 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 端点类方法中得到 maxRecords 的值为 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/