1、给web项目添加web service支持,web.xml文件会自动修改。
<SERVLET-NAME>XFireServlet</SERVLET-NAME><SERVLET-CLASS>org.codehaus.xfire.transport.http.XFireConfigurableServlet</SERVLET-CLASS><LOAD-ON-STARTUP>0</LOAD-ON-STARTUP><SERVLET-MAPPING><SERVLET-NAME>XFireServlet</SERVLET-NAME><URL-PATTERN>/services/*</URL-PATTERN></SERVLET-MAPPING>
2、 创建对外提供的服务接口和实现类
接口:HelloService
package com.xaccp.service;public interface HelloService { public String sayHello(String name);}
实现类:HelloServiceImpl
package com.xaccp.service;public class HelloServiceImpl implements HelloService { public String sayHello(String name) { System.out.println("来自客户端的用户:" + name); return "服务器说你好:" + name; }}
3、 发布服务
上面发布后 services.xml 就发生下面的变化
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://xfire.codehaus.org/config/1.0"> <service> <name>Hello</name> <serviceClass>com.xaccp.service.HelloService</serviceClass> <implementationClass> com.xaccp.service.HelloServiceImpl </implementationClass> <style>wrapped</style> <use>literal</use> <scope>application</scope> </service></beans>
到此服务器端就ok了,测试一下是否ok,发布服务到Tomcat;启动Tomcat,访问:http://localhost:8080/helloService/services,出现如下信息说明发布成功
4、 客户端
创建web项目(需要添加xFire包)或webService项目,需要服务器提供接口:
测试类:
public static void main(String[] args) {// 创建服务的元数据Service serviceModel = new ObjectServiceFactory().create(HelloService.class);// 创建服务的代理XFire xfire = XFireFactory.newInstance().getXFire();XFireProxyFactory factory = new XFireProxyFactory(xfire);// 指定服务的地址 应用程序地址+“/services/”+服务名称String serviceUrl = "http://192.168.0.98:8080/helloService/services/Hello";HelloService client = null;try {// 创建服务的对象client = (HelloService) factory.create(serviceModel, serviceUrl);// 调用服务String res = client.sayHello("哈哈");System.out.println(res);} catch (MalformedURLException e) {System.out.println(" " + e.getMessage());}}
[Ok3w_NextPage]本文由北大青鸟论坛投稿,原文地址:http://www.beiniao.net/thread-3174-1-1.html