读书人

My web service开发指南(一)

发布时间: 2012-11-16 14:12:15 作者: rapoo

My web service开发指南(1)
Web Service 开发指南
1、服务器端开发
a)创建服务器端接口
package com.huawei.ws.s;

import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.jws.soap.SOAPBinding.Use;

@WebService
@SOAPBinding(style = Style.RPC, use = Use.LITERAL)
public interface EmployeePort
{
public Employee searchEmpByID(String id);

}
b)接口实现类
package com.huawei.ws.s;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebService;

@WebService(endpointInterface="com.huawei.ws.s.EmployeePort")
public class EmployeeService implements EmployeePort {
……

b)生成WSDL文件
package com.huawei.ws.s;

import javax.xml.ws.Endpoint;

public class TestService
{

public static void main(String[] args)
{
Endpoint.publish("http://127.0.0.1:1234/empolyee", new EmployeeService());
}

}


2、使用JDK自带工具生成 客户端代码
jdk6自带jax-ws,运行wsimport命令完成客户端代码的自动生成
如:wsimport -keep -p com.wsclient http://127.0.0.1:1234/empolyee?wsdl
说明如下:
Usage: wsimport [options] <WSDL_URI>
-keep keep generated files
-p <pkg> specifies the target package
在生成的*service.java中有方法可以直接拿到ws接口。
package com.huawei.ws.c;

import java.net.URL;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPMessage;

public class TestClient {

public static void main(String[] args) throws Exception {

// 1.创建连接
SOAPConnectionFactory soapMsgF = SOAPConnectionFactory.newInstance();
SOAPConnection conn = soapMsgF.createConnection();

// 2.根据wsdl的schema构建soap消息
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage soapMsg = mf.createMessage();
Name name = soapMsg.getSOAPPart().getEnvelope().createName("searchEmpByID", "zx", "http://com.huawei.c/");
Name arg0 = soapMsg.getSOAPPart().getEnvelope().createName("arg0");
soapMsg.getSOAPPart().getEnvelope().getBody().addBodyElement(name).addChildElement(arg0).addTextNode("01");

// 3.调用服务
SOAPMessage soapMsgResponse = conn.call(soapMsg, new URL("http://127.0.0.1:1234/employee"));
soapMsgResponse.writeTo(System.out);

}
}


读书人网 >Web前端

热点推荐