zoukankan      html  css  js  c++  java
  • 调用webService的几种方式

    转自:http://blog.csdn.net/u011165335/article/details/51345224

    一、概览

    方式1:

    HttpClient:可以用来调用webservie服务,也可以抓取网页数据

    版本1:HttpClient3.0.x

    版本2:HttpClient4.x.x(目前最新4.5.2)

    这2个版本的使用方式不一样;变动较大

    方式2:纯Java(自带API)      jws

    方式3:cxf框架

    方式4:axis2框架

    准备工作:

    1.了解wsimport        java自带的一个命令(建议使用jdk7,稳定支持)

    作用:将wsdl文件生成本地代理(java代码),方便调用

    语法  wsimport [opations] <wsdl_uri>
        - wsdl_uri:wsdl 的统一资源标识符
        - d  :指定要输出的文件的位置
        - s  :表示要解析java的源码 ,默认解析出的是class字节码 
        - p  : 指定输出的包名
     
    1. 获取服务路径:比如
      http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL


    2. 获取wsdl文件.建议使用JDK1.6以上的版本的wsimport命令


    进入dos的桌面:
    方式1:wsimport http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL
    这种默认只会生成class,且会生成默认的包
    方式2:生成源码,指定包和路径
    wsimport -s ./ -p cn.aa http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL


    3.可以把class文件打成jar包 jar cvf  test.jar  打包目录

    4.放在你的项目中进行调用:

    [html] view plain copy
     
    1. public static void main(String[] args) {  
    2.         MobileCodeWS mobileCodeWs=new MobileCodeWS();  
    3.         MobileCodeWSSoap mobileCodeWSSoap=mobileCodeWs.getMobileCodeWSSoap();  
    4.         String tel=mobileCodeWSSoap.getMobileCodeInfo("183735xxxx",null);  
    5.         System.out.println(tel);  
    6.     }  



    2.规范了解

    JAVA 中共有三种WebService 规范,分别是JAX-WS(JAX-RPC)、JAXM&SAAJ、JAX-RS。

    1. Jaxws(掌握)

    JAX-WS  的全称为 Java API for XML-Based Webservices ,早期的基于SOAP 的JAVA 的Web 服务规范JAX-RPC(java API For XML-RemoteProcedure Call)目前已经被JAX-WS 规范取代。从java5开始支持JAX-WS2.0版本,Jdk1.6.0_13以后的版本支持2.1版本,jdk1.7支持2.2版本。

     Jaxws开发的webservice传输soap协议。

    2JAXM&SAAJ(了解)

    JAXM(JAVA API For XML Message)主要定义了包含了发送和接收消息所需的API,SAAJ(SOAP With Attachment APIFor Java,JSR 67)是与JAXM 搭配使用的API,为构建SOAP 包和解析SOAP 包提供了重要的支持,支持附件传输等,JAXM&SAAJ 与JAX-WS 都是基于SOAP 的Web 服务,相比之下JAXM&SAAJ 暴漏了SOAP更多的底层细节,编码比较麻烦,而JAX-WS 更加抽象,隐藏了更多的细节,更加面向对象,实现起来你基本上不需要关心SOAP 的任何细节

    3.  JAX-RS(掌握)

    JAX-RS 是JAVA 针对REST(Representation State Transfer)风格制定的一套Web 服务规范,由于推出的较晚,该规范(JSR 311,目前JAX-RS 的版本为1.0)并未随JDK1.6 一起发行。

    Rest定义可以自行搜索

     jax-RS可以发布 rest风格webservice,因为rest的webservice不采用soap传输,直接采用http传输,可以返回xml或json,比较轻量。

    以后可能会流行Rest风格的

    二、简单例子

    1.httpClient3.x.x   

    此方式不需要wsimport命令

    [html] view plain copy
     
    1. // 通过Http-Client 框架来模拟实现 Http请求--get  
    2.     public static String getMobileCodeInfo1(String mobileCode, String userID)  
    3.             throws HttpException, IOException {  
    4.         HttpClient client = new HttpClient();  
    5.         GetMethod getMethod=new GetMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode="  
    6.                 + mobileCode + "&userID=" + userID);  
    7.           
    8.         //执行,得到消息码  
    9.         int code = client.executeMethod(getMethod);  
    10.         System.out.println("消息码:"+code);  
    11.         String result="";  
    12.         if (code==HttpURLConnection.HTTP_OK) {  
    13.             //得到执行结果  
    14.              result = getMethod.getResponseBodyAsString();  
    15.             System.out.println(result);  
    16.         }  
    17.           
    18.        return result;  
    19.     }  
    20.   
    21.   
    22.     // 通过Http-Client 框架来模拟实现 Http请求--post  
    23.     // 需要导入3个jar包,本demo的jar包版本是3.1.0  
    24.     // 目前最新的是4.5.2,使用方式也发生了变化  
    25.     public static String getMobileCodeInfo2(String mobileCode, String userID)  
    26.             throws HttpException, IOException {  
    27.   
    28.         // 输入服务网址  
    29.         HttpClient client = new HttpClient();  
    30.         // GetMethod  
    31.         PostMethod post = new PostMethod(  
    32.                 "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");  
    33.         // 设置参数  
    34.         post.setParameter("mobileCode", mobileCode);  
    35.         post.setParameter("userID", userID);  
    36.         // client.setTimeout(newTimeoutInMilliseconds);  
    37.   
    38.         // 执行,返回一个结果码  
    39.         int code = client.executeMethod(post);  
    40.            
    41.         System.out.println("结果码:" + code);  
    42.         // 获取xml结果  
    43.         String result = post.getResponseBodyAsString();  
    44.         System.out.println("结果:" + result);  
    45.         //释放连接  
    46.         post.releaseConnection();  
    47.         return result;  
    48.     }  
    49.   
    50.     // Post请求 :通过Http-Client 框架来模拟实现 Http请求  
    51.     //从xml中获取请求参数  
    52.     //SOAP1.1方式  
    53.     //问题:soap怎么定义,这里已经返回接结果,但是没有手机号信息,也就返回的结果匹配,不知道为什么  
    54.     //估计是配置文件有问题  
    55.   
    56.       
    57.     //soap1.1  
    58.     @Test  
    59.     public void soap() throws Exception{  
    60.   
    61.         HttpClient client=new HttpClient();  
    62.         PostMethod postMethod=new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");  
    63.         //3.设置请求参数  
    64.           postMethod.setRequestBody(new FileInputStream("D:/soap.xml")); //文件名自定义  
    65.           //修改请求的头部  
    66.           postMethod.setRequestHeader("Content-Type", "text/xml; charset=utf-8");  
    67.         //4.执行请求 ,结果码  
    68.         int code=client.executeMethod(postMethod);  
    69.         System.out.println("结果码:"+code);  
    70.         //5. 获取结果  
    71.         String result=postMethod.getResponseBodyAsString();  
    72.         System.out.println("Post请求的结果:"+result);  
    73.     }  
    74.   
    75.     public static void main(String[] args) throws IOException {  
    76.         // getMobileInfo("13476699xxx", "");  
    77.         getMobileCodeInfo1("13476699xxx", "");//  
    78. //      getMobileCodeInfo2("13476699xxx", "");//   
    79.         //soap,利用xml传输参数  
    80.     }  

    其中:请求参数封装在soap.xml中

    请求规范服务方会提供给你的

    soap.xml请求内容如下:

    [html] view plain copy
     
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">  
    3.   <soap:Body>  
    4.     <getMobileCodeInfo xmlns="http://WebXml.com.cn/">  
    5.       <mobileCode>1347669xxxx</mobileCode>  
    6.       <userID></userID>  
    7.     </getMobileCodeInfo>  
    8.   </soap:Body>  
    9. </soap:Envelope>  

    httpClient4.x.x不做演示,感兴趣的可以去查查,资料很多


    2.java自带API实现

         2.1 类发布

              2.1.1 使用默认设置

    [html] view plain copy
     
    1. @WebService  
    2. //默认服务名会加上Service  
    3. public class PhoneInfoWS {  
    4.       //默认方法名getPhoneInfo  
    5.      //默认参数名arg0  
    6.     //默认返回值名字:return  
    7.     //targetNamespace默认情况下为倒置的包名  
    8.       public Phone getPhoneInfo(String OSName) {  
    9.           Phone p=new Phone();  
    10.         if ("Android".equalsIgnoreCase(OSName)) {  
    11.             p.setOS(OSName);  
    12.             p.setOwn("Google");  
    13.             p.setScale(80);  
    14.         }else if("IOS".equalsIgnoreCase(OSName)){  
    15.             p.setOS(OSName);  
    16.             p.setOwn("Apple");  
    17.             p.setScale(14);  
    18.         }else if("windows Phone".equalsIgnoreCase(OSName)){  
    19.             p.setOS(OSName);  
    20.             p.setOwn("Microsoft");  
    21.             p.setScale(4);  
    22.         }else{  
    23.             p.setOS("others");  
    24.             p.setOwn("others");  
    25.             p.setScale(2);  
    26.         }  
    27.         return p;  
    28.     }  
    29.         
    30.         
    31.       //静态,非public方法不会被自动发布  
    32.       public static String say(String city){  
    33.           return "hello"+city;  
    34.       }  
    35.         
    36.       //访问时自动生成一个描述文件xml+xsd约束文件  
    37.       public static void main(String[] args) {  
    38.           //implementor要发布的对象,一般是接口的实现类  
    39.          String address1="http://127.0.0.1/PhoneInfoWS1?WSDL";  
    40.         // String address2="http://127.0.0.1/PhoneInfoWS2?WSDL";  
    41.          Endpoint point = Endpoint.publish(address1, new PhoneInfoWS());  
    42.          Endpoint.publish(address1, new PhoneInfoWS());  
    43.     //   Endpoint.publish(address2, new PhoneInfoWS());  
    44.            
    45.          //关闭发布  
    46. //       point.stop();  
    47.           
    48.            
    49.     }  
    50. }  

       2.1.2自定义设置

      

    [html] view plain copy
     
    1. @WebService(serviceName="PhoneInfoService",targetNamespace="http://PhoneService.web.com/")  
    2. //默认服务名会加上Service  
    3. public class PhoneInfoWS1 {  
    4.       @WebMethod(operationName="getPhoneInfo")  
    5.       public @WebResult(name="phone") Phone getPhoneInfo(@WebParam(name="OSName") String OSName) {  
    6.           Phone p=new Phone();  
    7.         if ("Android".equalsIgnoreCase(OSName)) {  
    8.             p.setOS(OSName);  
    9.             p.setOwn("Google");  
    10.             p.setScale(80);  
    11.         }else if("IOS".equalsIgnoreCase(OSName)){  
    12.             p.setOS(OSName);  
    13.             p.setOwn("Apple");  
    14.             p.setScale(14);  
    15.         }else if("windows Phone".equalsIgnoreCase(OSName)){  
    16.             p.setOS(OSName);  
    17.             p.setOwn("Microsoft");  
    18.             p.setScale(4);  
    19.         }else{  
    20.             p.setOS("others");  
    21.             p.setOwn("others");  
    22.             p.setScale(2);  
    23.         }  
    24.         return p;  
    25.     }  
    26.         
    27.         
    28.       //静态,非public方法不会被自动发布  
    29.       public static String say(String city){  
    30.           return "hello"+city;  
    31.       }  
    32.         
    33.       //屏蔽要发布的方法  
    34.       @WebMethod(exclude=true)  
    35.       public  String say1(String city){  
    36.           return "hello"+city;  
    37.       }  
    38.       public  String say2(String city){  
    39.           return "hello"+city;  
    40.       }  
    41.         
    42.         
    43.       //访问时自动生成一个描述文件xml+xsd约束文件  
    44.       public static void main(String[] args) {  
    45.           //implementor要发布的对象,一般是接口的实现类  
    46.          String address1="http://127.0.0.1/PhoneInfoWS1?WSDL";  
    47. //       String address2="http://127.0.0.1/PhoneInfoWS2?WSDL";  
    48.          Endpoint point = Endpoint.publish(address1, new PhoneInfoWS1());  
    49.          point.toString();  
    50.          Endpoint.publish(address1, new PhoneInfoWS1());  
    51. //       Endpoint.publish(address2, new PhoneInfoWS1());  
    52.            
    53.          //关闭发布  
    54. //       point.stop();  
    55.           
    56.            
    57.     }  
    58. }  

    注意:

    1.  在类上添加@WebService注解,代表发布一个WebService服务
    2. 通过EndPoint(端点服务)发布一个webService。Endpoint也是jdk提供的一个专门用于发布服务的类,它的publish方法接收两个参数,
                     一个是本地的服务地址,二是提供服务的类。它位于javax.xml.ws.*包中。
    3. Endpoint.publish(String address, Object implementor) 静态方法在给定地址处针对指定的实现者对象创建并发布端点
    4. 默认public修饰的方法自动发布,静态方法不会公布
    5. 如果希望某个方法不对外公开,可以在方法上添加@WebMethod(exclude=true),阻止对外公开。
    6. 如果一个类上,被添加了@WebService注解,则必须此类至少有一个可以公开的方法,否则将会启动失败。

    7.异常处理:
    报错:
     com.sun.xml.internal.ws.model.RuntimeModelerException: runtime modeler error: Wrapper class com.web.PhoneService.jaxws.GetPhoneInfo is not found. 
     Have you run APT to generate them?
    解决办法:jdk7就可以了

    8.测试方法:

        a.利用上面说的wsimport生成本地代理,然后调用里面的代码进行测试就可以了,这里就省略了

        b.更方便的测试是使用Eclipse的Web Services Explorer 或者Myeclipse的SOAP Web Services Explorer进行测试

           把链接:比如 http://127.0.0.1/PhoneInfoWS1?WSDL 放入到浏览器的WSDL地址栏就可以了

         2.2接口发布

    [html] view plain copy
     
    1. @WebService  
    2. public interface JobService {  
    3.    public String getJobInfo();  
    4. }  
    5.   
    6. /*  
    7.  * 默认只会发布接口的方法,实现类自定义的方法不会被发布了  
    8.  * 接口和实现类都需要加注解修饰  
    9.  *   
    10.  * 联想Spring的注入只需在实现类加入注解即可  
    11.  */  
    12. @WebService(serviceName="JobServiceImplService",  
    13. endpointInterface="com.web.InterfaceService.JobService")  
    14. public class JobServiceImpl implements JobService{  
    15.   
    16.     @Override  
    17.     public String getJobInfo() {  
    18.         // TODO Auto-generated method stub  
    19.         return "java开发|前端开发|数据库开发";  
    20.     }  
    21.       
    22. //  实现类自定义的方法不会被发布  
    23.     public String say(String name){  
    24.         return "hello "+name;  
    25.     }  
    26.       
    27.       
    28.     public static void main(String[] args) {  
    29.         String address="http://127.0.0.1/JobServiceImpl?WSDL";  
    30.         Endpoint.publish(address, new JobServiceImpl());  
    31.         System.out.println(address);  
    32.     }  
    33.   
    34. }  



    3.CXF框架

        Apache CXF 是一个开源的 Services 框架,是XFire和Celtix项目的结合产品,CXF 帮助您来构建和开发 Services 这些 Services 可以支持多种协议,比如:SOAP、POST/HTTP、RESTful HTTP CXF 大大简化了 Service可以天然地和 spring 进行无缝集成。

    3.1最简单的接口发布

    这里先不与Spring集成,需要的jar包

    asm-3.3.jar
    commons-logging-1.1.1.jar
    cxf-2.4.2.jar
    jetty-continuation-7.4.5.v20110725.jar
    jetty-http-7.4.5.v20110725.jar
    jetty-io-7.4.5.v20110725.jar
    jetty-security-7.4.5.v20110725.jar
    jetty-server-7.4.5.v20110725.jar
    jetty-util-7.4.5.v20110725.jar
    neethi-3.0.1.jar
    wsdl4j-1.6.2.jar
    xmlschema-core-2.0.jar

    这里用的是2.4.2的,老版本,不要介意,最新版本3.1.6,可以自行下载

    [html] view plain copy
     
    1. @WebService  
    2. //声明soap1.2  
    3. //@BindingType(value=SOAPBinding.SOAP12HTTP_BINDING)  
    4.   
    5. public interface LanguageService {  
    6.   
    7.     public  String getLanguage(int num);  
    8.   
    9. }  
    10.   
    11. //开发语言排行榜  
    12. @WebService  
    13. public class LanguageServiceImpl implements LanguageService {  
    14.     
    15.     @Override  
    16.     public String getLanguage(int num) {  
    17.         String language="";  
    18.         switch (num) {  
    19.         case 1:  
    20.             language="java语言";  
    21.             break;  
    22.         case 2:  
    23.             language="C语言";  
    24.             break;  
    25.         case 3:  
    26.             language="Objective-C语言";  
    27.             break;  
    28.         case 4:  
    29.             language="C#语言";  
    30.             break;  
    31.         default:  
    32.             language="没有找到你要排名的语言";  
    33.             break;  
    34.         }  
    35.         return language;  
    36.     }  
    37.       
    38.     /*  
    39.      * 方式1:ServerFactoryBean  
    40.      * 不支持注解,就算你添加了注解也不起作用  
    41.      * 所以你不能修改服务名,方法名,参数名,工作空间等  
    42.      * 另外不支持拦截器  
    43.      * 方式2:JaxWsServerFactoryBean为ServerFactoryBean的子类(功能扩展)  
    44.      * 特点:  
    45.      * 1、支持注解,如果你没有使用@webService,运行后,是不会发布方法的。。,所以注解必须加  
    46.      * 如果有接口实现,只需要在接口加上注解即可,命名注解也要在接口里面做  
    47.      * 这跟之前的纯java开发webservice有些不一样,纯java开发接口和实现类要改名必须都加上注解才行  
    48.      * 2、支持拦截器  
    49.      * 3、生成的wsdl更加规范  
    50.      * 两者的wsdl区别:  
    51.      *     a.方式1 默认不加servcie  方式2:默认加Service,比如<wsdl:definitions name="LanguageServiceService"   
    52.      *     b.方式1 元素前缀 xsd    方式2 元素前缀xs  
    53.      *     c.方式1   
    54.              <wsdl:portType name="LanguageServicePortType">  
    55.              方式2  
    56.              <wsdl:portType name="LanguageService">没有加PortType  
    57.                
    58.         webService访问流程:  
    59.         1.首先进行握手,检查本地代理与服务端的wsdl是否一致,采用的是get请求验证  
    60.         2.采用post请求,封装请求参数到xml中,采用soap通信,将这个请求xml传输到服务端  
    61.         3.封装结果为xml,采用soap通信返回xml,再到客户端解析得到方法的返回值  
    62.      */  
    63.       
    64.       
    65.     //方式1:不通过注解发布  
    66.     //这种方式没有添加webService注解,也就是说没有注解也可以发布webService服务,  
    67. //    但是这种方式不是很规范,比如我们不可以通过注解的方式来修改WSDL的标签信息  
    68.     private static void publishServie1(){  
    69.         LanguageService languageService=new LanguageServiceImpl();  
    70.         ServerFactoryBean bean=new ServerFactoryBean();  
    71.         //Endpoint :地址  , 实现对象  
    72. //      bean.setAddress("http://192.168.8.178:9999/ws/cxf/languangeService");  
    73.         bean.setAddress("http://127.0.0.1:9999/ws/cxf/languangeService?WSDL");  
    74.         //注册服务器地址和端口  
    75.         bean.setServiceClass(LanguageService.class);//对外提供webservcie的业务类或者接口  
    76.         //注册哪个实现类提供服务  
    77.         bean.setServiceBean(languageService);//服务的实现bean  
    78.         Server server = bean.create();//创建,发布webservice  
    79.         //10秒有效  
    80. //      Thread.sleep(1*10*1000);  
    81. //      server.stop();  
    82. //      System.exit(0);  
    83.     }  
    84.       
    85.       
    86.     //JaxWsServerFactoryBean是ServerFactoryBean的子类  
    87.     //可以提供拦截器  
    88.     private static void publishServie2(){  
    89.         JaxWsServerFactoryBean bean=new JaxWsServerFactoryBean();  
    90.         //地址WSDL加不加都可以,访问时加上就可以了,不加端口也可以发布  
    91.         bean.setAddress("http://127.0.0.1:8888/ws/cxf/languangeService?WSDL");  
    92. //      bean.setAddress("http://127.0.0.1/ws/cxf/languangeService?WSDL");  
    93.         //设置服务接口  
    94.         bean.setServiceClass(LanguageService.class);  
    95.         //设置服务的类  
    96.         bean.setServiceBean(new LanguageServiceImpl());  
    97.           
    98.         //输入信息拦截器  
    99.         bean.getInInterceptors().add(new LoggingInInterceptor());  
    100.         //输出信息拦截器  
    101.         bean.getOutInterceptors().add(new LoggingOutInterceptor());  
    102.           
    103.         Server server = bean.create();  
    104.     }  
    105.       
    106.     public static void main(String[] args) throws Exception{  
    107. //      publishServie1();  
    108.         publishServie2();  
    109.     }  
    110. }  


    3.2 结合Spring发布服务

          这里重点是如何配置发布服务,业务逻辑仅仅是演示(辅助),不必参考

         要发布的服务:保存和根据姓名查询员工

        saveEmployee          findEmployeeByName

        步骤:

           3.2.1.导包cxf2.7.18里面的所有jar包 ,其中jetty包不需要,因为应用是部署在tomcat里面

           3.2. 2.建实体类,DB类(模拟)

        

    [html] view plain copy
     
    1. public class Employee {  
    2.     private String name;  
    3.     private Integer age;  
    4.       
    5.     @DateTimeFormat(pattern="yyyy-MM-dd")  
    6.     private Date birthday;  
    7.   
    8.     public Employee() {  
    9.         super();  
    10.     }  
    11.   
    12.     public Employee(String name, Integer age, Date birthday) {  
    13.         super();  
    14.         this.name = name;  
    15.         this.age = age;  
    16.         this.birthday = birthday;  
    17.     }  
    18.   
    19.     public String getName() {  
    20.         return name;  
    21.     }  
    22.   
    23.     public void setName(String name) {  
    24.         this.name = name;  
    25.     }  
    26.   
    27.     public Integer getAge() {  
    28.         return age;  
    29.     }  
    30.   
    31.     public void setAge(Integer age) {  
    32.         this.age = age;  
    33.     }  
    34.   
    35.     public Date getBirthday() {  
    36.         return birthday;  
    37.     }  
    38.   
    39.     public void setBirthday(Date birthday) {  
    40.         this.birthday = birthday;  
    41.     }  
    42.   
    43.     @Override  
    44.     public String toString() {  
    45.         return "Employee [name=" + name + ", age=" + age + ", birthday="  
    46.                 + birthday + "]";  
    47.     }  
    48.   
    49. }  
    [html] view plain copy
     
    1. //运行时如果报错Unsupported major.minor version 51.0  
    2. //这说明jdk版本不对,即tomcat的jdk版本跟项目版本不一致  
    3. @Repository  
    4. public class EmployeeDB {  
    5.     public EmployeeDB(){}  
    6.    private static List<Employeelist=new ArrayList<Employee>();  
    7.       
    8.     static{  
    9.         list.add(new  Employee("小米", 12, new Date()));  
    10.     }  
    11.       
    12.     public void save(Employee employee){  
    13.         list.add(employee);  
    14.     }  
    15.       
    16.     public Employee findByName(String name){  
    17.           
    18.         if (list.size()>0) {  
    19.             for(Employee e:list){  
    20.                 if (e.getName().equals(name)) {  
    21.                     return e;  
    22.                 }  
    23.             }  
    24.         }  
    25.         return null;  
    26.     }  
    27.       
    28.     public List<Employee> findAll(){  
    29.         return list;  
    30.     }  
    31.       
    32.       
    33.     public void deleteByName(String name) throws Exception{  
    34.         if (name.length()==0||name==null) {  
    35.           throw new Exception("删除用户异常");  
    36.         }  
    37.           
    38.         for (int i = 0; i list.size(); i++) {  
    39.             if (name.equals(list.get(i).getName())) {  
    40.                 list.remove(list.get(i));  
    41.                 break;  
    42.             }  
    43.         }  
    44.     }  
    45. }   


        3.2.3.建立服务类

        

    [html] view plain copy
     
    1. @WebService(serviceName="EmployeeService")  
    2. public interface EmployeeService {  
    3.       
    4.    public void saveEmployee(@WebParam(name="employee")Employee employee );  
    5.      
    6.    public @WebResult(name="Employee")Employee  findEmployeeByName(@WebParam(name="name")String name);  
    7. }  
    8.   
    9.   
    10. public class EmployeeServiceImpl implements EmployeeService{  
    11.   
    12.     @Autowired  
    13.     private EmployeeDB db;  
    14.       
    15.     @Override  
    16.     public void saveEmployee(Employee employee) {  
    17.         System.out.println("EmployeeDB:"+db);  
    18.         db.save(employee);  
    19.     }  
    20.   
    21.     @Override  
    22.     public Employee findEmployeeByName(String name) {  
    23.         if (name.length()==0||name==null) {  
    24.             return null;  
    25.         }  
    26.           
    27.         return  db.findByName(name);  
    28.     }  
    29.   
    30. }  

     3.2. 4.写页面,写Servlet(如果单纯为了测试发布的服务,这些可以不需要)

       

    [html] view plain copy
     
    1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
    2.   
    3.   
    4. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    5. <html>  
    6.   <head>  
    7.       
    8.     <title>添加员工</title>  
    9.     <meta http-equiv="pragma" content="no-cache">  
    10.     <meta http-equiv="cache-control" content="no-cache">  
    11.     <meta http-equiv="expires" content="0">      
    12.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    13.     <meta http-equiv="description" content="This is my page">  
    14.     <!-- 
    15.     <link rel="stylesheet" type="text/css" href="styles.css"> 
    16.     -->  
    17.   </head>  
    18.     
    19.   <body>  
    20.        <form action="${pageContext.request.contextPath}/AddServlet" method="post">  
    21.             用户名:<input type="text" name="name" /><br/>  
    22.             年龄:<input type="text" name="age" /><br/>  
    23.             生日:<input type="text" name="birthday" /><br/>  
    24.             <input type="submit" value="提交" />  
    25.       </form>  
    26.   
    27.   </body>  
    28. </html>  
    [html] view plain copy
     
    1. public class AddServlet extends HttpServlet {  
    2.   
    3.     private EmployeeService employeeService;  
    4.       
    5.     @Override  
    6.     public void init() throws ServletException {  
    7.         WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());  
    8.         //得到的是实现类对象  
    9.         employeeService=(EmployeeService) context.getBean("employeeService");  
    10.         System.out.println("employeeService:"+employeeService);  
    11.     }  
    12.       
    13.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
    14.             throws ServletException, IOException {  
    15.         response.setContentType("text/html;charset=utf-8");  
    16.         String name=request.getParameter("name");  
    17.         String age=request.getParameter("age");  
    18.         String birthday=request.getParameter("birthday");  
    19.           
    20.           
    21.         Employee employee=new Employee();  
    22.         employee.setName(name);  
    23.         employee.setAge(Integer.parseInt(age));  
    24.         employee.setBirthday(DateUtil.stringToDate(birthday, "yyyy-MM-dd"));  
    25.           
    26.         employeeService.saveEmployee(employee);  
    27.           
    28.         //检查是否存进去进去了  
    29.         EmployeeDB db=new EmployeeDB();  
    30.         System.out.println("db.size():"+db.findAll().size());  
    31.     }  
    32.   
    33.   
    34.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
    35.             throws ServletException, IOException {  
    36.          doGet(request, response);    
    37.     }  
    38.       
    39.       
    40. }  

    3.2.5.配置applicationContext.xml和web.xml

    [html] view plain copy
     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans  
    3.     xmlns="http://www.springframework.org/schema/beans"  
    4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    5.     xmlns:p="http://www.springframework.org/schema/p"  
    6.       xmlns:context="http://www.springframework.org/schema/context"  
    7.       xmlns:jaxws="http://cxf.apache.org/jaxws"  
    8.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
    9.     http://www.springframework.org/schema/context  
    10.     http://www.springframework.org/schema/context/spring-context.xsd  
    11.     http://cxf.apache.org/jaxws   
    12.     http://cxf.apache.org/schemas/jaxws.xsd">  
    13.       
    14. <context:component-scan base-package="com.demo.*"></context:component-scan>  
    15.   
    16. <bean id="employeeService"  class="com.demo.webService.EmployeeServiceImpl"></bean>  
    17.   
    18.   
    19.   <!-- 配置cxf     
    20.      地址:    比如:  http://192.168.114.10:8080/CXF_Server/ws/employeeManager  
    21.      组成 :           http://192.168.114.10:8080 +CXF_Server( 项目名)+ws(过滤的路径)+/employeeManager(自定义部分)  
    22.      服务类 :  
    23.      服务的实现类:  
    24.      拦截器    
    25.    -->  
    26.      
    27.      
    28.    <jaxws:server serviceClass="com.demo.webService.EmployeeService" address="/employeeService">  
    29.         <jaxws:serviceBean>  
    30.            <ref bean="employeeService"/>  
    31.         </jaxws:serviceBean>  
    32.        <jaxws:inInterceptors>  
    33.           <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>  
    34.        </jaxws:inInterceptors>  
    35.          
    36.        <jaxws:outInterceptors>  
    37.           <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>  
    38.         </jaxws:outInterceptors>  
    39.    </jaxws:server>  
    40. </beans>  

    web.xml

    [html] view plain copy
     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
    3.   <display-name>CXFDemo1</display-name>  
    4.   <welcome-file-list>  
    5.     <welcome-file>index.jsp</welcome-file>  
    6.   </welcome-file-list>  
    7.     
    8. <!--   配置CXF的Servlet,用来处理webService的请求 -->  
    9.   <servlet>  
    10.     <servlet-name>cxf</servlet-name>  
    11.     <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
    12.     <load-on-startup>1</load-on-startup>  
    13.   </servlet>  
    14.   <servlet>  
    15.     <servlet-name>AddServlet</servlet-name>  
    16.     <servlet-class>com.demo.web.AddServlet</servlet-class>  
    17.   </servlet>  
    18.   
    19.     
    20.   <servlet-mapping>  
    21.      <servlet-name>cxf</servlet-name>  
    22.      <url-pattern>/ws/*</url-pattern>  
    23.   </servlet-mapping>  
    24.     
    25.     
    26.   <servlet-mapping>  
    27.     <servlet-name>AddServlet</servlet-name>  
    28.     <url-pattern>/AddServlet</url-pattern>  
    29.   </servlet-mapping>  
    30.     
    31.   <listener>  
    32.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    33.   </listener>  
    34.   <context-param>  
    35.     <param-name>contextConfigLocation</param-name>  
    36.     <param-value>classpath:applicationContext.xml</param-value>  
    37.   </context-param>  
    38. </web-app>  

    3.2.6.工具类

    [html] view plain copy
     
    1. public class DateUtil {  
    2.   
    3.     private DateUtil() {  
    4.     }  
    5.   
    6.     public static String dateToString(Date d, String format) {  
    7.   
    8.         return new SimpleDateFormat(format).format(d);  
    9.     }  
    10.       
    11.     public static Date stringToDate(String s, String format) {  
    12.         try {  
    13.             return new SimpleDateFormat(format).parse(s);  
    14.         } catch (ParseException e) {  
    15.             e.printStackTrace();  
    16.         }  
    17.         return null;  
    18.     }  
    19.   
    20. }  

    3.2.7.访问:http://localhost:8080/CXFDemo2/ws


    4.Axis2发布服务

        4.1比较

        Axis2是从Axis1.x系列发展而来。CXF则是XFire和Celtix项目的结合产品。Axis2是从底层全部重新实现,使用了新的扩展性更好模块架构。 CXF也重新的深化了XFire和Celtix这两个开发工具。
    1.CXF支持 WS-Addressing,WS-Policy, WS-RM, WS-Security和WS-I Basic Profile。Axis2不支持WS-Policy,现在应该支持了。
    2. CXF可以很好支持Spring。Axis2不能(没测试过,现在应该可以吧,待测。。)
    3. AXIS2支持更广泛的数据并对,如XMLBeans,JiBX,JaxMe和JaxBRI和它自定义的数据绑定ADB。注意JaxME和JaxBRI都还是试验性的。CXF只支持JAXB和Aegis。
    4. Axis2支持多语言-除了Java,他还支持C/C++版本
    如何抉择: 
    1、如果应用程序需要多语言的支持,Axis2 应当是首选了; 
    2、如果应用程序是遵循 Spring 哲学路线的话,Apache CXF 是一种更好的选择,特别对嵌入式的 Web Services 来说; 

       

    目前asix2最新版本1.7.1

        4.2安装插件

         4.2.1Eclipse

         axis2-eclipse-codegen-plugin-1.7.1.zip
         axis2-eclipse-service-plugin-1.7.1.zip

         解压的jar包放入Eclipse的dropins目录

         4.2.2Myeclipse

         axis2-eclipse-codegen-wizard.zip
         axis2-eclipse-service-archiver-wizard.zip
         解压放入到Myeclipse的dropins目录

        4.3  实现方式有很多

       这里简单说明下最快速的2种方式,Eclipse实现

         方式1:不使用插件实现

             1.配置环境变量(不是必须的)

           

              2.配置webService环境

           

           

             2.建立一个动态web项目

           

            

        

       

       

         方式2:使用插件实现

         建一个普通的动态项目,不选择webService环境

         这个实现网上有很多,实现参考:http://blog.csdn.NET/wangchangpen62/article/details/45171001

         好了,先写到这吧

         以上做了个简单的小结,深入应用还待学习。。。。

  • 相关阅读:
    Mac 自带 apache 服务器
    比较器Comparable Comparator
    深入学习二叉树(01)完全二叉树
    深入学习二叉树(02)线索二叉树
    深入学习二叉树(06)霍夫曼树/哈夫曼编码/最优二叉树
    深入学习二叉树(05)红黑树
    深入学习二叉树(07)B树
    Java 1.8 红黑树
    ConcurrentHashMap 结构 1.7 与1.8
    git 操作详情
  • 原文地址:https://www.cnblogs.com/xiaohouzai/p/7287710.html
Copyright © 2011-2022 走看看