Java实现SOAP协议 之 HelloWorld

时间:2022-12-04 11:49:16

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

然后倒入。

代码结构:

Java实现SOAP协议 之 HelloWorld

web.xml代码如下:

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

DemoSend.java

  1. package cody.soap.demo;
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.net.URL;
  6. import javax.activation.DataHandler;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import javax.xml.soap.AttachmentPart;
  12. import javax.xml.soap.MessageFactory;
  13. import javax.xml.soap.SOAPBody;
  14. import javax.xml.soap.SOAPConnection;
  15. import javax.xml.soap.SOAPConnectionFactory;
  16. import javax.xml.soap.SOAPEnvelope;
  17. import javax.xml.soap.SOAPException;
  18. import javax.xml.soap.SOAPHeader;
  19. import javax.xml.soap.SOAPMessage;
  20. import javax.xml.soap.SOAPPart;
  21. public class DemoSend extends HttpServlet {
  22. /**
  23. *
  24. */
  25. private static final long serialVersionUID = 1L;
  26. private SOAPConnection connection;
  27. @Override
  28. public void init() throws ServletException {
  29. super.init();
  30. try {
  31. SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();
  32. connection = connectionFactory.createConnection();
  33. } catch (UnsupportedOperationException e) {
  34. e.printStackTrace();
  35. } catch (SOAPException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. @Override
  40. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  41. throws ServletException, IOException {
  42. String outString ="<HTML><H1>Sending and reading the SOAP Message</H1><P>";
  43. try {
  44. MessageFactory messageFactory = MessageFactory.newInstance();
  45. SOAPMessage outgoingMessage = messageFactory.createMessage();
  46. SOAPPart soappart = outgoingMessage.getSOAPPart();
  47. SOAPEnvelope envelope = soappart.getEnvelope();
  48. SOAPHeader header = envelope.getHeader();
  49. SOAPBody body = envelope.getBody();
  50. body.addBodyElement(envelope.createName("numberAvailable", "laptops", "http://ecodl.taobao.com/")).addTextNode("216");
  51. StringBuffer serverUrl = new StringBuffer();
  52. serverUrl.append(request.getScheme()).append("://").append(request.getServerName());
  53. serverUrl.append(":").append(request.getServerPort()).append(request.getContextPath());
  54. String baseUrl = serverUrl.toString();
  55. URL url = new URL(baseUrl + "/test.html");
  56. AttachmentPart attachmentpart = outgoingMessage.createAttachmentPart(new DataHandler(url));
  57. attachmentpart.setContentType("text/html");
  58. outgoingMessage.addAttachmentPart(attachmentpart);
  59. URL client = new URL(baseUrl + "/DemoReceiver");
  60. FileOutputStream outgoingFile = new FileOutputStream("out.msg");
  61. outgoingMessage.writeTo(outgoingFile);
  62. outgoingFile.close();
  63. outString += "SOAP outgoingMessage sent (see out.msg). <BR>"+baseUrl+"<BR>";
  64. SOAPMessage incomingMessage = connection.call(outgoingMessage, client);
  65. if (incomingMessage != null) {
  66. FileOutputStream incomingFile = new FileOutputStream("in.msg");
  67. incomingMessage.writeTo(incomingFile);
  68. incomingFile.close();
  69. outString += "SOAP outgoingMessage received (see in.msg).</HTML>";
  70. }
  71. } catch (SOAPException e) {
  72. e.printStackTrace();
  73. }
  74. try {
  75. OutputStream outputStream = response.getOutputStream();
  76. outputStream.write(outString.getBytes());
  77. outputStream.flush();
  78. outputStream.close();
  79. } catch (IOException e) {}
  80. }
  81. @Override
  82. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  83. throws ServletException, IOException {
  84. doGet(req, resp);
  85. }
  86. }

DemoReceiver.java

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

test.xml

  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. <BODY>
  8. <H1>SOAP and Java</H1>
  9. Click <A HREF="DemoSend">here</a> to send the SOAP message.
  10. </BODY>
  11. </HTML>

out.msg

  1. ------=_Part_0_1985246804.1403343570084
  2. Content-Type: text/xml; charset=utf-8
  3. <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  4. <SOAP-ENV:Header/>
  5. <SOAP-ENV:Body>
  6. <laptops:numberAvailable xmlns:laptops="http://ecodl.taobao.com/">216</laptops:numberAvailable>
  7. </SOAP-ENV:Body>
  8. </SOAP-ENV:Envelope>
  9. ------=_Part_0_1985246804.1403343570084
  10. Content-Type: text/html
  11. <?xml version="1.0" encoding="UTF-8" ?>
  12. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  13. <HTML>
  14. <HEAD>
  15. <TITLE>SOAP and Java</TITLE>
  16. </HEAD>
  17. <BODY>
  18. <H1>SOAP and Java</H1>
  19. Click <A HREF="DemoSend">here</a> to send the SOAP message.
  20. </BODY>
  21. </HTML>
  22. ------=_Part_0_1985246804.1403343570084--

in.msg

  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]