WebService:JAX-WS实现WebService
? ? ? ? WebService和Java核心技术中的RMI一样用于实现异构平台上的应用程序之间数据的交互,唯一不同的是这种技术屏蔽了语言之间的差异,这也是其大行其道的原因。实现WebService的技术多种多样,可以使用JAX-WS、CXF、Axis2或Metro等方式实现WebService,接下来会给大家展示如何使用不同的方式实现WebService,本篇博客为大家演示如何使用JAX-WS实现WebService: ? ? ? ? 一、创建WebService服务器端: ? ? ? ? 1、新建一个名为“server”的Java工程; ? ? ? ? 2、创建IComputeService接口,代码如下: package com.ghj.service; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; /** * SEI Service Endpoint Interface 发布的服务接口 * * @author GaoHuanjie */ @WebService @SOAPBinding(style=SOAPBinding.Style.RPC) public interface IComputeService { public int add(int a,int b); } ? ? ? ? 3、创建IComputeService接口实现类ComputeService,代码如下: package com.ghj.service.impl; import javax.jws.WebService; import com.ghj.service.IComputeService; /** * SIB Service Implemention Bean * * @author GaoHuanjie */ //endpointInterface指定接入点接口:接口必须存在 @WebService(endpointInterface="com.ghj.service.IComputeService") public class ComputeService implements IComputeService{ @Override public int add(int a,int b) { System.out.println(a+"+"+b+"="+(a+b)); return a+b; } } ? ? ? ? 4、创建启动服务器端服务的类StartServer,代码如下: package com.ghj.server; import javax.xml.ws.Endpoint; import com.ghj.service.impl.ComputeService; /** * 启动服务器端服务 * * @author GaoHuanjie */ public class StartServer { public static void main(String[] args) { String address = "http://localhost:8888/compute"; Endpoint.publish(address,new ComputeService()); } } ? ? ? ? 二、创建WebService客户端: ? ? ? ? 1、新建一个名为“client”的Java工程; ? ? ? ? 2、将“server”工程中的IComputeService接口拷贝到“client”工程中; ? ? ? ? 3、创建调用“server”工程IComputeService接口实现类的代码,代码如下: package com.ghj.client; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import com.ghj.service.IComputeService; public class Client { public static void main(String[] args) { try { URL url = new URL("http://localhost:8888/compute?wsdl");//创建访问wsdl服务地址的url QName sname = new QName("http://impl.service.ghj.com/","ComputeServiceService");//通过Qname指明服务的具体信息,其参数值与本工程中的1.png图 Service service = Service.create(url,sname);//创建服务 IComputeService computeService = service.getPort(IComputeService.class);//实现接口 System.out.println(computeService.add(12,33)); } catch (MalformedURLException e) { e.printStackTrace(); } } } ? ? ? ? 三、运行WebService: ? ? ? ? 1、运行“server”工程中的StartServer类; ? ? ? ? 2、运行“client”工程中的Client类; ? ? ? ? 【0分下载资源】 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |