【点点积累__使用JAXM创建Web服务】

   学习了Axis,有点使用框架的感觉。总觉得对soap理解的不是太透彻。公司要做一个Demo,使用soap消息格式存储到web服务上去。这样我就来看看JAXM了,

说到这,其实有很多提供好的webservice引擎,但是很多人不屑与用吧。说来也是啊,还要调查如何使用这些框架或者是接口,看得很Dan疼是吧。那就跟我来吧。

先看看什么是JAXM:

通常我们说的JAXM API是java平台提供的开发web服务的一系列API,它包括两个包:

Javax.xml.soap:它是发送SOAP消息的基本包,主要包含了发送带有附件的SOAP消息的API(SOAP with Attachments API for Java ,SAAJ)。它是SOAP消息的基本包,它为构建SOAP包和解析SOAP包提供了重要的支持。它包含了发送请求-响应消息相关的API。

Javax.xml.messaging:定义了JAXM的规范,包含了发送和接收消息所需的API。JAXM包含了以下几个概念:消息(Message)、连接(Connection)、消息提供者(Messaging providers)。对于什么是消息,连接,消息提供者看这里:http://www.ibm.com/developerworks/cn/webservices/ws-jaxm/part1/index.html

我们直接看怎么使用JAXM创建我们的应用吧:

首先 JAXM需要一个服务提供者的容器,毋庸置疑是Tomcat了。服务器供者就是Servlet了。关于配置Tomcat我就不用多说了。大侠都知道了。

我们下面在Eclipse中创建一个web的项目吧。作为我们的服务器端:

首先创建一个Servlet ---CPESoapServer.java继承自JAXMServlet 代码如下

View Code
   
     
package com.jftt.cpe.soap.server;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.xml.messaging.JAXMServlet;
import javax.xml.messaging.ReqRespListener;
import javax.xml.soap.SOAPMessage;

import com.jftt.cpe.thread.SoapMessageSaveThread;

public class CPESoapServer extends JAXMServlet implements ReqRespListener {


@Override
public void init(ServletConfig servletConfig) throws ServletException {
super .init(servletConfig);
SOAPFunc.init(servletConfig);
}

public SOAPMessage onMessage(SOAPMessage soapMsg) {
SOAPFunc func
= new SOAPFunc();
String file
= getServletContext().getRealPath( " / " ) + " result.xml " ;
System.out.println(
" file path= " + file );
new Thread( new SoapMessageSaveThread(file,soapMsg)).run();
return func.onMessage(soapMsg);
}
}
class SOAPFunc {


public static void init(ServletConfig servletConfig)
throws ServletException {
}

public SOAPMessage onMessage(SOAPMessage soapMsg) {
return soapMsg;
}

}
对,看看我们的代码中启动一个线程,这个线程类SoapMessageSaveThread。java 是这样写的

View Code
   
     
1 package com.jftt.cpe.thread;
2
3 import java.io.BufferedWriter;
4 import java.io.ByteArrayOutputStream;
5 import java.io.FileOutputStream;
6 import java.io.FileWriter;
7 import java.io.IOException;
8 import java.io.OutputStream;
9 import java.io.OutputStreamWriter;
10
11 import javax.xml.soap.SOAPBody;
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 import javax.xml.transform.Source;
17 import javax.xml.transform.Transformer;
18 import javax.xml.transform.TransformerConfigurationException;
19 import javax.xml.transform.TransformerException;
20 import javax.xml.transform.TransformerFactory;
21 import javax.xml.transform.TransformerFactoryConfigurationError;
22 import javax.xml.transform.stream.StreamResult;
23
24 public class SoapMessageSaveThread implements Runnable {
25
26 private SOAPMessage message;
27 private String filePath;
28
29 public SoapMessageSaveThread(String filePath, SOAPMessage message) {
30 super ();
31 this .filePath = filePath;
32 this .message = message;
33 }
34
35 @Override
36 public void run() {
37 try {
38 // System.out.println("body="+message.getSOAPBody().getTextContent().toString());
39 // System.out.println( "message="+message.getSOAPPart().getTextContent().toString());
40 SOAPPart replySP = message.getSOAPPart();
41 SOAPEnvelope replySE = replySP.getEnvelope();
42 SOAPBody replySB = replySE.getBody();
43 if (replySB.hasFault()) {
44 System.out.println( " ERROR: "
45 + replySB.getFault().getFaultString());
46 } else {
47 System.out.println( " Positive response received. " );
48 }
49 FileWriter fw = new FileWriter(filePath, true );
50 OutputStream fiout = new FileOutputStream(filePath);
51 BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(fiout, " utf-8 " ));
52 Source source = message.getSOAPPart().getContent();
53 Transformer transformer = TransformerFactory.newInstance()
54 .newTransformer();
55 ByteArrayOutputStream myOutStr = new ByteArrayOutputStream();
56 StreamResult res = new StreamResult();
57 res.setOutputStream(myOutStr);
58 transformer.transform(source, res);
59 String temp = myOutStr.toString( " UTF-8 " ).trim();
60 System.out.println(temp);
61 bw.write(temp);
62 bw.newLine();
63 bw.flush();
64 bw.close();
65 } catch (TransformerConfigurationException e) {
66 e.printStackTrace();
67 } catch (SOAPException e) {
68 e.printStackTrace();
69 } catch (IOException e) {
70 e.printStackTrace();
71 } catch (TransformerFactoryConfigurationError e) {
72 e.printStackTrace();
73 } catch (TransformerException e) {
74 e.printStackTrace();
75 }
76 }
77
78 }

看到了吧,其实这个类就是接受到的soap消息体原封不动的存入文件中。好了。服务器就这样建好了。当然要注意一下Servlet的映射配置是否正确

否则到时候要出现404的错误就搞笑了哈。

接下来看看我们的客户端是怎么写的吧:

我这里客户端也是一个web项目,使用tomcat容器。公司要求这么实现。我就先联系一下了。其实客户端没有必要做一个web服务的。

好了,闲话不说了,先看看吧客户端有一个Servlet-----SendSoapMessage.java,直接看代码

View Code
   
     
1 package com.jftt.soap;
2
3 import java.io.IOException;
4 import javax.servlet.ServletException;
5 import javax.servlet.http.HttpServlet;
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpServletResponse;
8
9 public class SendSoapMessage extends HttpServlet {
10 private static final long serialVersionUID = 1L ;
11
12 public SendSoapMessage() {
13 super ();
14 }
15
16 protected void doGet(HttpServletRequest request,
17 HttpServletResponse response) throws ServletException, IOException {
18 super .doGet(request, response);
19 }
20
21 protected void doPost(HttpServletRequest request,
22 HttpServletResponse response) throws ServletException, IOException {
23 request.setCharacterEncoding( " utf-8 " );
24 String userName = request.getParameter( " text1 " );
25 String huiXian = request.getParameter( " text2 " );
26 String kind = request.getParameter( " select " );
27 String qrcode = request.getParameter( " text3 " );
28 boolean isSoaped = SoapUtil.sendSoapMessage( " http://localhost:8080/CPE_Soap_Server/CPESoapServer " , userName, huiXian, kind, qrcode);
29 if (isSoaped){
30 response.getWriter().write( " Soap Message send successfully ! " );
31 response.getWriter().flush();
32 response.getWriter().close();
33 }
34 }
35
36 }

看官注意了,其中的URL地址正好是刚才上面的服务器端配置的IP端口和url。现在清楚了吧我们其实是两个web服务在通信。上面的

SoapUtil类如下:

View Code
   
     
1 package com.jftt.soap;
2
3 import java.net.MalformedURLException;
4 import java.net.URL;
5
6
7 public class SoapUtil {
8 public static boolean sendSoapMessage(String desturl,String name,String huixian,String kind,String qrcode) {
9 URL url;
10 SOAPClient soapClient = null ;
11 try {
12 url = new URL(desturl);
13 StringBuffer str = makeSoapBody(name, huixian, kind, qrcode);
14 soapClient = new SOAPClient(str,url);
15
16 } catch (MalformedURLException e) {
17 e.printStackTrace();
18 }
19 return soapClient.sendSoapMsg();
20 }
21 public static StringBuffer makeSoapBody(String name,String huixian,String kind,String qrcode){
22 StringBuffer str = new StringBuffer( " <记录>\n<担当者> " + name + " </担当者>\n " );
23 str.append( " <回線コード> " + huixian + " </回線コード>\n " );
24 str.append( " <設備種別> " + kind + " </設備種別>\n " );
25 str.append( " <設備コード> " + qrcode + " </設備コード>\n " );
26 str.append( " </记录>\n " );
27
28
29 return str;
30 }
31 }

