順應SOA潮流,玩玩WebServices

                  最近SOA很火,SOA實現服務整合,其中最核心的部分就是WebService,筆者對WebService還停留在菜鳥級,于是從網上下載了axis開發包,嘗試了一下WebSerivce的開發和部署。
                   一、開發工具:MyEclipse5.0M2+Eclipse3.2.0+JDK1.5.0_12+axis2-1.3-RC2-bin+axis2-1.3-RC2-war
           +proxool-0.9.0RC2+SqlServer2000+Tomcat5.5.20,以上工具的下載地址我就不細說了,如果讀者對哪個工具的下載地址不了解,請在這篇文章后給我留言。
                    二、開發環境:
                   1.將下載的Axis開發包axis2-1.3-RC2-bin.zip解壓,將其中的axis2-1.3-RC2 目錄拷貝到D:\;添加環境變量AXIS2_HOME=D:\axis2-1.3-RC2;在path變量中添加: D:\axis2-1.3-RC2。 
                   2.啟動Eclipse(我的Eclipse安裝在D:\eclipse3.2,workspace安裝在D:\eclipse3.2\workspace),新建一個web項目testwebservice,然后在項目的build path中添加axis2的UserLibrary(D:\axis2-1.3-RC2\*.jar)。
                   3.將D:\axis2-1.3-RC2\samples\quickstartaxiom下的目錄和文件拷貝到D:\eclipse3.2\workspace\testwebservice;刪除D:\eclipse3.2\workspace\testwebservice\resources\META-INF\StockQuoteService.wsdl;將D:\eclipse3.2\workspace\testwebservice\build.xml進行修改:將<property name="AXIS2_HOME" value="../.."/>更改為
           <property name="AXIS2_HOME" value="${env.AXIS2_HOME}"/>。
                   4.將下載的axis2-1.3-RC2-war.zip解壓,將其中的axis2.war拷貝到D:\Tomcat 5.5\webapps\,啟動Tomcat后,axis2.war被自動解壓為axis2目錄;將數據庫驅動程序包mssqlserver.jar、msbasejar、msutil.jar以及proxool數據源proxool-0.9.0RC2.jar都拷貝到D:\Tomcat 5.5\webapps\axis2\WEB-INF\lib,并且將上面的jar包添加的項目的build path中。
                   三、開發過程:
                   1.在SQLServer中新建數據庫test,在查詢分析器中執行下面的命令:
                   USE test;
                   
          CREATE TABLE stock        
                  {
                        symbol 
          varchar(10);
                        price 
          varchar(20);
                    };
                   
          INSERT INTO stock values('WSO','100');

                   將管理員sa的密碼改為lzqdiy。
                   2.在D:\eclipse3.2\workspace\testwebservice\src新建文件proxool.xml,內容如下:
           
          <?xml version="1.0" encoding="UTF-8"?>
          <something-else-entirely>
            
          <!-->proxool>
              <alias>oracle</alias>
              <driver-url>jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SID=ldb)(SERVER=DEDICATED)))
              </driver-url>
              <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
              <driver-properties>
                <property name="user" value="xdh"/>
                <property name="password" value="manager"/>
              </driver-properties>
              <maximum-connection-count>100</maximum-connection-count>
              <minimum-connection-count>1</minimum-connection-count>
              <house-keeping-test-sql>select CURRENT_DATE</house-keeping-test-sql>
            </proxool
          -->
            
          <proxool>
              
          <alias>sqlserver</alias>
              
          <driver-url>jdbc:microsoft:sqlserver://192.168.1.6:1433;databasename=test
              
          </driver-url>
              
          <driver-class>com.microsoft.jdbc.sqlserver.SQLServerDriver</driver-class>
              
          <driver-properties>
                
          <property name="user" value="sa"/>
                
          <property name="password" value="lzqdiy"/>
              
          </driver-properties>
              
          <maximum-connection-count>100</maximum-connection-count>
              
          <minimum-connection-count>20</minimum-connection-count>
              
          <house-keeping-test-sql>select CURRENT_DATE</house-keeping-test-sql>
            
          </proxool>
          </something-else-entirely>

                  3. 新建類dbc\DBConnection.java,內容如下:
          package dbc;

          import java.sql.*;
          import org.logicalcobwebs.proxool.ProxoolException;
          import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;

          public class DBConnection
          {
              
          public static final String ORACLE = "oracle";

              
          public static final String SQLSERVER = "sqlserver";

              
          private static boolean initialized = false;

              
          public static Connection getConnection() throws SQLException
              {

                  
          return getConnection(DBConnection.SQLSERVER);
              }

              
          public static Connection getConnection(String aliasName)
                      
          throws SQLException
              {
                  Connection connection 
          = null;
                  
          if (!initialized)
                  {

                      init();
                  }

                  connection 
          = DriverManager.getConnection("proxool." + aliasName);

                  
          if (connection != null)
                  {
                      
          return connection;
                  } 
          else
                  {
                      
          throw new NullPointerException(
                              
          "Didn't get connection, which probably means that no Driver accepted the URL");
                  }

              }

              
          private static void init()
              {
                  String fileName 
          = "D:/eclipse3.2/workspace/testwebservice/src/proxool.xml";
                  
          try
                  {

                      JAXPConfigurator.configure(fileName, 
          false);
                      
          // The false means non-validating
                      Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
                  } 
          catch (ClassNotFoundException e)
                  {
                      
          // TODO Auto-generated catch block
                      e.printStackTrace();
                  } 
          catch (ProxoolException e)
                  {
                      
          // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
                  initialized 
          = true;
              }

          }

                   4.修改D:\eclipse3.2\workspace\testwebservice\src\samples\quickstart\service\axiom\StockQuoteService.java
            1 /*
            2  * Licensed to the Apache Software Foundation (ASF) under one
            3  * or more contributor license agreements. See the NOTICE file
            4  * distributed with this work for additional information
            5  * regarding copyright ownership. The ASF licenses this file
            6  * to you under the Apache License, Version 2.0 (the
            7  * "License"); you may not use this file except in compliance
            8  * with the License. You may obtain a copy of the License at
            9  *
           10  * http://www.apache.org/licenses/LICENSE-2.0
           11  *
           12  * Unless required by applicable law or agreed to in writing,
           13  * software distributed under the License is distributed on an
           14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
           15  * KIND, either express or implied. See the License for the
           16  * specific language governing permissions and limitations
           17  * under the License.
           18  */
           19 package samples.quickstart.service.axiom;
           20 
           21 import javax.xml.stream.XMLStreamException;
           22 import javax.xml.namespace.QName;
           23 
           24 import org.apache.axiom.om.OMAbstractFactory;
           25 import org.apache.axiom.om.OMElement;
           26 import org.apache.axiom.om.OMFactory;
           27 import org.apache.axiom.om.OMNamespace;
           28 
           29 import dbc.DBConnection;
           30 
           31 import java.sql.Connection;
           32 import java.sql.ResultSet;
           33 import java.sql.SQLException;
           34 import java.sql.Statement;
           35 public class StockQuoteService {
           36 
           37     private String namespace = "http://quickstart.samples/xsd";
           38     
           39     public  Connection getConnection() throws SQLException
           40     {
           41         return DBConnection.getConnection();
           42     }
           43 
           44     public OMElement getPrice(OMElement element) throws XMLStreamException {
           45         element.build();
           46         element.detach();
           47 
           48         OMElement symbolElement = element.getFirstElement();
           49         String symbol = symbolElement.getText();
           50 
           51         String returnText = "42";
           52         
           53         Connection con=null;
           54         Statement st=null;
           55         ResultSet rs=null;
           56         String price=null;
           57         try
           58         {
           59             con = getConnection();
           60             st=con.createStatement();
           61             rs=st.executeQuery("select price from stock where symbol='"+symbol+"'");
           62             
           63             while(rs.next())
           64             price = rs.getString("price");
           65         } catch (SQLException e)
           66         {
           67             // TODO Auto-generated catch block
           68             e.printStackTrace();
           69         }
           70         finally{
           71             if(rs!=null)
           72             {
           73                 try
           74                 {
           75                     rs.close();
           76                 } catch (SQLException e)
           77                 {
           78                     // TODO Auto-generated catch block
           79                     e.printStackTrace();
           80                 }
           81             }
           82             if(st!=null)
           83             {
           84                 try
           85                 {
           86                     st.close();
           87                 } catch (SQLException e)
           88                 {
           89                     // TODO Auto-generated catch block
           90                     e.printStackTrace();
           91                 }
           92             }
           93             if(con!=null)
           94             {
           95                 try
           96                 {
           97                     con.close();
           98                 } catch (SQLException e)
           99                 {
          100                     // TODO Auto-generated catch block
          101                     e.printStackTrace();
          102                 }
          103             }
          104         }
          105         
          106         if(price != null){
          107             returnText  = price;
          108         }
          109         OMFactory fac = OMAbstractFactory.getOMFactory();
          110         OMNamespace omNs =
          111             fac.createOMNamespace(namespace, "ns");
          112         OMElement method = fac.createOMElement("getPriceResponse", omNs);
          113         OMElement value = fac.createOMElement("return", omNs);
          114         value.addChild(fac.createOMText(value, returnText));
          115         method.addChild(value);
          116         return method;
          117     }
          118 
          119     public void update(OMElement element) throws XMLStreamException {
          120         element.build();
          121         element.detach();
          122 
          123         OMElement symbolElement = element.getFirstChildWithName(new QName(namespace, "symbol"));
          124         String symbol = symbolElement.getText();
          125 
          126         OMElement priceElement = element.getFirstChildWithName(new QName(namespace, "price"));
          127         String price = priceElement.getText();
          128 
          129         Connection con=null;
          130         Statement st=null;
          131         try
          132         {
          133             con = getConnection();
          134             st=con.createStatement();
          135             st.executeUpdate("update stock set price='"+price+"' where symbol='"+symbol+"'");
          136             
          137         } catch (SQLException e)
          138         {
          139             // TODO Auto-generated catch block
          140             e.printStackTrace();
          141         }
          142         finally{
          143             
          144             if(st!=null)
          145             {
          146                 try
          147                 {
          148                     st.close();
          149                 } catch (SQLException e)
          150                 {
          151                     // TODO Auto-generated catch block
          152                     e.printStackTrace();
          153                 }
          154             }
          155             if(con!=null)
          156             {
          157                 try
          158                 {
          159                     con.close();
          160                 } catch (SQLException e)
          161                 {
          162                     // TODO Auto-generated catch block
          163                     e.printStackTrace();
          164                 }
          165             }
          166         }
          167     }
          168 }
          169 
          我在其中添加了訪問數據庫的語句和獲得數據庫連接的方法。運行build.xml中的compile編譯這個類,如果成功,在D:\eclipse3.2\workspace\testwebservice\build\classes\samples\quickstart\service\axiom下就會生成StockQuoteService.class,
               5.打開Dos窗口,進入D:\eclipse3.2\workspace\testwebservice\build\classes目錄輸入下面的命令來生成WSDL文件
          java2wsdl -cp . -cn samples.quickstart.service.axiom.StockQuoteService -of StockQuoteService.wsdl
          將StockQuoteService.wsdl 拷貝到D:\eclipse3.2\workspace\testwebservice\resources\META-INF\
               6.在WebRoot下新建test.jsp
          <%@ page language="java"  
          import
          ="samples.quickstart.clients.*" 
          import
          ="org.apache.axiom.om.*" 
          import
          ="org.apache.axis2.Constants"
          import
          ="org.apache.axis2.addressing.EndpointReference"
          import
          ="org.apache.axis2.client.Options"
          import
          ="org.apache.axis2.client.ServiceClient"
          pageEncoding
          ="GBK"
          %>

          <%
          String path = request.getContextPath();
          String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
          %>

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
          <html>
            
          <head>
              
          <base href="<%=basePath%>">
              
              
          <title>My JSP 'test.jsp' starting page</title>
              
              
          <meta http-equiv="pragma" content="no-cache">
              
          <meta http-equiv="cache-control" content="no-cache">
              
          <meta http-equiv="expires" content="0">    
              
          <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
              
          <meta http-equiv="description" content="This is my page">
              
          <!--
              <link rel="stylesheet" type="text/css" href="styles.css">
              
          -->

            
          </head>
            
            
          <body>
              This is my JSP page. 
          <br>
              
          <%
               EndpointReference targetEPR 
          = 
                  
          new EndpointReference(
                                        
          "http://localhost:8080/axis2/services/StockQuoteService");
              try {
                      
                      
                      OMElement getPricePayload 
          = AXIOMClient.getPricePayload("WSO");
                      OMElement updatePayload 
          = AXIOMClient.updatePayload("WSO"123.42);
                      Options options 
          = new Options();
                      options.setTo(targetEPR);
                      options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

                      ServiceClient sender 
          = new ServiceClient();
                      sender.setOptions(options);

                      sender.fireAndForget(updatePayload);
                      out.println(
          "price updated");
                      Thread.sleep(
          3000);
                      OMElement result 
          = sender.sendReceive(getPricePayload);

                      
          String response1 = result.getFirstElement().getText();
                      out.println(
          "Current price of WSO: " + response1);
                      
                  } catch (Exception e) {
                      e.printStackTrace();
                      out.println(e.getMessage());
                  }
              
               
          %>
            
          </body>
          </html>
                7.運行build.xml中的generate.service,如果成功后,會在D:\eclipse3.2\workspace\testwebservice\build下生成StockQuoteService.aar,將它拷貝到D:\Tomcat 5.5\webapps\axis2\WEB-INF\services \
                8.在使用MyEclipse提供的部署功能將testwebservice這個web項目發布到Tomcat上。
                9.重啟Tomcat后,打開IE,輸入http://localhost:8080/testwebservice/test.jsp,如果你看到下面的信息,表明運行成功!
          This is my JSP page.
          price updated Current price of WSO: 123.42

          本程序的項目結構圖如下:


          posted on 2007-08-26 11:13 我為J狂 閱讀(1521) 評論(0)  編輯  收藏 所屬分類: WebService


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          <2007年8月>
          2930311234
          567891011
          12131415161718
          19202122232425
          2627282930311
          2345678

          導航

          統計

          常用鏈接

          留言簿(11)

          隨筆分類(48)

          文章分類(29)

          常去逛逛

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 民权县| 余干县| 九江市| 邵阳县| 辽阳县| 林口县| 福海县| 南通市| 濮阳县| 浦江县| 广饶县| 安义县| 石嘴山市| 奎屯市| 乐安县| 七台河市| 江孜县| 石屏县| 顺昌县| 大名县| 南华县| 上蔡县| 家居| 封开县| 于田县| 宁晋县| 永和县| 石首市| 岳池县| 安康市| 龙陵县| 托里县| 滦南县| 朝阳县| 垣曲县| 偏关县| 双柏县| 安乡县| 通辽市| 隆安县| 巴彦淖尔市|