天天看點

web service 的簡單實作

Java進階群:224651178

如何使用webservices

1.建立一個項目 webServer

項目結構圖

web service 的簡單實作

ItestService.java為測試接口類 給了聲明了一個getNameByUid的方法

package com.wzpmt.service; //Generated by MyEclipse public interface ItestService { public String getNameByUid(Object uid); }

ItestService.java 為測試接口實作類

package com.wzpmt.service; import java.util.HashMap; import java.util.Map; //Generated by MyEclipse public class TestServiceImpl implements ItestService { public TestServiceImpl(){ map.put(1,"我是1"); map.put(2,"我是2"); map.put(3,"我是3"); } private Map<Object,Object> map=new HashMap<Object, Object>(); public String getNameByUid(Object uid){ Object obj=map.get(uid); return obj+""; } }

services.xml 為webService配置檔案

<?xml version="1.0"encoding="UTF-8"?> <beans xmlns="http://xfire.codehaus.org/config/1.0"> <service> <name>testService</name> <serviceClass>com.wzpmt.service.ItestService</serviceClass> <implementationClass> com.wzpmt.service.TestServiceImpl </implementationClass> <style>wrapped</style> <use>literal</use> <scope>application</scope> </service> </beans>

2.建立一個測試項目 webClient

項目結果為下圖

web service 的簡單實作

該項目下也必須建立一個ItestService.java的接口與webServer下ItestService.java相對應。

ItestService.java類

package com.wzpmt.service; //Generated by MyEclipse public interface ItestService { public String getNameByUid(Object uid); }

完成了以上工作就可以創一個測試類進行測試了。

package com.wzpmt.test; import java.net.MalformedURLException; import org.codehaus.xfire.XFire; import org.codehaus.xfire.XFireFactory; import org.codehaus.xfire.client.XFireProxyFactory; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.binding.ObjectServiceFactory; import com.wzpmt.service.ItestService; public class Test { public static void main(String[] args) { Service serviceModel = new ObjectServiceFactory().create(ItestService.class); XFire xfire = XFireFactory.newInstance().getXFire(); XFireProxyFactory factory = new XFireProxyFactory(xfire); String serviceUrl = "http://localhost:8080/webServer/services/testService"; ItestService client = null; try { client = (ItestService)factory.create(serviceModel,serviceUrl); } catch (MalformedURLException e) { System.out.println( "Client callwebservice has exception: " + e.toString()); } System.out.println(client.getNameByUid(3)); } }

這是一個簡單的web service實作,有很多不足,望大家指出

Java進階群:224651178