WebService知識(shí)整理

WebService學(xué)習(xí)筆記

友情提示,本文檔的圖床使用極簡圖床進(jìn)行圖片存儲(chǔ),默認(rèn)存儲(chǔ)到七牛云空間

本學(xué)習(xí)貼是根據(jù)blog.java1234.com.cn的webservice視頻教程整理和總結(jié)的,多處引用了Java1234_小鋒老師的原文,感謝小峰老師的開源精神.致敬!!

前言

webservice是一種跨平臺(tái)跨語言的規(guī)范秋冰,用于不同平臺(tái),不同語言開發(fā)的應(yīng)用之間的交互埃撵。

開發(fā)人員一般就是在具體平臺(tái)開發(fā)webservice接口虽另,以及調(diào)用webservice接口捂刺;每種開發(fā)語言都有自己的webservice實(shí)現(xiàn)框架族展。比如Java 就有 Apache Axis1仪缸、Apache Axis2锣尉、Codehaus XFireApache CXF爱谁、Apache Wink寺旺、Jboss RESTEasyd等等...

第一節(jié): 使用CXF開發(fā)WebService服務(wù)端接口

一.使用傳統(tǒng)的jdk實(shí)現(xiàn)webservice功能

1.1 **新建maven project 填入項(xiàng)目名稱 **

選擇第一個(gè) 構(gòu)建maven管理項(xiàng)目 而不是生成具體的java文件(只有目錄)

使用的packeage為 jar (傳統(tǒng)的project)

項(xiàng)目 結(jié)構(gòu)如下:

本章節(jié)先展示如何使用javaee原生的jar開發(fā)webservice功能

1.2 更換j2ee的版本 使用maven生成的默認(rèn)使用j2ee1.5 這里使用webservice功能需要使用1.7及以上

1.3 新建接口

1.4 編輯接口

package com.ztgeo.webservice;

import javax.jws.WebService;

@WebService //使用webservice進(jìn)行聲明類
public interface HelloWorld {
    
    public String say(String str);
}

1.5 新建并編輯實(shí)現(xiàn)類

package com.ztgeo.webservice.impl;

import javax.jws.WebService;

import com.ztgeo.webservice.HelloWorld;

@WebService//同樣適用webservice進(jìn)行注解
public class HelloWorldImpl implements HelloWorld {

    public String say(String str) {//接口發(fā)布后由對(duì)接方出入?yún)?shù)
        return "對(duì)接方傳過來的參數(shù)是:"+str;
    }

}

1.6 編寫主類service進(jìn)行暴露接口(這里暫時(shí)在impl包中書寫)
package com.ztgeo.webservice.impl;

import javax.xml.ws.Endpoint;

import com.ztgeo.webservice.HelloWorld;

public class Service {
    
    public static void main(String[] args) {
        System.out.println("webservice開始工作!!");
        HelloWorld hl = new HelloWorldImpl();//1. 暴露的實(shí)現(xiàn)類
        String address = "http://172.29.152.143/baolu"; //2. 暴露的地址 其中http必須 地址為本機(jī)地址 /后隨便
        Endpoint.publish(address, hl); //3.發(fā)布
        System.out.println("webservice已經(jīng)開始!!");
    }

}

1.7 運(yùn)行

1.8 訪問

這里需要特別注意的是 需要使用url?wsdl訪問 否則無法訪問

WSDL的概述
這里的wsdlWeb Services Description Language的縮寫迈窟,是一個(gè)用來描述Web服務(wù)和說明如何與Web服務(wù)通信XML語言骇径。WSDL是Web Service的描述語言,用于描述Web Service的服務(wù)拴袭,接口綁定等父泳,為用戶提供詳細(xì)的接口說明書杆融。

二.使用cxf框架 實(shí)現(xiàn)webservice

2.1 pom.xml中添加和下載apache cxf框架 中央倉庫

<dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxws</artifactId>
        <version>3.1.12</version>
  </dependency>

