使用CXF為webservice添加攔截器

來源:互聯網
上載者:User

標籤:

 

攔截器分為Service端和Client端

     攔截器是在發送soap訊息包的某一個時機攔截soap訊息包,對soap訊息包的資料進行分析或處理。分為CXF內建的攔截器和自訂的攔截器

 

1、Service端:

通過將org.apache.cxf.jaxws.EndpointImpl類的方法即可實現

  發布Web Service 方法可以通過Endpoint.publish()方法,此方法返為EndpointImpl,所以為Service端添加攔截器很簡單。

 

部分代碼:UserService us = new UserServiceImpl(); String address = "http://192.168.10.254:9999/crazyit"; EndpointImpl ep = (EndpointImpl)Endpoint.publish(address , us);
//下面方法就可以添加攔截器(CXF提供的攔截器)
//cxf-2.2.10.jar  org.apache.cxf.interceptor.* (CXF提供的攔截器) ep.getOutInterceptors().add(new LoggingOutInterceptor()); ep.getInInterceptors().add(new LoggingInInterceptor()); ep.getInInterceptors().add(new AuthIntercetpr()); //此攔截器是自訂的攔截器。

 

2、Client端 用戶端可以通過對org.apache.cxf.frontend.ClientProxy中的getClient()方法擷取org.apache.cxf.endpoint.Client對象,該對象可以為用戶端添攔截器。

部分代碼//為用戶端添加攔截器 org.apache.cxf.endpoint.Client client = ClientProxy.getClient(us); client.getInInterceptors().add(new LoggingInInterceptor()); client.getOutInterceptors().add(new LoggingOutInterceptor());//自訂攔截器 client.getOutInterceptors().add(new AddHeaderInterceptor("crazyit" , "crazyit.org2"));

 

3、自訂的攔截器

   自訂攔截器需要繼承org.apache.cxf.phase.AbstractPhaseInterceptor 抽象類別,並實現其handleMessage方法,與重寫自訂的構造器(由於AbstractPhaseInterceptor 沒有無參構造器,所以要在自訂構攔截器的造器中調用supper(帶參數))。

部分代碼public class AuthIntercetpr     extends AbstractPhaseInterceptor<SoapMessage> {     public AuthIntercetpr()     {         //子類總會調用父類的構造器,         //預設是調用無參數的構造器。
        //指定該攔截器在哪個階段被激發       
  super(Phase.PRE_INVOKE);     }
    //處理訊息   
  public void handleMessage(SoapMessage message)     {         System.out.println("==================" + message);
        //擷取SOAP訊息的全部頭    
     List<Header> headers = message.getHeaders();
        if(headers.size() < 1)         {   
          throw new Fault(new SOAPException("SOAP訊息頭格式不對哦!"));         }        
        for(Header header : headers)         {  
           SoapHeader soapHeader = (SoapHeader)header;             //取出SOAP的Header元素             Element element = (Element)soapHeader.getObject();             checkSOAPHeader(element);         }         } }

使用CXF為webservice添加攔截器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.