我正在创建一个带有轴的Web服务。我使用的是SAAJ,JAXB和Servlet。我可以正确地使用JAXB对一个班级进行编组和解组。但是我如何一起使用SAAJ和JAXB进行SOAP通信。我想把JAXB转换的xml文本放到带有SAAJ的SOAP BODY标签中。我怎样才能做到这一点?我阅读了Oracle网站上的SAAJ文档,但这是不可理解的。他们说得太复杂了。
答案 0 :(得分:19)
您可以执行以下操作:
<强>演示强>
SOAPBody
实现了org.w3c.dom.Node
,因此你可以让你的JAXB实现编组:
import javax.xml.bind.*;
import javax.xml.soap.*;
public class Demo {
public static void main(String[] args) throws Exception {
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage message = mf.createMessage();
SOAPBody body = message.getSOAPBody();
Foo foo = new Foo();
foo.setBar("Hello World");
JAXBContext jc = JAXBContext.newInstance(Foo.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(foo, body);
message.saveChanges();
message.writeTo(System.out);
}
}
Java模型(Foo)
下面是我们将用于此示例的简单Java模型:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Foo {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
<强>输出强>
以下是运行演示代码的输出(我已将其格式化为我的答案,以便于阅读)。
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header />
<SOAP-ENV:Body>
<foo>
<bar>Hello World</bar>
</foo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
<强>更新强>
以下是使用JAXB和JAX-WS API的示例(有关服务的详细信息,请参阅:http://blog.bdoughan.com/2013/02/leveraging-moxy-in-your-web-service-via.html)。
import javax.xml.bind.JAXBContext;
import javax.xml.namespace.QName;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;
import blog.jaxws.provider.*;
public class Demo {
public static void main(String[] args) throws Exception {
QName serviceName = new QName("http://service.jaxws.blog/", "FindCustomerService");
Service service = Service.create(serviceName);
QName portQName = new QName("http://example.org", "SimplePort");
service.addPort(portQName, SOAPBinding.SOAP11HTTP_BINDING, "http://localhost:8080/Provider/FindCustomerService?wsdl");
JAXBContext jc = JAXBContext.newInstance(FindCustomerRequest.class, FindCustomerResponse.class);
Dispatch<Object> sourceDispatch = service.createDispatch(portQName, jc, Service.Mode.PAYLOAD);
FindCustomerRequest request = new FindCustomerRequest();
FindCustomerResponse response = (FindCustomerResponse) sourceDispatch.invoke(request);
System.out.println(response.getValue().getFirstName());
}
}