JAVA realize WebServcie

1, WebService Overview

(1) using the protocol described in WSDL content and services, access address and the like;

(2) using the SOAP protocol encapsulation interactive content, including the content request and response content;

(3) Http protocol to implement the transfer of information between client and server.

 

2, the service-side development

(1) Development services

The service class using @WebService notes, show class service class

Package com.gs; 

// provides resolution functions noted @WebService 
Import the javax.jws.WebService; 

/ * 
 * for the service class annotated Num2Cn 
 * Function: converts a number to characters 
 * / 
@WebService 
public  class Num2Cn 
{ 
    public String getCN ( int NUM) { 
        String S = "square" ;
         Switch (NUM) 
        { 
            Case 0: S = "square"; BREAK ;
             Case . 1: S = "a"; BREAK ;
             Case 2: S = "two"; BREAK ;
             Case . 3 : s = "three";break;
            case 4: s =  "四"; break;
            case 5: s =  "五"; break;
            case 6: s =  "六"; break;
            case 7: s =  "七"; break;
            case 8: s =  "八"; break;
            case 9: s =  "九"; break;
        }
        return s;
    }
}

(2) will be released out of service class

package com.gs;

// 提供发布webservice服务功能
import javax.xml.ws.Endpoint;

public class MyWS
{
    public static void main(String[] args) 
    {
        /*
         * 发布地址
         */
        String address = "http://127.0.0.1:8099/MyWS";
        
        /*
         * 发布对象
         */
        Endpoint.publish(address, new Num2Cn());
        
        System.out.println("发布服务成功…");
    }
}

3.客户端功能开发

(1)生成本地调用接口文件

wsimport -p com.serv -clientjar num2cn-1.0.jar http://127.0.0.1:8099/MyWS?wsdl

上述命令会在目录下生成序列class文件,并将这些class文件打包为num2cn-1.0.jar文件

(2)编写客户端代码

package com.gs;

import com.serv.Num2Cn;
import com.serv.Num2CnService;

public class TestNum2Cn
{
    public static void main(String[] args){
        /*
         * 过程分为3步:
         * 1. 新建服务类
         * 2. 查询服务功能接口
         * 3. 调用接口的方法
         */
        Num2CnService num2CnService =new Num2CnService();
        Num2Cn num2Cn = num2CnService.getNum2CnPort();
        String result =num2Cn.getCN(8);
        
        System.out.println("8="+result);
        }   
}

 

(3)运行

java -cp .;../lib/num2cn-1.0.jar com.gs.TestNum2Cn

结果为8=八

 

Guess you like

Origin www.cnblogs.com/coderbase/p/11322129.html