利用JDK开发调用web service

JavaSE6.0下的Web Service

部分转自:点击打开链接

从JavaSE6.0开始,Java引入了对Web Service的原生支持。我们只需要简单的使用Java的Annotation标签即可将标准的Java方法发布成Web Service。(PS:Java Annotation资料请参考 JDK5.0 Annotation学习笔记(一)

但不是所有的Java类都可以发布成Web Service。Java类若要成为一个实现了Web Service的bean,它需要遵循下边这些原则:
  •  这个类必须是public类
  •  这些类不能是final的或者abstract
  •  这个类必须有一个公共的默认构造函数
  •  这个类绝对不能有finalize()方法

下面我们将通过一个具体的Java Web Service代码例子,配合上述的WSDL文件,讲述如何编写JavaSE6.0的原生Web Service应用。

完整的Java Web Service类代码

Java代码
  1. package org.jsoso.jws.server;  
  2.   
  3. import java.util.ArrayList;  
  4. import javax.jws.WebMethod;  
  5. import javax.jws.WebParam;  
  6. import javax.jws.WebResult;  
  7. import javax.jws.WebService;  
  8. import javax.jws.WebParam.Mode;  
  9. import javax.jws.soap.SOAPBinding;  
  10. /  
  11.  * 提供WebService服务的类  
  12.  */  
  13. @WebService(name="Example", targetNamespace="http://www.jsoso.com/wstest", serviceName="Example")  
  14. @SOAPBinding(style=SOAPBinding.Style.RPC)  
  15. public class Example {  
  16.     private ArrayList<Person> persons = new ArrayList<Person>();;  
  17.     /** 
  18.      *  
  19.      * 返回一个字符串 
  20.      * @param userName 
  21.      * @return 
  22.      */  
  23.     @WebMethod(operationName="toSayHello",action="sayHello",exclude=false)  
  24.     @WebResult(name="returnWord")//自定义该方法返回值在WSDL中相关的描述  
  25.     public String sayHello(@WebParam(name="userName")String userName) {  
  26.         return "Hello:" + userName;  
  27.     }  
  28.   
  29.     /** 
  30.      * web services 方法的返回值与参数的类型不能为接口 
  31.      * @param person 
  32.      * @return 
  33.      * @throws HelloException 
  34.      */  
  35.     @WebMethod(operationName="sayHello", action="sayHello")  
  36.     @WebResult(partName="personList")  
  37.     public Person[] sayHello(@WebParam(partName="person", mode=Mode.IN)Person person,   
  38.             String userName) throws HelloException {  
  39.         if (person == null || person.getName() == null) {  
  40.             throw new HelloException("说hello出错,对像为空。。");  
  41.         }  
  42.         System.out.println(person.getName() + " 对 " + userName + " 说:Hello,我今年" + person.getAge() + "岁");  
  43.         persons.add(person);  
  44.         return persons.toArray(new Person[0]);  
  45.     }  
  46. }  


Annotation 1@WebService(name="Example", targetNamespace="http://www.jsoso.com/wstest", serviceName="Example")
@WebService标签主要将类暴露为WebService,其中targetNamespace属性定义了自己的命名空间,serviceName则定义了< definitions >标签和<service>标签的name属性。

Annotation 2:@SOAPBinding(style=SOAPBinding.Style.RPC)
@SOAPBinding标签定义了WSDL文档中SOAP的消息协议,其中style属性对应SOAP的文档类型,可选的有RPC和DOCUMENT

Annotation 3:@WebMethod(operationName="toSayHello",action="sayHello",exclude=false)
@WebMethod定义Web Service运作的方法,
属性action 对应操作的活动 ,如<soap:operation soapAction="sayHello" />
属性operationName匹配的wsdl:operation 的名称,如<operation name="toSayHello" parameterOrder="userName">
属性exclude 用于阻止将某一继承方法公开为web服务,默认为false

Annotation 4:@WebResult(name="returnWord")
@ WebResult定义方法返回值得名称,如<part name="returnWord" type="xsd:string" />

Annotation 5:@WebParam(partName="person", mode=Mode.IN
@WebParam定义方法的参数名称,如<part name="person" type="tns:person" />,其中mode属性表示参数的流向,可选值有IN / OUT / INOUT

这里要着重说明的是,上述Web Service类的sayHello方法中,带有HelloException这个异常声明,造成该服务类不能直接发布成Web Service。需要使用wsgen工具为其生存异常Bean。关于wsgen工具的使用,请参考wsgen与wsimport命令说明

发布一个的Java Web Service
在完成了上述的Web Service Annotation注释后,我们使用wsgen工具为其进行服务资源文件的构造(这里主要是生成一个名为org.jsoso.jws.server.jaxws.HelloExceptionBean的异常bean类),最后使用以下的类发布Web 服务:
Java代码
  1. package org.jsoso.jws.server;  
  2.   
  3. import java.util.LinkedList;  
  4. import java.util.List;  
  5. import javax.xml.ws.Binding;  
  6. import javax.xml.ws.Endpoint;  
  7. import javax.xml.ws.handler.Handler;  
  8.   
  9. /** 
  10.  * @author zsy 启动web services服务 
  11.  */  
  12. public class StartServer {  
  13.   
  14.     /** 
  15.      * @param args 
  16.      */  
  17.     public static void main(String[] args) {  
  18.         /* 
  19.          * 生成Example 服务实例 
  20.          */  
  21.         Example serverBean = new Example();  
  22.         /* 
  23.          * 发布Web Service到http://localhost:8080/hello地址 
  24.          */  
  25.         Endpoint endpoint =   
  26.            Endpoint.publish("http://localhost:8080/hello", serverBean);  
  27.         Binding binding = endpoint.getBinding();  
  28.         /* 
  29.          * 设置一个SOAP协议处理栈 
  30.          * 这里就简单得打印SOAP的消息文本 
  31.          */  
  32.         List<Handler> handlerChain = new LinkedList<Handler>();  
  33.         handlerChain.add(new TraceHandler());  
  34.         binding.setHandlerChain(handlerChain);  
  35.         System.out.println("服务已启动 http://localhost:8080/hello");  
  36.     }  
  37. }  

在控制台运行这个类,就可以使用URL :http://localhost:8080/hello?wsdl 浏览到上文所描述的WSDL的全文了。这说明您的第一个Web Service应用发布成功!

构建Web Service客户端
使用JavaSE6.0构建Web Service的客户端是一件相当简单的事。这里我们要使用到JDK中的另一个命令行工具wsimport。在控制台下输入以下命令:
引用
wsimport -d ./bin -s ./src -p org.jsoso.jws.client.ref http://localhost:8080/hello?wsdl

即可在包org.jsoso.jws.client.ref中生成客户端的存根及框架文件。其中我们要使用的类只有两个:服务类Example_Service和本地接口Example。编写如下客户端,即可调用Web Service服务:
Java代码
  1. package org.jsoso.jws.client;   
  2.   
  3. import org.jsoso.jws.client.ref.*;   
  4.   
  5. public class RunClient {   
  6.   
  7.     /**  
  8.      * @param args  
  9.      */  
  10.     public static void main(String[] args) {   
  11.         //初始化服务框架类   
  12.         Example_Service service = new Example_Service();   
  13.         //或者本地服务借口的实例   
  14.         Example server = (Example) service.getExamplePort();   
  15.         try {   
  16.             //调用web service的toSayHello方法   
  17.             System.out.println("输入toSayHello的返回值——" + server.toSayHello("阿土"));            
  18.              Person person = new Person();   
  19.              person.setName("阿土");   
  20.              person.setAge(25);   
  21.              //调用web service的sayHello方法   
  22.              server.sayHello(person, "机器人");   
  23.                 
  24.              person = new Person();   
  25.              person.setName("aten");   
  26.              person.setAge(30);   
  27.              //调用web service的sayHello方法   
  28.              PersonArray list = server.sayHello(person, "机器人");   
  29.             //输出返回值   
  30.              System.out.println("/n以下输入sayHello的返回值——");   
  31.             for (Person p : list.getItem()) {   
  32.                 System.out.println(p.getName() + ":" + p.getAge());   
  33.             }              
  34.         } catch (HelloException_Exception e) {   
  35.             e.printStackTrace();   
  36.         }   
  37.     }   
  38. }  

届此,本次Web Service的学习暂告一个段落。Java Web Service是一个相当庞大的知识体系,其中涉及的相关技术较多,这里无法一一道来,我们将会在今后的开发和使用中,同大家做进一步深入的探讨和学习。


附录:wsgen与wsimport命令说明

转自:点击打开链接

The jax-ws tools wsgen and wsimport generate artifacts for easy for web service development, deployment, and invocation. Previously with JAX-RPC, axis 1 etc we had tools like wsdl1java and java2wsdl, but we will only consider jax-ws tools now.

Since we were using simple types till now, it would not have made much difference if we created Publisher and Client using the wsgen and wsimport generated artifacts; however these tools become more useful when we are using complex types and collections in our applications as parameters and return types.

 

The wsimport tool

The wsimport tool reads a WSDL and generates all the required artifacts for web service development, deployment, and invocation. The wsimport tool supports the top-down approach to developing JAX-WS Web services, where you are starting from a wsdl.

The wsimport tool generated JAX-WS portable artifacts include Service Endpoint Interface (SEI), Service, Exception class mapped from wsdl:fault (if any), JAXB generated value types (mapped java classes from schema types) etc. These artifacts can be packaged in a WAR file with the WSDL and schema documents along with the endpoint implementation to be deployed.

 

The wsgen tool

The wsgen tool reads an existing web service implementation class (SIB) and generates the required JAX–WS portable artifacts for web service development and deployment. The wsgen tool can be used for bottoms-up approach, where you are starting from a service endpoint implementation (SIB) rather than a wsdl.

From JAX-WS RI 2.1.4 onwards, you don't have to run wsgen, the runtime takes care of it by generating all required classes dynamically. I am using java 7 which has that version and hence it will generate all classes dynamically when I run the publisher. Even the latest java 6 version (update 37) I have too has the required version and generated the classes on the fly. However compared to java 7, java 6 gave a INFO message that these classes were dynamically created.

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值