2.2 這邊使用jetty發(fā)布(類似于tomcat)web

<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http-jetty</artifactId>
    <version>3.1.12</version>
</dependency>

2.3 修改代碼 使用cxf實(shí)現(xiàn)

package com.ztgeo.webservice.impl;

import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

import com.ztgeo.webservice.HelloWorld;

public class Service {
    
    public static void main(String[] args) {
        System.out.println("webservice開始工作!!");
        HelloWorld hl = new HelloWorldImpl();//1. 暴露的實(shí)現(xiàn)類
        String address = "http://localhost/baolu"; //2. 暴露的地址 其中http必須 地址為本機(jī)地址 /后隨便
        //Endpoint.publish(address, hl); //3.發(fā)布
        JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();
        factoryBean.setAddress(address);//設(shè)置發(fā)布地址  
        factoryBean.setServiceClass(HelloWorld.class);//設(shè)置接口類
        factoryBean.setServiceBean(hl);//設(shè)置實(shí)現(xiàn)類
        factoryBean.create();//啟動(dòng)
        System.out.println("webservice已經(jīng)開始!!");
    }

}

2.4 請(qǐng)求頁面 這里使用框架來構(gòu)建 url無需加?wsdl也不會(huì)報(bào)錯(cuò)

第二章 使用cxf 開發(fā)客戶端

客戶端開發(fā)用來解析url
2.1 新建maven項(xiàng)目

使用wsdl2java可以根據(jù)wsdl動(dòng)態(tài)生成代碼
這個(gè)工具在cxf的源碼包中,點(diǎn)擊xcf鏈接下載

下載后主要使用bin下的wsdl2java命令工具

使用該命令前需要在系統(tǒng)變量中將該bin設(shè)置為系統(tǒng)變量.


2.2 使用wsdl2java根據(jù)wsdl生成對(duì)應(yīng)代碼

cd 切換目錄到項(xiàng)目文件夾


使用過程中 如果報(bào)指令不符合...確定加入環(huán)境變量后重開cmd

2.3 refresh ecilipse 查看生成的代碼

暴露的節(jié)后生成類后依然是接口,具體的實(shí)現(xiàn)由HelloWorldService來實(shí)現(xiàn)

2.4 編寫Client類,使用該接口 該類位于生成類的同包下

package com.ztgeo.webservice;

public class Client {

    //客戶端調(diào)用
    public static void main(String[] args) {
        HelloWorldService service = new HelloWorldService();//實(shí)體化服務(wù)類
        HelloWorld hl = service.getHelloWorldPort();//獲得接口類 (HelloWorld)
        System.out.println(hl.say("你好,服務(wù)端!我是客戶端")); //調(diào)用該接口的方法
    }

}

2.5 結(jié)果展示

使用同樣的操作可以解密貴公司提供的解密服務(wù)(c++編寫)


第三章 使用CXF處理JavaBean以及復(fù)合類型

需求升級(jí)描述 由客戶端傳入字符串改為傳入U(xiǎn)ser類驗(yàn)證擁有的權(quán)限

3.1 服務(wù)端增加User類
重要字段:

private Integer id;//編號(hào)
private String usernamee;//用戶名
private String password;//密碼    

3.2 服務(wù)端增加Role類
重要字段:

private Integer id;//編號(hào)
private String roleName;//角色名稱  

3.3 在暴露的接口(HelloWorld)體現(xiàn)需求 (過來用戶 返回角色集合)

//給用戶 返回角色集合  
public List<Role> getRolesByUser(User user);  

3.4 實(shí)現(xiàn)類中進(jìn)行接口的實(shí)現(xiàn)

public List<Role> getRolesByUser(User user) {
    List<Role> roles = new ArrayList<Role>();
    if("wh".equals(user.getUsername())&&"123456".equals(user.getPassword())){
        roles.add(new Role(1,"系統(tǒng)管理員"));
        roles.add(new Role(2, "程序員"));
    
    }else{
        roles.add(new Role(3,"普通用戶"));
    }
    return roles;
}

3.5 重新發(fā)布下

3.6 客戶端使用wsdl2java 重新更新生成類(無需刪除)

相應(yīng)的實(shí)體類也生成了

3.7 更改客戶端的調(diào)用

public static void main(String[] args) {
    HelloWorldService service = new HelloWorldService();//實(shí)體化服務(wù)類
    HelloWorld hl = service.getHelloWorldPort();//獲得接口類 (HelloWorld)
    //System.out.println(hl.say("你好,服務(wù)端!我是客戶端")); //調(diào)用該接口的方法
    User user = new User();//這里的user只能通過無參構(gòu)造  
    user.setUsername("wh");
    user.setPassword("123456");
    
    List<Role> roles = hl.getRolesByUser(user);//調(diào)用實(shí)現(xiàn)
    
    for (Role role : roles) {
        System.out.println(role.getId()+"角色民稱:"+role.getRoleName());
    }
}

3.8 運(yùn)行后輸出

![](http://or316jtnw.bkt.clouddn.com//17-7-11/57009298.jpg)  

第四章 CXF 處理復(fù)雜類型(MAP)

問題暴露:
4.1 接口需求編寫

public Map<String,List<Role>> getAllRoles();

4.2 方法的實(shí)現(xiàn)

public Map<String, List<Role>> getAllRoles() {
    Map<String, List<Role>> roles = new HashMap<String, List<Role>>();
    List<Role> roles1 = new ArrayList<Role>();
    roles1.add(new Role(1,"角色一"));
    roles1.add(new Role(2,"角色二"));
    List<Role> roles2 = new ArrayList<Role>();
    roles1.add(new Role(3,"角色三"));

    roles.put("1",roles1);
    roles.put("2",roles2);

    return roles;
}

4.3 發(fā)布后發(fā)現(xiàn)問題

這時(shí)候需要特殊處理map類

4.4 暴露的接口中使用適配器進(jìn)行處理

//返回所有用戶角色和權(quán)限  
@XmlJavaTypeAdapter(MapAdapte.class)//加入適配器類(不能處理的類的具體實(shí)現(xiàn))
public Map<String,List<Role>> getAllRoles(); 

其中 具體來處理適配器的類是MapAdate 是自己需要編寫的

4.5 編寫適配器類的適配規(guī)則

//該類必須繼承XmlAdapter 參數(shù)一 被轉(zhuǎn)換的類型(數(shù)組 自行創(chuàng)建 map 已存在 )
public class MapAdapte extends XmlAdapter<MyRole[], Map<String, List<Role>>>{
    
}

其中MyRole自行創(chuàng)建 [] 代表多個(gè)類

4.6 創(chuàng)建 轉(zhuǎn)換成的類 MyRole
主要屬性:

private String key;
private List<Role> value;

其實(shí)就相當(dāng)于 將key value轉(zhuǎn)換成了具體的實(shí)體類 然后map轉(zhuǎn)換成了實(shí)體類數(shù)組

4.7 實(shí)現(xiàn)繼承需要被重寫的方法
就是具體的轉(zhuǎn)換過程

//適配轉(zhuǎn)換 MyRole[]-->Map<String, List<Role>
@Override
public Map<String, List<Role>> unmarshal(MyRole[] v) throws Exception {
//實(shí)現(xiàn)的方式
Map<String, List<Role>> map = new HashMap<String, List<Role>>();
for (int i = 0; i < v.length; i++) {
map.put(v[i].getKey(), v[i].getValue());
}
return map;
}

//適配轉(zhuǎn)換 Map<String, List<Role>-->MyRole[]
@Override
public MyRole[] marshal(Map<String, List<Role>> v) throws Exception {
    MyRole[] myroles = new MyRole[v.size()];
    int i =0;
    for (String key  : v.keySet()) {
        //必須實(shí)例化 否則 空指針 
        myroles[i] = new MyRole();
        myroles[i].setKey(key);
        myroles[i].setValue(v.get(key));
        i++;
    }
    return myroles;
}

4.8 再次發(fā)布運(yùn)行

發(fā)布成功!!無報(bào)錯(cuò)

且真正的返回類型在wsdl中已有改變 為MyRole


4.9 客戶端重新更新代碼

4.10 客戶端解析代碼

public static void main(String[] args) {
    HelloWorldService service = new HelloWorldService();//實(shí)體化服務(wù)類
    HelloWorld hl = service.getHelloWorldPort();//獲得接口類 (HelloWorld)
    
    MyRoleArray myRoleArray = hl.getAllRoles();
    
    //編譯array
    
    List<MyRole> roles = myRoleArray.getItem();
    for (MyRole myRole : roles) {
        //便利里面的角色名稱
        for (Role role : myRole.getValue()) {
            System.out.println("角色id:"+role.getId()+"角色名稱:"+role.getRoleName());
        }
    }
}

輸出結(jié)果 :

第五章 CXF添加攔截器 (內(nèi)置攔截器)

5.1 添加cxf內(nèi)置in log攔截器(可以看到soap消息) __服務(wù)器端

    factoryBean.getInInterceptors().add(new LoggingInInterceptor());//in日志攔截器 進(jìn)入啟用  

5.2 添加cxf內(nèi)置out log攔截器(可以看到soap消息) __服務(wù)器端

    factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());//out日志攔截器 退出啟用  

5.3 服務(wù)器端啟動(dòng)-->客戶端調(diào)用 查看日志

webservice開始工作!!
七月 11, 2017 9:00:49 下午 org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
信息: Creating Service {http://webservice.ztgeo.com/}HelloWorldService from class com.ztgeo.webservice.HelloWorld
七月 11, 2017 9:00:51 下午 org.apache.cxf.endpoint.ServerImpl initDestination
信息: Setting the server's publish address to be http://localhost:80/baolu
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
webservice已經(jīng)開始!!
七月 11, 2017 9:00:58 下午 org.apache.cxf.services.HelloWorldService.HelloWorldPort.HelloWorld
信息: Inbound Message
----------------------------
ID: 1
Address: http://localhost/baolu?wsdl
Http-Method: GET
Content-Type: 
Headers: {Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], Content-Type=[null], Host=[localhost], Pragma=[no-cache], User-Agent=[Apache-CXF/3.1.12]}
--------------------------------------
七月 11, 2017 9:01:00 下午 org.apache.cxf.services.HelloWorldService.HelloWorldPort.HelloWorld
信息: Inbound Message
----------------------------
ID: 2
Address: http://localhost/baolu
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml; charset=UTF-8
Headers: {Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], Content-Length=[168], content-type=[text/xml; charset=UTF-8], Host=[localhost], Pragma=[no-cache], SOAPAction=[""], User-Agent=[Apache-CXF/3.1.12]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getAllRoles xmlns:ns2="http://webservice.ztgeo.com/"/></soap:Body></soap:Envelope>
--------------------------------------
七月 11, 2017 9:01:00 下午 org.apache.cxf.services.HelloWorldService.HelloWorldPort.HelloWorld
信息: Outbound Message
---------------------------
ID: 2
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml
Headers: {}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getAllRolesResponse xmlns:ns2="http://webservice.ztgeo.com/"><return><item><key>1</key><value><id>1</id><roleName>角色一</roleName></value><value><id>2</id><roleName>角色二</roleName></value><value><id>3</id><roleName>角色三</roleName></value></item><item><key>2</key></item></return></ns2:getAllRolesResponse></soap:Body></soap:Envelope>
--------------------------------------

其中id2 是返回的攔截器.里面有soap消息

Client端實(shí)現(xiàn)攔截

因?yàn)閏lient端要使用攔截器,所以 jar包還是需要的
5.4 pom.xml中配置相應(yīng)的jar

  <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxws</artifactId>
        <version>3.1.12</version>
  </dependency>
  
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http-jetty</artifactId>
        <version>3.1.12</version>
    </dependency>

