您的位置:首页 > 编程语言 > Java开发

总结java开发web service的方法

2006-08-29 23:45 465 查看
总结java开发web service的方法

来源:http://bbs.w3china.org/dispbbs.asp?boardid=10&id=35751

目前看到的有三种比较简单的方法:
1使用静态的stub
通过wsdl2java工具,处理相应ws的wsdl文件,我们可以得到远程ws的stub 直接调用这
个stub即可
AXIS提供的wsdl2java工具,如下:
java org.apache.axis.wsdl.WSDL2Java (WSDL-file-URL)
我们直接调用stub即可
eclipse也有相应的插件可以直接import wsdl来产生stub,如果你安装了EMF all in one版本的eclipse 3.1,就可以在视图里把Web Service的相关视图打开,接着就可以通过Web Service的Wizard来创建出相关的Web Service Client或者Server

2 Dynamic Proxy
根据远程wsdl,利用javax.xml.rpc.Service的getPort函数,可以得到远程ws的一个 D
ynamic Proxy
编写代理接口

public interface HelloClientInterface
extends Java.rmi.Remote
{
public String getName(String name)
throws Java.rmi.RemoteException;
}

客户端程序TestHelloClient.Java

import Javax.xml.rpc.Service;
import Javax.xml.rpc.ServiceFactory;
import Java.net.URL;
import Javax.xml.namespace.QName;

public class TestHelloClient
{
public static void main(String[] args)
{
try
{
String wsdlUrl = "http://localhost:8080/axis/HelloClient.jws?wsdl";
String nameSpaceUri = "http://localhost:8080/axis/HelloClient.jws";
String serviceName = "HelloClientService";
String portName = "HelloClient";
ServiceFactory serviceFactory = ServiceFactory.newInstance();
Service afService = serviceFactory.createService(new url(http://www.zhmy.com/wsdlUrl),
new QName(nameSpaceUri, serviceName));
HelloClientInterface proxy = (HelloClientInterface)afService.getPort(new QName(
nameSpaceUri, portName), HelloClientInterface.class);
System.out.println("return value is "+proxy.getName("john") ) ;
}catch(Exception ex)
{
ex.printStackTrace() ;
}
}
}

3 DII
Dynamic Invocation Interface 这个最好理解,比如你动态获得了一个类,只知道类的
名字,你要调用他的一个方法,只好使用reflection得到你要调用的类,相应的参数信
息,然后调用
使用DII调用WS的时候,你知道的只是一个WSDL的地址,通过解析wsdl,你可以得到相应
的ws endpoint的信息,然后通过javax.xml.rpc.Call的setOperationName, addParam
eter等函数来指定要调用的函数,指定参数,然后调用
提供DII调用的原因是,我们有可能使用程序自动的去动态调用网络上的WS,而这个WS的
一切信息都是来自其WSDL
,只有通过DII,我们才有可能动态的去调用这个ws
例子:
服务器端程序

public class HelloClient
{
public String getName(String name)
{
return "hello "+name;
}
}
把源码拷贝到AXIS_HOME下,并改名为 HelloClient.jws

客户端程序
import org.apache.Axis.client.Call;
import org.apache.Axis.client.Service;
import Javax.xml.namespace.QName;
import Javax.xml.rpc.ServiceException;
import Java.net.MalformedURLException;
import Java.rmi.RemoteException;

public class SayHelloClient2
{
public static void main(String[] args)
{
try
{
String endpoint = "http://localhost:8080/axis/HelloClient.jws";

Service service = new Service();
Call call = null;

call = (Call) service.createCall();

call.setOperationName
(new QName("http://localhost:8080/axis/HelloClient.jws", "getName"));
call.setTargetEndpointAddress(new Java.net.url(http://www.zhmy.com/endpoint));

String ret =
(String) call.invoke(new Object[]
{"zhangsan"});
System.out.println
("return value is " + ret);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: