我正在使用带有JAXB绑定的Spring WS对Web服务客户端应用程序进行编码。我正在使用的服务需要通过SOAP标头(以及另一个自定义标头)中的wsse:security元素进行身份验证。我已经编译了所有必需的模式,包括wsse.xsd
编译为org.xmlsoap.schemas.ws._2002._12.secext.Security
。
但是我找不到将这种或任何其他元素插入SOAP标头中的方法。我知道我可以使用拦截器或SoapActionCallback
s,但是它们允许我做的是手动构造标头,然后通过((SaajSoapMessage)webServiceMessage).getSoapHeader().addHeaderElement(qName)
诸如此类将其添加到标头部分。但是我不想手动构建此标头,因为我有一个可以轻松编组的对应类。
我的问题-在Spring WS中调用Web服务调用时,是否可以将对象插入SOAP头(或信封的其他部分)中?我使用Apache CXF和Axis2来使用Web服务,但这从来都不是问题-框架只是在幕后为我(通常是通过服务存根机制)为我做的。
我已经设法解决了这个问题,感谢@GPI的提示。我对Spring WS和javax.xml。还是相当陌生,所以我无法确定这是正确的方法还是优雅的方法,但它确实满足我的要求。
这段代码<SOAP-ENV:Header>
基于我通过JAXB从XSD架构生成的对象,向中添加了自定义标头元素。我不知道Transformer如何知道我要将这些元素放置在哪里,但是它正确地将它们放置在Header部分中。
public class HeaderComposingCallback implements WebServiceMessageCallback {
private final String action;
public HeaderComposingCallback( String action ) {
this.action = action;
}
@Override
public void doWithMessage(WebServiceMessage webServiceMessage) throws IOException, TransformerException {
SoapHeader soapHeader = ((SoapMessage)webServiceMessage).getSoapHeader();
try {
JAXBContext context = JAXBContext.newInstance( MessageHeader.class, Security.class );
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document securityDocument = builder.newDocument();
Document headerDocument = builder.newDocument();
Marshaller marshaller = context.createMarshaller();
marshaller.marshal( HeaderFactory.getHeader( action ), headerDocument );
marshaller.marshal( SecurityFactory.getSecurity(), securityDocument );
Transformer t = TransformerFactory.newInstance().newTransformer();
DOMSource headerSource = new DOMSource( headerDocument );
DOMSource securitySource = new DOMSource( securityDocument );
t.transform( headerSource, soapHeader.getResult() );
t.transform( securitySource, soapHeader.getResult() );
} catch (JAXBException | ParserConfigurationException e) {
e.printStackTrace();
}
}
}
然后,我只是在服务调用期间将HeaderComposingCallback
对象传递给marshalSendAndReceive()
方法。
编辑(在Arjen评论后)
阿延的权利。我想做的事情可以更简单地实现。现在我的doWithMessage
方法如下:
@Override
public void doWithMessage(WebServiceMessage webServiceMessage) throws IOException, TransformerException {
SoapHeader soapHeader = ((SoapMessage)webServiceMessage).getSoapHeader();
try {
JAXBContext context = JAXBContext.newInstance( MessageHeader.class, Security.class );
Marshaller marshaller = context.createMarshaller();
marshaller.marshal( header, soapHeader.getResult() );
marshaller.marshal( security, soapHeader.getResult() );
} catch (JAXBException e) {
e.printStackTrace();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句