一、我们也可以这样写一个webservice的客户端来调用webserivce.
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); /** * wsdl的获取方法:在启动web工程的时候,我们输入url/service就可以看到工程里面的所有暴露的接口, * 找到你需要的那个接口点进去后,看到的url就是需要的wadl * */ org.apache.cxf.endpoint.Client client = dcf.createClient("http://127.0.0.1:8080/lxjweb/service/test?wsdl"); Object[] reply = null; String paramw = "admin1"; String param = "admin2"; try { /** * 调用的时候,第一个为实现时方法的名称 * 后面的参数才是方法所需要的参数 */ reply = client.invoke("testMethod",paramw,param); System.out.println(reply[0].toString()); } catch (Exception e) { e.printStackTrace(); }
二、这样写的时候,我们要把对应的接口映射过来
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean (); factory.setServiceClass(ITest.class); factory.setAddress("http://127.0.0.1:8080/lxjweb/service/test"); Object obj = factory.create(); if(obj != null){ ITest it = (ITest)obj; try { String s = it.testMethod("admin", "admin123"); System.out.println(s); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
三、服务端代码:接口
import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; @WebService public interface ITest { //当调用这个方法的时候,第一个参数为方法名称,后面的参数才是真正的参数 @WebMethod public String testMethod(@WebParam(name="param1") String param1, @WebParam(name="param2") String param2); }
接口实现类
import javax.jws.WebService; import com.lenovo.lxj.product.webservice.ITest; /** * webService的一个实现类, * endpointInterface 表示实现的那个接口 * targetNamespace 命名空间 * @author issuser * */ @WebService(endpointInterface = "com.lenovo.lxj.product.webservice.ITest", targetNamespace="http://webservice.product.lxj.lenovo.com/") public class TestImpl implements ITest{ @Override public String testMethod(String param1, String param2) { // TODO Auto-generated method stub String result = "This is param1: " + param1 + ", this is param2: " + param2; return result; } }
配置文件
<jaxws:endpoint id="test" address="/test"> <jaxws:implementor> <bean class="com.lenovo.lxj.product.webservice.impl.TestImpl"> </bean> </jaxws:implementor> </jaxws:endpoint>
注意在写配置文件的时候一定要引入
<import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
注:做试验的时候,一定要把客户端和服务端分别写在两个工程里面。