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 version="1.0" encoding="ISO-8859-1"?>
- <!DOCTYPE web-app
- PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
- "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
- <web-app>
- <servlet>
- <servlet-name>DemoSend</servlet-name>
- <servlet-class>cody.soap.demo.DemoSend</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>DemoReceiver</servlet-name>
- <servlet-class>cody.soap.demo.DemoReceiver</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>DemoSend</servlet-name>
- <url-pattern>/DemoSend</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>DemoReceiver</servlet-name>
- <url-pattern>/DemoReceiver</url-pattern>
- </servlet-mapping>
- </web-app>
DemoSend.java
- package cody.soap.demo;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.net.URL;
- import javax.activation.DataHandler;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.xml.soap.AttachmentPart;
- import javax.xml.soap.MessageFactory;
- import javax.xml.soap.SOAPBody;
- import javax.xml.soap.SOAPConnection;
- import javax.xml.soap.SOAPConnectionFactory;
- import javax.xml.soap.SOAPEnvelope;
- import javax.xml.soap.SOAPException;
- import javax.xml.soap.SOAPHeader;
- import javax.xml.soap.SOAPMessage;
- import javax.xml.soap.SOAPPart;
- public class DemoSend extends HttpServlet {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private SOAPConnection connection;
- @Override
- public void init() throws ServletException {
- super.init();
- try {
- SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();
- connection = connectionFactory.createConnection();
- } catch (UnsupportedOperationException e) {
- e.printStackTrace();
- } catch (SOAPException e) {
- e.printStackTrace();
- }
- }
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String outString ="<HTML><H1>Sending and reading the SOAP Message</H1><P>";
- try {
- MessageFactory messageFactory = MessageFactory.newInstance();
- SOAPMessage outgoingMessage = messageFactory.createMessage();
- SOAPPart soappart = outgoingMessage.getSOAPPart();
- SOAPEnvelope envelope = soappart.getEnvelope();
- SOAPHeader header = envelope.getHeader();
- SOAPBody body = envelope.getBody();
- body.addBodyElement(envelope.createName("numberAvailable", "laptops", "http://ecodl.taobao.com/")).addTextNode("216");
- StringBuffer serverUrl = new StringBuffer();
- serverUrl.append(request.getScheme()).append("://").append(request.getServerName());
- serverUrl.append(":").append(request.getServerPort()).append(request.getContextPath());
- String baseUrl = serverUrl.toString();
- URL url = new URL(baseUrl + "/test.html");
- AttachmentPart attachmentpart = outgoingMessage.createAttachmentPart(new DataHandler(url));
- attachmentpart.setContentType("text/html");
- outgoingMessage.addAttachmentPart(attachmentpart);
- URL client = new URL(baseUrl + "/DemoReceiver");
- FileOutputStream outgoingFile = new FileOutputStream("out.msg");
- outgoingMessage.writeTo(outgoingFile);
- outgoingFile.close();
- outString += "SOAP outgoingMessage sent (see out.msg). <BR>"+baseUrl+"<BR>";
- SOAPMessage incomingMessage = connection.call(outgoingMessage, client);
- if (incomingMessage != null) {
- FileOutputStream incomingFile = new FileOutputStream("in.msg");
- incomingMessage.writeTo(incomingFile);
- incomingFile.close();
- outString += "SOAP outgoingMessage received (see in.msg).</HTML>";
- }
- } catch (SOAPException e) {
- e.printStackTrace();
- }
- try {
- OutputStream outputStream = response.getOutputStream();
- outputStream.write(outString.getBytes());
- outputStream.flush();
- outputStream.close();
- } catch (IOException e) {}
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- doGet(req, resp);
- }
- }
DemoReceiver.java
- package cody.soap.demo;
- import java.util.Iterator;
- import javax.servlet.ServletConfig;
- import javax.servlet.ServletException;
- import javax.xml.messaging.JAXMServlet;
- import javax.xml.messaging.ReqRespListener;
- import javax.xml.soap.MessageFactory;
- import javax.xml.soap.SOAPBody;
- import javax.xml.soap.SOAPElement;
- import javax.xml.soap.SOAPEnvelope;
- import javax.xml.soap.SOAPException;
- import javax.xml.soap.SOAPMessage;
- import javax.xml.soap.SOAPPart;
- public class DemoReceiver extends JAXMServlet implements ReqRespListener{
- /**
- * Generated automatically
- */
- private static final long serialVersionUID = 1L;
- private static MessageFactory messageFactory = null;
- @Override
- public void init(ServletConfig servletConfig) throws ServletException {
- super.init(servletConfig);
- try {
- messageFactory = MessageFactory.newInstance();
- } catch (SOAPException e) {
- e.printStackTrace();
- }
- }
- @Override
- public SOAPMessage onMessage(SOAPMessage msg) {
- SOAPPart soappart = msg.getSOAPPart();
- try {
- SOAPEnvelope incomingEnvelope;
- incomingEnvelope = soappart.getEnvelope();
- SOAPBody body = incomingEnvelope.getBody();
- Iterator<?> iterator = body.getChildElements(incomingEnvelope.createName("numberAvailable", "laptops", "http://ecodl.taobao.com/"));
- SOAPElement element;
- element = (SOAPElement) iterator.next();
- SOAPMessage message = messageFactory.createMessage();
- SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
- SOAPBody responsebody = envelope.getBody();
- String responseText = "Got the SOAP message indicating there are " + element.getValue() + " laptops available.";
- responsebody.addChildElement(envelope.createName("Response")).addTextNode(responseText);
- return message;
- } catch (SOAPException e) {
- e.printStackTrace();
- return null;
- }
- }
- }
test.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <HTML>
- <HEAD>
- <TITLE>SOAP and Java</TITLE>
- </HEAD>
- <BODY>
- <H1>SOAP and Java</H1>
- Click <A HREF="DemoSend">here</a> to send the SOAP message.
- </BODY>
- </HTML>
out.msg
- ------=_Part_0_1985246804.1403343570084
- Content-Type: text/xml; charset=utf-8
- <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
- <SOAP-ENV:Header/>
- <SOAP-ENV:Body>
- <laptops:numberAvailable xmlns:laptops="http://ecodl.taobao.com/">216</laptops:numberAvailable>
- </SOAP-ENV:Body>
- </SOAP-ENV:Envelope>
- ------=_Part_0_1985246804.1403343570084
- Content-Type: text/html
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <HTML>
- <HEAD>
- <TITLE>SOAP and Java</TITLE>
- </HEAD>
- <BODY>
- <H1>SOAP and Java</H1>
- Click <A HREF="DemoSend">here</a> to send the SOAP message.
- </BODY>
- </HTML>
- ------=_Part_0_1985246804.1403343570084--
in.msg
- <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
- <SOAP-ENV:Header/>
- <SOAP-ENV:Body>
- <Response>Got the SOAP message indicating there are 216 laptops available.
- </Response>
- </SOAP-ENV:Body>
- </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]