我正在创建一个带有轴的Web服务。我正在使用SAAJ,JAXB和Servlet。我可以正确地使用JAXB编组和解组一个类。但是,如何将SAAJ和JAXB一起用于SOAP通信。我想用SAAJ将JAXB转换的xml文本放到SOAP BODY标签中。我怎样才能做到这一点?我阅读了Oracle网站上的SAAJ文档,但这是无法理解的。他们讲的如此复杂。
您可以执行以下操作:
演示版
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());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句