CXF詳細介紹

首先介紹下CXF的攔截器:
簡單地說,CXF使用流水線型(或者說總線型)處理機制,它的核心是一個Bus。一個客戶端的請求或者一個對客戶端樁代碼的調用被組織成爲一個Message。同時,全部的CXF功能都組織成Interceptor掛接在Bus上,分階段依次處理MessageMessage本質上是一個Map數據結構,既包含系統公共的也包含Interceptor自定義的數據。

AbstractPhaseInterceptor<Message>這個抽象類攔截器類,自定義攔截器類能夠繼承它實現它其中一個抽象方法public void handleMessage(Message message) throws Fault

以下代碼實現:java

package com.jd.train.service.webservice.ipinterceptor;web

import com.jd.train.service.util.CodesUtil;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;spring

import javax.servlet.http.HttpServletRequest;
import java.util.List;數據庫

/**
 * Created by IntelliJ IDEA.
 * User: zhangzhaozhao
 * Date: 12-3-26
 * Time: 下午4:06
 * To change this template use File | Settings | File Templates.
 */
public class IpAddressInInterceptor extends AbstractPhaseInterceptor<Message> {
    //這個屬性是注入進來的,你也能夠從properties,xml文件中去讀取,也能夠從數據庫中去獲取;
    private List<String> ipList;apache

    public void setIpList(List<String> ipList) {
        this.ipList = ipList;
    }api

    private final static Logger logger = LogManager.getLogger(IpAddressInInterceptor.class);
    public IpAddressInInterceptor() {
        super(Phase.RECEIVE);
    }服務器

    public void handleMessage(Message message) throws Fault {
        //指定CXF獲取客戶端的HttpServletRequest : http-request;
        HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
        String ipAddress="";
        boolean flag = false;
        if (null != request) {
            ipAddress = getUserIpAddr(request); // 取客戶端IP地址
            logger.info("請求客戶端的IP地址:" + ipAddress);
            for (String s : ipList) {
                if (s.equals(ipAddress)) {
                    flag = true;
                    break;
                }
            }
        }
        if(!flag) {
            throw new Fault(new IllegalAccessException("IP address " + ipAddress + " is stint"));
        }
    }數據結構

    /**
     * 獲取IP地址的方法
     * @param request
     * @return
     */
    private String getUserIpAddr(HttpServletRequest request) {
        //獲取通過代理的客戶端的IP地址; 排除了request.getRemoteAddr() 方法 在經過了Apache,Squid等反向代理軟件就不能獲取到客戶端的真實IP地址了
        String ip = CodesUtil.getIpAddr(request);
        if (ip != null && ip.indexOf(",") > 0) {
            logger.info("取到客戶多個ip1====================" + ip);
            String[] arr = ip.split(",");
            ip = arr[arr.length - 1].trim();//有多個ip時取最後一個ip
            logger.info("取到客戶多個ip2====================" + ip);
        }
        return ip;
    }
}dom

看下Spring 配置文件的信息:

ui

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xmlns:http-conf="http://cxf.apache.org/transports/http/configuration" xmlns:cxf="http://cxf.apache.org/core"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
             http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
             http://cxf.apache.org/transports/http/configuration
             http://cxf.apache.org/schemas/configuration/http-conf.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd"
       default-autowire="byName">

    <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>

    <jaxws:endpoint id="messageNotifyServices" address="/MessageNotifyServices" >
        <jaxws:implementor>
            <bean class="com.jd.train.service.webservice.impl.MessageNotifyServicesImpl"/>
        </jaxws:implementor>
        <jaxws:inInterceptors>
            <ref bean="ipInterceptor"/>
        </jaxws:inInterceptors>
    </jaxws:endpoint>
    <!-- 訂單推送WebService接口-->
    <jaxws:endpoint id="orderStatusServices" address="/OrderStatusServices">
        <!--這是須要發佈的實現類 -->
        <jaxws:implementor>
            <bean class="com.jd.train.service.webservice.impl.OrderStatusServicesImpl"/>
        </jaxws:implementor>
        <jaxws:inInterceptors>
            <ref bean="ipInterceptor"/>
        </jaxws:inInterceptors>
    </jaxws:endpoint>

    <!--毫秒單位 name 爲 webservice 的域名 或者地址-->
    <http-conf:conduit name="${train.api.domain.name}.*">
        <http-conf:client ConnectionTimeout="10000" ReceiveTimeout="20000"/>
    </http-conf:conduit>

    <bean id="logIn" class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
    <bean id="logOut" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
     <!-- 自定義攔截器-->
    <bean id="ipInterceptor" class="com.jd.train.service.webservice.ipinterceptor.IpAddressInInterceptor"/>
    <!-- 合法的IP地址,若是第三方IP變更須要修改 -->
    <bean id="ipList" class="java.util.ArrayList">
        <constructor-arg>
            <list>
                <value>114.80.202.120</value>
            </list>
        </constructor-arg>
    </bean>

    <!-- CXF 全局的攔截器-->
   <cxf:bus>
       <cxf:inInterceptors>
           <ref bean="logIn"/>
       </cxf:inInterceptors>
       <cxf:outInterceptors>
           <ref bean="logOut" />
       </cxf:outInterceptors>
   </cxf:bus>

    
