webService需要的maven依
<properties>
<myVersion>2.7.18</myVersion>
</properties>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${myVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${myVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${myVersion}</version>
</dependency>
服务端需要三个类,
服务方法实体类,
package cn.et;
public class ArithImp implements Arith {
/* (non-Javadoc)
* @see cn.et.Arith#arithmetic(int, int, java.lang.String)
*/
@Override
public String arithmetic(int param1,int param2,String run){
if(run==null){
return "算术不合法";
}
if(run.trim().equals("+")){
return (param1+param2)+"";
}else if(run.trim().equals("-")){
return (param1+param2)+"";
}else if(run.trim().equals("*")){
return (param1+param2)+"";
}else if(run.trim().equals("/")){
return (param1+param2)+"";
}else if(run.trim().equals("%")){
return (param1+param2)+"";
}
return "算术不合法";
}
}
实体类的接口,
package cn.et;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface Arith {
@WebMethod
public abstract String arithmetic(int param1, int param2, String run);
}
程序入口类
package cn.et;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
public class Test {
public static void main(String[] args) {
//创建服务工厂类
JaxWsServerFactoryBean jsfb=new JaxWsServerFactoryBean();
//添加访问地址
jsfb.setAddress("http://192.168.4.142:8090/arith");
//添加服务方法实例
jsfb.setServiceBean(new ArithImp());
//添加实体类的接口
jsfb.setServiceClass(Arith.class);
//创建服务
Server create = jsfb.create();
}
}
客户端
用jdk提供的wsimport命令生成代码调用wsimport -d D:\etop1610\WORK\testB\src -p cn.et.ws -keep http://localhost:8888/test?wsdl
手动实现代理调用
需要知道调用的方法实现一个代理接口
package cn.et;
import javax.jws.WebService;
//通过代理方式调用webservice服务
@WebService
public interface Arith {
//这里的方法名和返回值需要与webservice提供的一致
public String arithmetic(int var,int var1,String run);
}
客户端入口
package cn.et;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class Test {
public static void main(String[] args) {
//创建代理工厂类
JaxWsProxyFactoryBean jpfb=new JaxWsProxyFactoryBean();
//添加访问远程webservice地址
jpfb.setAddress("http://192.168.4.142:8090/arith");
//添加代理接口
jpfb.setServiceClass(Arith.class);
//创建代理类
Arith arith = (Arith)jpfb.create();
//调用远程方法
String str = arith.arithmetic(10, 20,"+");
System.out.println(str);
}
}