webService 实现原理

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);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值