5.5 使用client代理類進(jìn)行編寫

public static void main(String[] args) {
    HelloWorldService service = new HelloWorldService();//實(shí)體化服務(wù)類
    HelloWorld hl = service.getHelloWorldPort();//獲得接口類 (HelloWorld)
    
    //MyRoleArray myRoleArray = hl.getAllRoles();//這個(gè)位置攔截不到信息 因?yàn)榉椒▓?zhí)行后才攔截
    org.apache.cxf.endpoint.Client client = ClientProxy.getClient(hl);//使用代理類 獲取客戶端  
    client.getInInterceptors().add(new LoggingInInterceptor());//進(jìn)入攔截器
    client.getOutInterceptors().add(new LoggingOutInterceptor());//檢出攔截器
    //編譯array
    MyRoleArray myRoleArray = hl.getAllRoles();//這邊一定要注意順序 攔截器必須在方法前 否則 攔截不到
    List<MyRole> roles = myRoleArray.getItem();
    for (MyRole myRole : roles) {
        //便利里面的角色名稱
        for (Role role : myRole.getValue()) {
            System.out.println("角色id:"+role.getId()+"角色名稱:"+role.getRoleName());
        }
    }
}

和服務(wù)器端不同的是 先有檢出 后進(jìn)入

5.6 控制臺(tái)監(jiān)控的信息如下 :

