顺应SOA潮流,玩玩WebServices

顺应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

本程序的项目结构图如下:
顺应SOA潮流,玩玩WebServices_第1张图片

你可能感兴趣的:(顺应SOA潮流,玩玩WebServices)