Java实现SOAP协议

Java实现SOAP协议Java 实现 SOAP 协议 nbsp SOAP 是把基于 HTTP 的 WEB 技术与 XML 的灵活性和可扩展性组合在了一起 准备 1 准备一个 webserver Tomcat 下载地址 http tomcat apache org 本例使用版本 apache tomcat 7 0 54 windows x64 zip2 写一个 servletsend 用来

SOAP是把基于HTTP的WEB技术与XML的灵活性和可扩展性组合在了一起。

准备:

1. 准备一个web server。Tomcat 下载地址 http://tomcat.apache.org/

本例使用版本 apache-tomcat-7.0.54-windows-x64.zip

2. 写一个servlet send用来发送一个SOAP的message并添加一个附件。

3. 写一个servlet receive用来做SOAP message的解析并返回一个response。

4. 写一个简单的html页面触发 servlet A。

 

开发工具:

eclipse 版本 eclipse-jee-juno-SR2-win32-x86_64

下载地址:

http://www.eclipse.org/downloads/

下载J2EE版本的eclipse里面包含了SOAP常用的一些jar,但这个版本的没有jaxm-api.jar,这个需要额外下载

然后倒入。

代码结构:


Java实现SOAP协议
 

web.xml代码如下:

Xml代码  
收藏代码


  1. xml version=“1.0” encoding=“ISO-8859-1”?>  
  2.   
  3.     PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN”  
  4.     “http://java.sun.com/j2ee/dtds/web-app_2_2.dtd”>  
  5.   
  6. <web-app>  
  7.     <servlet>  
  8.         <servlet-name>DemoSend
    servlet-name>  
  9.         <servlet-class>cody.soap.demo.DemoSend
    servlet-class>  
  10.     
    servlet>  
  11.   
  12.     <servlet>  
  13.         <servlet-name>DemoReceiver
    servlet-name>  
  14.         <servlet-class>cody.soap.demo.DemoReceiver
    servlet-class>  
  15.     
    servlet>  
  16.   
  17.     <servlet-mapping>  
  18.         <servlet-name>DemoSend
    servlet-name>  
  19.         <url-pattern>/DemoSend
    url-pattern>  
  20.     
    servlet-mapping>  
  21.   
  22.     <servlet-mapping>  
  23.         <servlet-name>DemoReceiver
    servlet-name>  
  24.         <url-pattern>/DemoReceiver
    url-pattern>  
  25.     
    servlet-mapping>  

  26. web-app>  

 DemoSend.java