呵呵其实挺简单的,而且看得出来我们的参数的来源是页面的表单了。SoapUtil中用的SOAPClient如下:

View Code
   
     
1 package com.jftt.soap;
2
3
4 import java.io.ByteArrayInputStream;
5 import java.net.URL;
6
7 import javax.xml.parsers.DocumentBuilder;
8 import javax.xml.parsers.DocumentBuilderFactory;
9 import javax.xml.soap.MessageFactory;
10 import javax.xml.soap.SOAPConnection;
11 import javax.xml.soap.SOAPConnectionFactory;
12 import javax.xml.soap.SOAPException;
13 import javax.xml.soap.SOAPMessage;
14 import javax.xml.soap.SOAPPart;
15 import javax.xml.transform.dom.DOMSource;
16
17 import org.w3c.dom.Document;
18
19 public class SOAPClient {
20
21 private StringBuffer soapBody;
22 private URL url;
23 private StringBuffer soapXml;
24 private SOAPMessage msg;
25 private MessageFactory mf;
26 private SOAPMessage reply;
27 public SOAPClient(StringBuffer soapBody, URL url) {
28 super ();
29 this .soapBody = soapBody;
30 this .url = url;
31 }
32 public boolean sendSoapMsg () {
33
34 try {
35 soapXml = new StringBuffer();
36 mf = MessageFactory.newInstance();
37 msg = mf.createMessage();
38 SOAPPart part = msg.getSOAPPart();
39 setXmlHeader();
40 soapXml.append(soapBody);
41 setXmlFooter();
42 System.out.println( " ********************************************************************************* " );
43 System.out.println( " Send SOAPMessage: " );
44 System.out.println(soapXml);
45 System.out.println( " ********************************************************************************* " + soapXml.toString().getBytes( " shift-jis " ));
46 ByteArrayInputStream xmlStream = new ByteArrayInputStream(soapXml.toString().getBytes( " UTF-8 " ));
47 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
48 synchronized (dbf) {
49 DocumentBuilder db = dbf.newDocumentBuilder();
50 Document doc = db.parse(xmlStream);
51 DOMSource domSource = new DOMSource(doc);
52 part.setContent(domSource);
53 }
54 // msg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
55 msg.saveChanges();
56
57 } catch (Exception e) {
58 return false ;
59 }
60 try {
61 SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
62
63 SOAPConnection conn = scf.createConnection();
64
65 reply = conn.call(msg, url);
66 conn.close();
67
68 } catch (Exception e) {
69 return false ;
70 }
71 if (reply == null ) {
72 return false ;
73 }
74 String receiveMsg = null ;
75 try {
76 receiveMsg = reply.getSOAPBody().toString();
77 } catch (SOAPException e) {
78 return false ;
79 }
80 return true ;
81 }
82 private void setXmlHeader() {
83
84 soapXml.append( " <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n " );
85 soapXml.append( " <soapenv:Envelope " );
86 soapXml.append( " soapenv:encodingStyle= " +
87 " \"http://schemas.xmlsoap.org/soap/encoding/\" " );
88 soapXml.append( " xmlns:soapenv=\"http: " +
89 " //schemas.xmlsoap.org/soap/envelope/\" " );
90 soapXml.append( " xmlns:xsd=\"http: " +
91 " //www.w3.org/2001/XMLSchema\" " );
92 soapXml.append( " xmlns:xsi=\"http: " +
93 " //www.w3.org/2001/XMLSchema-instance\" " );
94 soapXml.append( " xmlns:SOAP-ENC=\"http: " +
95 " //schemas.xmlsoap.org/soap/encoding/\">\n " );
96 soapXml.append( " <soapenv:Header/>\n " );
97 soapXml.append( " <soapenv:Body>\n " );
98
99 }
100 private void setXmlFooter() {
101
102 soapXml.append( " </soapenv:Body>\n " );
103 soapXml.append( " </soapenv:Envelope>\n " );
104
105 }
106
107 }

