Java使用XFire调用WebService接口
服务端(为客户端提供Webservice接口):
使用工具:myeclipse-8.6.1-win32,apache-tomcat-7.0.11
开发步骤:1.创建工程
File->New->Web Service Project,弹出Web Service Project窗口,需要填写Project Name(例子是Demo),选择XFire,然后一路next,直到完成。
创建完成后,打开生成的web.xml文件,可以看到,XFire已经配置好了。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>XFireServlet</servlet-name> <servlet-class>org.codehaus.xfire.transport.http.XFireConfigurableServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>XFireServlet</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://xfire.codehaus.org/config/1.0"> <service> <name>IMyService</name> <serviceClass>com.demo.service.IIMyService</serviceClass> <implementationClass> com.demo.service.IMyServiceImpl </implementationClass> <style>wrapped</style> <use>literal</use> <scope>application</scope> </service></beans>
package com.demo.service; //Generated by MyEclipse public interface IIMyService { public String example(String message); }package com.demo.service; //Generated by MyEclipse public class IMyServiceImpl implements IIMyService { public String example(String message) { return message; } }
package com.demo.client; import org.codehaus.xfire.client.XFireProxyFactory; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.binding.ObjectServiceFactory; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String serviceUrl = "http://localhost:8080/Demo/services/MyService"; Service serviceModel = new ObjectServiceFactory().create(IMyService.class, null, "http://localhost:8080/Demo/services/MyService?wsdl", null); XFireProxyFactory serviceFactory = new XFireProxyFactory(); try{ IMyService service = (IMyService)serviceFactory.create(serviceModel,serviceUrl); String hello = service.example("hello"); System.out.println(hello); }catch(Exception e){ e.printStackTrace(); } } }