Java代码  
收藏代码

  1. package cody.soap.demo;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.OutputStream;  
  6. import java.net.URL;  
  7.   
  8. import javax.activation.DataHandler;  
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13. import javax.xml.soap.AttachmentPart;  
  14. import javax.xml.soap.MessageFactory;  
  15. import javax.xml.soap.SOAPBody;  
  16. import javax.xml.soap.SOAPConnection;  
  17. import javax.xml.soap.SOAPConnectionFactory;  
  18. import javax.xml.soap.SOAPEnvelope;  
  19. import javax.xml.soap.SOAPException;  
  20. import javax.xml.soap.SOAPHeader;  
  21. import javax.xml.soap.SOAPMessage;  
  22. import javax.xml.soap.SOAPPart;  
  23.   
  24. public class DemoSend extends HttpServlet {  
  25.   
  26.     / 
  27.      *  
  28.      */  
  29.     private static final long serialVersionUID = 1L;  
  30.   
  31.     private SOAPConnection connection;  
  32.     @Override  
  33.     public void init() throws ServletException {  
  34.         super.init();  
  35.         try {  
  36.             SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();  
  37.             connection = connectionFactory.createConnection();  
  38.         } catch (UnsupportedOperationException e) {  
  39.             e.printStackTrace();  
  40.         } catch (SOAPException e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.     }  
  44.   
  45.     @Override  
  46.     protected void doGet(HttpServletRequest request, HttpServletResponse response)  
  47.             throws ServletException, IOException {  
  48.         String outString =

    Sending and reading the SOAP Message

    “;  

  49.         try {  
  50.             MessageFactory messageFactory = MessageFactory.newInstance();  
  51.             SOAPMessage outgoingMessage = messageFactory.createMessage();  
  52.             SOAPPart soappart = outgoingMessage.getSOAPPart();  
  53.             SOAPEnvelope envelope = soappart.getEnvelope();  
  54.             SOAPHeader header = envelope.getHeader();  
  55.             SOAPBody body = envelope.getBody();  
  56.               
  57.             body.addBodyElement(envelope.createName(“numberAvailable”“laptops”“http://ecodl.taobao.com/”)).addTextNode(“216”);  
  58.               
  59.             StringBuffer serverUrl = new StringBuffer();  
  60.             serverUrl.append(request.getScheme()).append(“://”).append(request.getServerName());  
  61.             serverUrl.append(“:”).append(request.getServerPort()).append(request.getContextPath());  
  62.             String baseUrl = serverUrl.toString();  
  63.             URL url = new URL(baseUrl + “/test.html”);  
  64.               
  65.             AttachmentPart attachmentpart = outgoingMessage.createAttachmentPart(new DataHandler(url));  
  66.             attachmentpart.setContentType(“text/html”);  
  67.             outgoingMessage.addAttachmentPart(attachmentpart);  
  68.               
  69.             URL client = new URL(baseUrl + “/DemoReceiver”);  
  70.               
  71.             FileOutputStream outgoingFile = new FileOutputStream(“out.msg”);  
  72.             outgoingMessage.writeTo(outgoingFile);  
  73.             outgoingFile.close();  
  74.               
  75.             outString += “SOAP outgoingMessage sent (see out.msg). 

    +baseUrl+

    ;  
  76.               
  77.             SOAPMessage incomingMessage = connection.call(outgoingMessage, client);  
  78.               
  79.             if (incomingMessage != null) {  
  80.                 FileOutputStream incomingFile = new FileOutputStream(“in.msg”);  
  81.                 incomingMessage.writeTo(incomingFile);  
  82.                 incomingFile.close();  
  83.                 outString += “SOAP outgoingMessage received (see in.msg).”;  
  84.             }  
  85.         } catch (SOAPException e) {  
  86.             e.printStackTrace();  
  87.         }  
  88.           
  89.         try {  
  90.             OutputStream outputStream = response.getOutputStream();  
  91.             outputStream.write(outString.getBytes());  
  92.             outputStream.flush();  
  93.             outputStream.close();  
  94.         } catch (IOException e) {}  
  95.     }  
  96.   
  97.     @Override  
  98.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  99.             throws ServletException, IOException {  
  100.         doGet(req, resp);  
  101.     }  
  102.   
  103.       
  104. }  

 DemoReceiver.java

Java代码  
收藏代码

  1. package cody.soap.demo;  
  2.   
  3. import java.util.Iterator;  
  4.   
  5. import javax.servlet.ServletConfig;  
  6. import javax.servlet.ServletException;  
  7. import javax.xml.messaging.JAXMServlet;   
  8. import javax.xml.messaging.ReqRespListener;  
  9. import javax.xml.soap.MessageFactory;  
  10. import javax.xml.soap.SOAPBody;  
  11. import javax.xml.soap.SOAPElement;  
  12. import javax.xml.soap.SOAPEnvelope;  
  13. import javax.xml.soap.SOAPException;  
  14. import javax.xml.soap.SOAPMessage;  
  15. import javax.xml.soap.SOAPPart;  
  16.   
  17. public class DemoReceiver extends JAXMServlet implements ReqRespListener{  
  18.   
  19.     / 
  20.      * Generated automatically 
  21.      */  
  22.     private static final long serialVersionUID = 1L;  
  23.     private static MessageFactory messageFactory = null;  
  24.     @Override  
  25.     public void init(ServletConfig servletConfig) throws ServletException {  
  26.         super.init(servletConfig);  
  27.         try {  
  28.             messageFactory = MessageFactory.newInstance();  
  29.         } catch (SOAPException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  
  33.   
  34.     @Override  
  35.     public SOAPMessage onMessage(SOAPMessage msg) {  
  36.         SOAPPart soappart = msg.getSOAPPart();  
  37.         try {  
  38.             SOAPEnvelope incomingEnvelope;        
  39.             incomingEnvelope = soappart.getEnvelope();        
  40.             SOAPBody body = incomingEnvelope.getBody();  
  41.       
  42.             Iterator
     iterator = body.getChildElements(incomingEnvelope.createName(“numberAvailable”“laptops”“http://ecodl.taobao.com/”));  
  43.       
  44.             SOAPElement element;  
  45.             element = (SOAPElement) iterator.next();  
  46.       
  47.             SOAPMessage message = messageFactory.createMessage();  
  48.             SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();  
  49.       
  50.             SOAPBody responsebody = envelope.getBody();  
  51.             String responseText = “Got the SOAP message indicating there are “ + element.getValue() + ” laptops available.”;  
  52.             responsebody.addChildElement(envelope.createName(“Response”)).addTextNode(responseText);  
  53.       
  54.             return message;  
  55.         } catch (SOAPException e) {  
  56.             e.printStackTrace();  
  57.             return null;  
  58.         }  
  59.     }  
  60.   
  61. }  

 test.xml

Html代码  
收藏代码


  1. xml version=“1.0” encoding=“UTF-8” ?>  
  2. >  
  3. <HTML>  
  4.     <HEAD>  
  5.         <TITLE>SOAP and Java
    TITLE>  
  6.     
    HEAD>  
  7.   
  8.     <BODY>  
  9.         <H1>SOAP and Java
    H1>  
  10.            Click <A HREF=“DemoSend”>here
    a> to send the SOAP message.  
  11.     
    BODY>  

  12. HTML>  

out.msg

Xml代码  
收藏代码

  1. ——=_Part_0_.84  
  2. Content-Type: text/xml; charset=utf-8  
  3.   
  4. <SOAP-ENV:Envelope xmlns:SOAP-ENV=“http://schemas.xmlsoap.org/soap/envelope/”>  
  5. <SOAP-ENV:Header/>  
  6. <SOAP-ENV:Body>  
  7. <laptops:numberAvailable xmlns:laptops=“http://ecodl.taobao.com/”>216
    laptops:numberAvailable>  

  8. SOAP-ENV:Body>  

  9. SOAP-ENV:Envelope>  
  10. ——=_Part_0_.84  
  11. Content-Type: text/html  
  12.   

  13. xml version=“1.0” encoding=“UTF-8” ?>  
  14. >  
  15. <HTML>  
  16.     <HEAD>  
  17.         <TITLE>SOAP and Java
    TITLE>  
  18.     
    HEAD>  
  19.   
  20.     <BODY>  
  21.         <H1>SOAP and Java
    H1>  
  22.            Click <A HREF=“DemoSend”>here
    a> to send the SOAP message.  
  23.     
    BODY>  

  24. HTML>  
  25.   
  26. ——=_Part_0_.84–  

 

in.msg

Xml代码  
收藏代码

  1. <SOAP-ENV:Envelope xmlns:SOAP-ENV=“http://schemas.xmlsoap.org/soap/envelope/”>  
  2. <SOAP-ENV:Header/>  
  3. <SOAP-ENV:Body>  
  4. <Response>Got the SOAP message indicating there are 216 laptops available.  

  5. Response>  

  6. SOAP-ENV:Body>  

  7. SOAP-ENV:Envelope>  

原文:http://www.informit.com/library/content.aspx?b=STY_XML_21days&seqNum=228

在Tomcat上部署的目录结构:

webapps [This is a directory]
|____soapdemoserver [This is a directory]
     |____test.html [Our starting Web page]
     |____WEB-INF [This is a directory]
          |____web.xml [Configures Tomcat]
          |____classes [This is a directory]
               |____cody/soap/demo [This is a directory]
                    |____DemoReceiver.class [The server servlet]
                    |____DemoSend.class [The client servlet]


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/223666.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午1:41
下一篇 2026年3月17日 下午1:41


相关推荐

  • Transformer模型详解

    Transformer模型详解转载请注明出处,原文地址简介AttentionIsAllYouNeed是一篇Google提出的将Attention思想发挥到极致的论文。这篇论文中提出一个全新的模型,叫Transformer,抛弃了以往深度学习任务里面使用到的CNN和RNN,目前大热的Bert就是基于Transformer构建的,这个模型广泛应用于NLP领域,例如机器翻译,问答系统,文本摘要和语音识别等等方向…

    2022年5月15日
    37
  • Java内存管理

    Java内存管理

    2020年11月12日
    202
  • 访问数据库使用redis作为mysql的缓存(redis和mysql结合)

    访问数据库使用redis作为mysql的缓存(redis和mysql结合)首先声明一下,我是在一个SSM项目的基础上进行优化的,所以就不进行基础的介绍了。下面我也补充一些知识点:redis:内存型数据库,有持久化功能,具备分布式特性,可靠性高,适用于对读写效率要求都很高,数据处理业务复杂和对安全性要求较高的系统(如新浪微博的计数和微博发布部分系统,对数据安全性、读写要求都很高)。缓存机制说明:所有的查询结果都放进了缓存,也就是把MySQL查询的结果放…

    2022年6月17日
    38
  • linux中的 slab/slob/slub

    linux中的 slab/slob/slub很久很久以 bai 前 一个叫做 MarkHemment 的哥儿们 du 写了 Slab 在接下来的一些年里 zhi 其他人对 Slab 进行了完善 dao 一年半以前 SLOB 问世了 SLOB 的目标是针对嵌入式系统的 主要是适用于那些内存非常有限的系统 比如 32MB 以下的内存 它不太注重 largesmp 系统 虽然最近在这方面有一些小的改进 几个月之前 SLUB 闪亮登场 它基本上属于对 Slab 的重设计 redesign 但是代码更少 并且能更好的适应 largeNUMA 系统 SLUB 被很认为是 Slab 和 Slob 的取代者 大

    2026年3月19日
    2
  • 前端工程配置Nginx反向代理[通俗易懂]

    前端工程配置Nginx反向代理HTTP配置HTTPS配置配置两个反向代理,一个代理http页面,一个代理https页面,前者监听80端口,后者监听443端口。配置后整个文件如下,其中有不少冗余,挑有用的看即可。#user nobody;worker_processes 1;#error_log logs/error.log;#error_log logs/error.log notice;#error_log logs/error.log info;#pid

    2022年3月11日
    47
  • java时间计数_java计算方法耗时

    java时间计数_java计算方法耗时java时间计数

    2022年4月20日
    51

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号