这个类中包括了

  1. 创建 SOAP 连接
  2. 创建 SOAP 消息
  3. 在SOAP消息里增加数据
  4. 发送消息
  5. 对SOAP应答进行处理
    看看吧,这就是我们的SOAP通信的过程。好了我们前端的JSP页面如下

  6. View Code
        
          
    1 <% @ page language = " java " contentType = " text/html; charset=UTF-8 " import = " java.io.*,java.util.* "
    2 pageEncoding = " UTF-8 " %>
    3 <! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
    4 < html >
    5 < head >
    6 < meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" >
    7 < title > 情報登録画面 </ title >
    8 < script type ="text/javascript" >
    9 function notify(s){
    10 document.getElementById( " text3 " ).value = s;
    11 }
    12
    13 function onCamera(){
    14 window.java2js.toCamera();
    15 }
    16
    17 function check() {
    18 if (document.getElementById( " text1 " ).value == "" ) {
    19 alert( " 担当者を入力してください " );
    20 return false ;
    21 } else if (document.getElementById( " text2 " ).value == "" ) {
    22 alert( " 回線コードを入力してください " );
    23 return false ;
    24 } else if (document.getElementById( " text3 " ).value == "" ) {
    25 alert( " 設備コードを入力してください " );
    26 return false ;
    27 } else {
    28 return true ;
    29 }
    30 }
    31 </ script >
    32
    33 < style type ="text/css" >
    34 caption {
    35 font-size : x-large ;
    36 font-weight : bold ;
    37 }
    38
    39 td {
    40 text-align : center ;
    41 }
    42
    43 td > input {
    44 width : 180px ;
    45 }
    46
    47 .space {
    48 height : 20px ;
    49 }
    50 </ style >
    51 </ head >
    52
    53 < body >
    54 <%
    55 String path = getClass().getResource( " / " ).getPath();
    56 InputStream in = new FileInputStream(path + " confg.properties " );
    57 Properties property = new Properties();
    58 property .load(in);
    59 int count = Integer .parseInt( property .getProperty( " count " ));
    60 %>
    61 < center >
    62 < form name ="input" action ="info.jsp" method ="post" >
    63 < table >
    64 < caption > CPE設備管理 </ caption >
    65 < tr class ="space" ></ tr >
    66 < tr >
    67 < td > 担当者 </ td >
    68 < td >
    69 < input type ="text" name ="text1" id ="text1" />
    70 </ td >
    71 </ tr >
    72 < tr >
    73 < td > 回線コード </ td >
    74 < td >
    75 < input type ="text" name ="text2" id ="text2" />
    76 </ td >
    77 </ tr >
    78 < tr >
    79 < td > 設備種別 </ td >
    80 < td >
    81 < select name ="select" style ="width: 185px" >
    82 <%
    83 for ( int i = 1 ; i <= count; i ++ ) {
    84 String type = new String ( property .getProperty( " type " + i).getBytes( " ISO8859-1 " ), " UTF-8 " ) ;
    85 out.print( " <option value=\"" + type + " \ " > " + type + " </option> " );
    86 }
    87 %>
    88 </ select >
    89 </ td >
    90 </ tr >
    91 < tr >
    92 < td > 設備コード </ td >
    93 < td >
    94 < input type ="text" name ="text3" id ="text3" />
    95 </ td >
    96 </ tr >
    97 < tr >
    98 < td colspan ="2" >
    99 < input type ="button" id ="Personaldata" value ="QRコード読取" style ="width:150px" onclick ="onCamera();" />
    100 </ td >
    101 </ tr >
    102 < tr >
    103 < td colspan ="2" >
    104 < input type ="submit" value ="送信" style ="width:120px" onclick ="return check();" /> &nbsp;&nbsp;&nbsp;&nbsp;
    105 < input type ="reset" value ="取り消し" style ="width:120px" />
    106 </ td >
    107 </ tr >
    108 </ table >
    109 </ form >
    110 </ center >
    111 </ body >
    112 </ html >

你可能感兴趣的:(Web)