java-在Spring WS中将自定义元素添加到SOAP标头
作者:互联网
我正在使用带有JAXB绑定的Spring WS对Web服务客户端应用程序进行编码.
我正在使用的服务需要通过SOAP标头(以及另一个自定义标头)中的wsse:security元素进行身份验证.我已经编译了所有必要的模式,包括将wsse.xsd编译为
org.xmlsoap.schemas.ws._2002._12.secext.Security.
但是我找不到将这种或任何其他元素插入SOAP标头中的方法.我知道我可以使用拦截器或SoapActionCallbacks,但是它们允许我做的是手动构造标头并通过((SaajSoapMessage)webServiceMessage).getSoapHeader().addHeaderElement(qName)将其添加到标头部分.但是我不想手动构建此标头,因为我有一个可以轻松编组的对应类.
我的问题-在Spring WS中调用Web服务调用时,是否可以将对象插入SOAP头(或信封的其他部分)中?
我使用Apache CXF和Axis2来使用Web服务,这从来都不是问题-框架只是在幕后为我(通常是通过服务存根机制)为我做的.
解决方法:
我已经设法解决了这个问题,感谢@GPI的提示.我对Spring WS和javax.xml.还是相当陌生的,所以我无法确定这是正确的方法还是优雅的方法,但它确实满足我的要求.
这段代码基于我通过JAXB从XSD架构生成的对象,将自定义标头元素添加到< SOAP-ENV:Header>.我不知道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();
}
}
}
然后,我在服务调用期间仅将HeaderComposedCallback对象传递给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();
}
}
标签:spring-ws,web-services,spring,java,soap 来源: https://codeday.me/bug/20191121/2051337.html