首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >加入SAAJ和JAXB

加入SAAJ和JAXB
EN

Stack Overflow用户
提问于 2013-08-02 11:23:54
回答 1查看 5.7K关注 0票数 9

我正在创建一个带有轴的web服务。我使用的是SAAJ、JAXB和Servlet。我可以正确地使用JAXB的一个类马歇尔和unmarshall。但是如何将SAAJ和JAXB一起用于SOAP通信。我希望将JAXB转换的xml文本与SAAJ一起放入SOAP标记。我该怎么做?我读过Oracle网站上的SAAJ文档,但这是不能理解的。他们说的太复杂了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-08-02 13:26:26

你可以这样做:

Demo

SOAPBody实现了JAXB,因此您可以让JAXB实现封送:

代码语言:javascript
复制
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模型:

代码语言:javascript
复制
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;
    }

}

输出

下面是运行演示代码的输出(为了便于阅读,我在我的答案中对其进行了格式化)。

代码语言:javascript
复制
<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)。

代码语言:javascript
复制
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());
    }

}
票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18015699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档