gpt4 book ai didi

java - 加入 SAAJ 和 JAXB

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:39 25 4
gpt4 key购买 nike

我正在创建一个没有轴的网络服务。我正在使用 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());
}

}

关于java - 加入 SAAJ 和 JAXB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18015699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com