我正在创建一个带有轴的web服务。我使用的是SAAJ、JAXB和Servlet。我可以正确地使用JAXB的一个类马歇尔和unmarshall。但是如何将SAAJ和JAXB一起用于SOAP通信。我希望将JAXB转换的xml文本与SAAJ一起放入SOAP标记。我该怎么做?我读过Oracle网站上的SAAJ文档,但这是不能理解的。他们说的太复杂了。
发布于 2013-08-02 13:26:26
你可以这样做:
Demo
SOAPBody实现了JAXB,因此您可以让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中使用JAXB的示例(有关服务的详细信息,请参阅: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());
}
}https://stackoverflow.com/questions/18015699
复制相似问题