Java实现SOAP协议 之 HelloWorld

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java实现SOAP协议 之 HelloWorld相关的知识,希望对你有一定的参考价值。

Java实现SOAP协议 之 HelloWorld

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,这个需要额外下载

然后倒入。

代码结构:


技术分享
 

web.xml代码如下:

Xml代码  技术分享
  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2.   
  3. <!DOCTYPE web-app  
  4.     PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"  
  5.     "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">  
  6.   
  7. <web-app>  
  8.     <servlet>  
  9.         <servlet-name>DemoSend</servlet-name>  
  10.         <servlet-class>cody.soap.demo.DemoSend</servlet-class>  
  11.     </servlet>  
  12.   
  13.     <servlet>  
  14.         <servlet-name>DemoReceiver</servlet-name>  
  15.         <servlet-class>cody.soap.demo.DemoReceiver</servlet-class>  
  16.     </servlet>  
  17.   
  18.     <servlet-mapping>  
  19.         <servlet-name>DemoSend</servlet-name>  
  20.         <url-pattern>/DemoSend</url-pattern>  
  21.     </servlet-mapping>  
  22.   
  23.     <servlet-mapping>  
  24.         <servlet-name>DemoReceiver</servlet-name>  
  25.         <url-pattern>/DemoReceiver</url-pattern>  
  26.     </servlet-mapping>  
  27. </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 ="<HTML><H1>Sending and reading the SOAP Message</H1><P>";  
  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). <BR>"+baseUrl+"<BR>";  
  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).</HTML>";  
  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. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <HTML>  
  4.     <HEAD>  
  5.         <TITLE>SOAP and Java</TITLE>  
  6.     </HEAD>  
  7.   
  8.     <BODY>  
  9.         <H1>SOAP and Java</H1>  
  10.            Click <HREF="DemoSend">here</a> to send the SOAP message.  
  11.     </BODY>  
  12. </HTML>  

out.msg

Xml代码  技术分享
  1. ------=_Part_0_1985246804.1403343570084  
  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_1985246804.1403343570084  
  11. Content-Type: text/html  
  12.   
  13. <?xml version="1.0" encoding="UTF-8" ?>  
  14. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  15. <HTML>  
  16.     <HEAD>  
  17.         <TITLE>SOAP and Java</TITLE>  
  18.     </HEAD>  
  19.   
  20.     <BODY>  
  21.         <H1>SOAP and Java</H1>  
  22.            Click <HREF="DemoSend">here</a> to send the SOAP message.  
  23.     </BODY>  
  24. </HTML>  
  25.   
  26. ------=_Part_0_1985246804.1403343570084--  

 

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]

以上是关于Java实现SOAP协议 之 HelloWorld的主要内容,如果未能解决你的问题,请参考以下文章

java WebService接口采用SOAP协议的调用

SOAP协议是RPC协议的升级版,出现了WSDL

ASP.NET之SOAP的发送接收与处理类

webservciescxf框架之客户端与服务端实例详解

(原创)用JAX-WS+Spring实现简单soap规范的webservice

CXF支持 SOAP1.1 SOAP1.2协议