七月 11, 2017 9:11:56 下午 org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
信息: Creating Service {http://webservice.ztgeo.com/}HelloWorldService from WSDL: http://localhost/baolu?wsdl
七月 11, 2017 9:11:58 下午 org.apache.cxf.services.HelloWorldService.HelloWorldPort.HelloWorld
信息: Outbound Message
---------------------------
ID: 1
Address: http://localhost/baolu
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml
Headers: {Accept=[*/*], SOAPAction=[""]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getAllRoles xmlns:ns2="http://webservice.ztgeo.com/"/></soap:Body></soap:Envelope>
--------------------------------------
七月 11, 2017 9:11:58 下午 org.apache.cxf.services.HelloWorldService.HelloWorldPort.HelloWorld
信息: Inbound Message
----------------------------
ID: 1
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml; charset=UTF-8
Headers: {content-type=[text/xml; charset=UTF-8], Date=[Tue, 11 Jul 2017 13:11:58 GMT], Server=[Jetty(9.2.21.v20170120)], transfer-encoding=[chunked]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getAllRolesResponse xmlns:ns2="http://webservice.ztgeo.com/"><return><item><key>1</key><value><id>1</id><roleName>角色一</roleName></value><value><id>2</id><roleName>角色二</roleName></value><value><id>3</id><roleName>角色三</roleName></value></item><item><key>2</key></item></return></ns2:getAllRolesResponse></soap:Body></soap:Envelope>
--------------------------------------
角色id:1角色名稱:角色一
角色id:2角色名稱:角色二
角色id:3角色名稱:角色三

這邊需要注意的是.對(duì)于客戶端來講,先有出(訪問請(qǐng)求),才有進(jìn)(返回請(qǐng)求), 在返回端可以看到soap信息

第六節(jié) CXF添加自定義攔截器

添加自定義攔截器的思路和內(nèi)置攔截器相同 ,只需要替換內(nèi)置攔截器,自己寫就好..看內(nèi)置的實(shí)現(xiàn)了哪些方法

內(nèi)置攔截器的繼承關(guān)系

public class LoggingInInterceptor extends AbstractLoggingInterceptor

6.1 編寫服務(wù)端自定義攔截器

package com.ztgeo.interceptor;

import java.util.List;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;

public class MyInInterceptor extends  AbstractPhaseInterceptor<SoapMessage>{

public MyInInterceptor(String phase) {//實(shí)現(xiàn)父類的方法 ,這里是個(gè)構(gòu)造方法實(shí)現(xiàn)
    super(Phase.PRE_INVOKE);//給靜態(tài)變量賦值 在進(jìn)入方法前調(diào)用
    
}

public void handleMessage(SoapMessage message) throws Fault {
    //soap消息就是客戶端傳入的信息
    //全部封裝在headers中 進(jìn)行頭部的解析
    List<Header> headers = message.getHeaders();//獲取全部頭信息
    //判斷如果沒有頭部信息 那么一定有問題 
    if(headers==null|| headers.size()==0){
        throw new Fault(new IllegalArgumentException("頭信息不存在,in攔截器拋出了異常!!"));
    }
    //存在頭信息 獲取頭信息 (是xml形式)
    Header header = headers.get(0);
    //使用w3c的dom解析該header
    Element ele =(Element)header.getObject();
    //獲取其中的username和password節(jié)點(diǎn)
    String username = ele.getElementsByTagName("username").item(0).getTextContent();
    String password = ele.getElementsByTagName("password").item(0).getTextContent();
    
    //約定允許訪問的條件
    if("wh".equals(username)){
        if("123456".equals(password)){
            
        }else{
            throw new Fault(new IllegalArgumentException("用戶秘鑰異常~!!"));
        }
    }else{
        throw new Fault(new IllegalArgumentException("當(dāng)前用戶無訪問權(quán)限!"));
    }
    
}

}

6.1 客戶端添加檢出自定義攔截器 用于往頭部添加信息

 client.getOutInterceptors().add(new AddHeaderInInterceptor("wh","12456"));//自己編寫的類

6.2 編寫客戶端自定義攔截器
這邊的自定義類 和服務(wù)端一樣 只是觸發(fā)攔截的時(shí)機(jī)改為了準(zhǔn)備發(fā)送,soap message的處理 不是解析頭部信息 而是往頭部信息里添加username和password
package com.ztgeo.webservice;

import java.util.List;

import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;

import com.ztgeo.interceptor.AddHeaderInInterceptor;

public class Client {

//客戶端調(diào)用
public static void main(String[] args) {
    HelloWorldService service = new HelloWorldService();//實(shí)體化服務(wù)類
    HelloWorld hl = service.getHelloWorldPort();//獲得接口類 (HelloWorld)
    
    //MyRoleArray myRoleArray = hl.getAllRoles();//這個(gè)位置攔截不到信息 因?yàn)榉椒▓?zhí)行后才攔截
    org.apache.cxf.endpoint.Client client = ClientProxy.getClient(hl);//使用代理類 獲取客戶端  
    client.getInInterceptors().add(new LoggingInInterceptor());//進(jìn)入攔截器
    client.getOutInterceptors().add(new LoggingOutInterceptor());//檢出攔截器
    
    //添加自定義攔截器 用于在頭部添加用戶信息
    client.getOutInterceptors().add(new AddHeaderInInterceptor("wh","12456"));//自己編寫的類
    //編譯array
    MyRoleArray myRoleArray = hl.getAllRoles();//這邊一定要注意順序 攔截器必須在方法前 否則 攔截不到
    List<MyRole> roles = myRoleArray.getItem();
    for (MyRole myRole : roles) {
        //便利里面的角色名稱
        for (Role role : myRole.getValue()) {
            System.out.println("角色id:"+role.getId()+"角色名稱:"+role.getRoleName());
        }
    }
}

}

上面代碼需要 注意 發(fā)送前添加了一個(gè)頭 而不是修改一個(gè)頭

6.3 啟動(dòng)服務(wù)器端

啟動(dòng)正常

6.4 啟動(dòng)客戶端 查看結(jié)果
頭部攜帶的信息如下:

Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>用戶秘鑰異常~!!</faultstring></soap:Fault></soap:Body></soap:Envelope>

結(jié)果正常:

第七章 使用Spring整合CXF開發(fā)WEB端

關(guān)于整合spring發(fā)布webservice 官方文檔地址
7.1 新建一個(gè)web項(xiàng)目

骨架選擇 web1.0的骨架

7.2 替換為jre1.8

7.3 目前項(xiàng)目處于報(bào)錯(cuò)狀態(tài) 是因?yàn)閖sp文件中 沒有httpservlet

針對(duì)這種情況 實(shí)際上是缺少運(yùn)行時(shí)servlet導(dǎo)致的,解決的方法是 添加tomcat后重新保存

7.4 pom.xml中添加spring支持

<!-- 添加Spring支持 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.1.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>4.1.7.RELEASE</version>
</dependency>
<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-tx</artifactId>
     <version>4.1.7.RELEASE</version>
    </dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.1.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.1.7.RELEASE</version>
</dependency>
 
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.7.RELEASE</version>
</dependency>
 
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.1.7.RELEASE</version>
</dependency>
 
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>4.1.7.RELEASE</version>
</dependency>
 
 
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>4.1.7.RELEASE</version>
</dependency>
 
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.1.7.RELEASE</version>
</dependency>

7.5 添加cxf支持

<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-core</artifactId>
<version>3.1.5</version>
</dependency>

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxws</artifactId>
        <version>3.1.5</version>
    </dependency>
     
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http</artifactId>
        <version>3.1.5</version>
    </dependency>

注意 這邊已經(jīng)沒有了jetty的支持 改為tomcat

7.6 編寫spring的配置文件 注意文件的位置 放在resources中

7.7 具體的配置

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans"    
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:aop="http://www.springframework.org/schema/aop"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:jee="http://www.springframework.org/schema/jee"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="    
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">    
        
      <!-- 用于cxf相關(guān)類的實(shí)例化 -->  
    <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
    
    <!-- 自動(dòng)掃描 -->
    <context:component-scan base-package="com.ztgeo" />
    
    <!-- 定義服務(wù)提供者  -->
    <jaxws:endpoint
        implementor="#helloWorld"
        address="/HelloWorld"
     ></jaxws:endpoint>
</beans>  

其中 xmlns:jaxws="http://cxf.apache.org/jaxws" 為新命名的空間
implementor="#helloWorld" 為暴露的接口
adress ="/HelloWorld"為url訪問時(shí) 輸入的url標(biāo)識(shí)符

7.8 #helloWorld需要在實(shí)現(xiàn)類中加入注解

@Component("helloWorld")
@WebService//同樣適用webservice記性注解
public class HelloWorldImpl implements HelloWorld 

7.9 web.xml中的配置如下

    <?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>WS_Spring_CXF</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
    <!-- Spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
     
    <!-- Spring監(jiān)聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <servlet>  
     <servlet-name>CXFServlet</servlet-name>  
     <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
    </servlet>  
     
    <servlet-mapping>  
       <servlet-name>CXFServlet</servlet-name>  
       <url-pattern>/webservice/*</url-pattern>  
    </servlet-mapping>
</web-app>

除了基本的web配置外 需要單門配置servlet 的mapping進(jìn)行處理servlet

7.10 使用客戶端進(jìn)行解析

解析結(jié)果正常

第八章 使用spring攔截器

8.1 對(duì)于客戶端,添加攔截器需要在 applicationContext中配置如下:

 <jaxws:inInterceptors>
     <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
     <bean class="com.ztgeo.interceptor.MyInInterceptor"/>
    </jaxws:inInterceptors>
    <!-- 添加out攔截器 -->
    <jaxws:outInterceptors>
     <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
</jaxws:outInterceptors>

其中 有自定義的攔截器 和 框架本身的攔截器

8.2 客戶端的調(diào)用 做了些改動(dòng),因?yàn)槭褂胹pring發(fā)布的webservice 生成的類做了調(diào)整..具體的調(diào)用方法如下:

HelloWorldImplService service = new HelloWorldImplService();
    HelloWorld hl = service.getHelloWorldImplPort();//獲得接口類 (HelloWorld)

8.3 攔截效果如下:

本學(xué)習(xí)總結(jié)結(jié)束

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市兄纺,隨后出現(xiàn)的幾起案子座云,更是在濱河造成了極大的恐慌,老刑警劉巖限佩,帶你破解...
    沈念sama閱讀 216,692評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異砖顷,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)锣险,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,482評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門崖咨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事÷痔” “怎么了珊随?”我有些...
    開封第一講書人閱讀 162,995評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我掸屡,道長满着,這世上最難降的妖魔是什么宁改? 我笑而不...
    開封第一講書人閱讀 58,223評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮斗遏,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘铸本。我一直安慰自己,他們只是感情好汪茧,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,245評(píng)論 6 388
  • 文/花漫 我一把揭開白布舱污。 她就那樣靜靜地躺著,像睡著了一般媚赖。 火紅的嫁衣襯著肌膚如雪珠插。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,208評(píng)論 1 299
  • 那天磨隘,我揣著相機(jī)與錄音番捂,去河邊找鬼江解。 笑死鳖枕,一個(gè)胖子當(dāng)著我的面吹牛缠局,可吹牛的內(nèi)容都是我干的井辜。 我是一名探鬼主播,決...
    沈念sama閱讀 40,091評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼诺祸!你這毒婦竟也來了咸灿?” 一聲冷哼從身側(cè)響起卸勺,我...
    開封第一講書人閱讀 38,929評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤苹享,失蹤者是張志新(化名)和其女友劉穎抚岗,沒想到半個(gè)月后亩冬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體荚板,經(jīng)...
    沈念sama閱讀 45,346評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,570評(píng)論 2 333
  • 正文 我和宋清朗相戀三年彤枢,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片晤斩。...
    茶點(diǎn)故事閱讀 39,739評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡茫负,死狀恐怖勉失,靈堂內(nèi)的尸體忽然破棺而出徒蟆,到底是詐尸還是另有隱情嫂用,我是刑警寧澤疏唾,帶...
    沈念sama閱讀 35,437評(píng)論 5 344
  • 正文 年R本政府宣布懂从,位于F島的核電站辽旋,受9級(jí)特大地震影響补胚,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜溶其,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,037評(píng)論 3 326
  • 文/蒙蒙 一瓶逃、第九天 我趴在偏房一處隱蔽的房頂上張望廓块。 院中可真熱鬧,春花似錦昔汉、人聲如沸拴清。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,677評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至驾凶,卻和暖如春掷酗,著一層夾襖步出監(jiān)牢的瞬間窟哺,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,833評(píng)論 1 269
  • 我被黑心中介騙來泰國打工浮声, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留泳挥,地道東北人至朗。 一個(gè)月前我還...
    沈念sama閱讀 47,760評(píng)論 2 369
  • 正文 我出身青樓,卻偏偏與公主長得像矗钟,于是被迫代替她去往敵國和親嫌变。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,647評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理秸应,服務(wù)發(fā)現(xiàn)软啼,斷路器延柠,智...
    卡卡羅2017閱讀 134,652評(píng)論 18 139
  • 一、Java基礎(chǔ) 1.寫出下面代碼的執(zhí)行結(jié)果 2.寫出下面代碼的執(zhí)行結(jié)果 3.寫出下面代碼的執(zhí)行結(jié)果 (此題需寫出...
    joshul閱讀 512評(píng)論 0 1
  • 概覽 CXF frontends 是一組編程的API贿条,被用來開發(fā)和發(fā)布webservice整以。CXF支持兩種類型的f...
    JohnShen閱讀 1,305評(píng)論 2 2
  • 婆峻仇,身形削瘦,背微彎凡蚜,臉上全是皺紋,小小的眼睛恶迈,無牙谱醇,真的是一顆牙都沒有,頭發(fā)總是盤成一個(gè)發(fā)髻奈附。 婆總是穿著一件邊...
    國宴閱讀 264評(píng)論 11 8
  • 楔子 你像寒冬時(shí)節(jié)的弄堂里氤氳升起的濃霧佳晶。時(shí)光把無孔不入的孤獨(dú)切割成掩蓋...
    w可閱讀 271評(píng)論 0 0