</beans>

解釋下里面東西:
<jaxws:endpoint id="messageNotifyServices" address="/MessageNotifyServices" >
<jaxws:implementor>
    <bean class="com.jd.train.service.webservice.impl.MessageNotifyServicesImpl"/>
</jaxws:implementor>
<jaxws:inInterceptors>
    <ref bean="ipInterceptor"/>
</jaxws:inInterceptors>
</jaxws:endpoint>

<!-- 訂單推送WebService接口-->
<jaxws:endpoint id="orderStatusServices" address="/OrderStatusServices">
<!--這是須要發佈的實現類 -->
<jaxws:implementor>
    <bean class="com.jd.train.service.webservice.impl.OrderStatusServicesImpl"/>
</jaxws:implementor>
<jaxws:inInterceptors>
    <ref bean="ipInterceptor"/>
</jaxws:inInterceptors>
</jaxws:endpoint>
這兩個是我發佈出去的WebService 接口(這裏須要你本身去實現,我並無把代碼貼出來);
<jaxws:inInterceptors>
    <ref bean="ipInterceptor"/>
</jaxws:inInterceptors> 這個是自定義的攔截器類

說到這裏須要注意下了:若是把自定義的攔截器引入到發佈出去的接口當中,而不是引入到全局的<cxf:bus>中,這樣只對你發佈出去的接口起做用
若是配置到全局的<cxf:bus>中對你訪問第三方的WebService接口和別人訪問你發佈出去的WebService接口,都起到攔截做用,我開發過程遇到此問題,我調用第三方的webService接口時候也被攔截了,其中在自定義攔截器的HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
request是null ,而且IP也被過過濾掉了,使其我不能訪問第三方的接口了.

第二個問題:就是Spring 配置文件的頭信息http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd搞進去!

第三個問題:就是在獲取客戶IP時候,request.getRemoteAddr()取得客戶端的IP地址,可是在經過了Apache,Squid等反向代理軟件就不能獲取到客戶端的真實IP地址了。
通過代理之後,因爲在客戶端和服務之間增長了中間層,所以服務器沒法直接拿到客戶端的IP,服務器端應用也沒法直接經過轉發請求的地址返回給客戶端。可是在轉發請求的HTTP頭信息中,增長了X-FORWARDED-FOR信息用以跟蹤原有的客戶端IP地址和原來客戶端請求的服務器地址。給出比較靠譜實現: public static String getIpAddr(HttpServletRequest request) {        String ip = request.getHeader("x-forwarded-for");        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {            ip = request.getHeader("Proxy-Client-IP");        }        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {            ip = request.getHeader("WL-Proxy-Client-IP");        }        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {            ip = request.getRemoteAddr();        }        return ip;    }若是經過了多級反向代理的話,X-Forwarded-For的值並不止一個,而是一串ip值,其中哪一個纔是真正的用戶端的真實IP呢?答案是取X-Forwarded-For中第一個非unknown的有效IP字符串。如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100,用戶真實IP爲: 192.168.1.110若是朋友遇到以上問題,請多加註意.

相關文章
相關標籤/搜索