首先,我們在eclipse中建立一個WebService工程作為服務端,並編寫如下代碼:
IHelloService.java 服務介面,有一個方法,參數和傳回值均為複雜類型User
package test;
public interface IHelloService ...{
public User getUser(User user);
}
User.java
注意,這個javabean裡必須要有一個預設沒有參數的構造方法,否則在進行aegis綁定會有不能執行個體化user對象的異常
package test;
import java.io.Serializable;
public class User...{
private String username;
private String password;
public User()...{
}
public User(String username, String password) ...{
super();
this.username = username;
this.password = password;
}
public String getPassword() ...{
return password;
}
public void setPassword(String password) ...{
this.password = password;
}
public String getUsername() ...{
return username;
}
public void setUsername(String username) ...{
this.username = username;
}
}
HelloServiceImpl.java
方法實現是傳進來一個user對象,把這個對象的username,password變成我們設定的數值,然後返回這個對象
package test;
public class HelloServiceImpl implements IHelloService ...{
public void print() ...{
System.out.println("action");
}
public User getUser(User user) ...{
user.setUsername("new name");
user.setPassword("new password");
return user;
}
}
IHelloService.aegis.xml 為複雜參數和傳回型別綁定,和IHelloService在一個包下
<?xml version="1.0" encoding="UTF-8"?>
<mappings>
<mapping>
<method name="getUser">
<parameter index="0" componentType="test.User"/>
<return-type componentType="test.User"/>
</method>
</mapping>
</mappings>
services.xml xFire發布檔案
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<service xmlns="http://xfire.codehaus.org/config/1.0">
<name>HelloService</name>
<namespace>http://test/HelloService</namespace>
<serviceClass>test.IHelloService</serviceClass>
<implementationClass>test.HelloServiceImpl</implementationClass>
</service>
</beans>
部署到tomcat中,在瀏覽器中運行http://localhost:8080/XFire/services/HelloService?wsdl
如果部署正確,講出現XFire產生的wsdl檔案
把IHelloService.java, IHelloService.aegis.xm,User.java打包成jar
下面,我們編寫消費WS的用戶端
建立一個java工程,把服務端的jar放到classpath中,當然,服務和用戶端都要有XFire的類庫
編寫代碼
package test;
import java.net.MalformedURLException;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;
import test.IHelloService;
import test.User;
public class Client ...{
/** *//**
* @param args
*/
public static void main(String[] args) ...{
User user=new User("2","2");
String serviceURL="http://localhost:8080/XFire/services/HelloService";
Service serviceModel = new ObjectServiceFactory().create(IHelloService.class,null,"http://test/HelloService",null);
XFireProxyFactory serviceFactory = new XFireProxyFactory();
IHelloService service = null;
try ...{
service = (IHelloService) serviceFactory.create(serviceModel, serviceURL);
user=service.getUser(user);
System.out.println(user.getUsername()+" - "+user.getPassword());
} catch (MalformedURLException e) ...{
e.printStackTrace();
}
}
}
在tomca安裝目錄下的bin中啟動tomcat(注意不要使用eclipse環境中的啟動外掛程式,否則運行用戶端時候會自動關掉服務)
運行結果:
new name - new password
真是我們想要的結果