JAX-WS
基于java本身对webservice的支持进行webservice的开发
1.创建接口SEI(Service Endpoint Interface)
package com.hqh.service; import javax.jws.WebService; @WebService public interface IMyService { public int plus(int a,int b); public int minus(int a,int b); }
2.编写实现类SIB(Service Implements Bean)
package com.hqh.service; import javax.jws.WebService; @WebService(endpointInterface="com.hqh.service.IMyService") //endpointInterface 接入点接口 public class MyServiceImpl implements IMyService { @Override public int plus(int a, int b) { System.out.println("MyServiceImpl.plus()"); return a+b; } @Override public int minus(int a, int b) { System.out.println("MyServiceImpl.minus()"); return a-b; } }
3.发布服务
注意:使用注解配置SEI和SIB
package com.hqh.service; import javax.xml.ws.Endpoint; public class MyServer { public static void main(String[] args) { //对外提供服务的访问地址 String addr = "http://localhost:8888/numberService"; //根据提供的服务地址和服务具体实现类对外发布服务 Endpoint.publish(addr, new MyServiceImpl()); } }
4.访问服务
运行程序,访问如下地址,即可看到wsdl
http://localhost:8888/numberService?wsdl
package com.hqh.service; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; public class MyClient { public static void main(String[] args) throws Exception { //指定wsdl的地址 String wsdlAddr = "http://localhost:8888/numberService?wsdl"; //创建一个指向wsdl文件的URL URL wsdlDocumentLocation = new URL(wsdlAddr); //wsdl的目标命名空间[wsdl中定义的targetNamespace属性] String namespaceURI = "http://service.hqh.com/"; //wsdl的名称[wsdl中定义的name属性] String localPart = "MyServiceImplService"; //服务的名称[通过targetNamespace和name可以定位到一个definitions] QName serviceName = new QName(namespaceURI, localPart); //通过wsdl的URL和QName创建服务对象 Service service = Service.create(wsdlDocumentLocation, serviceName); //关键:xml:wsdl--->class:interface //解析wsdl将转换为一个java接口(这样本地就能通过调用这个接口的方法实现对服务的访问) //注意:IMyService接口 在远程客户端是没有的,这个问题如何解决呢??? IMyService serviceEndpointInterface = service.getPort(IMyService.class); //调用接口中的方法 int retPlus = serviceEndpointInterface.plus(1, 1); System.out.println(retPlus); int retMinus = serviceEndpointInterface.plus(2, 1); System.out.println(retMinus); } }