Java後端支付大雜燴之sps.controller(支付請求入口,配置文件)(五)

七、sps.controller.base,front.

說明

若是有幸能看到,其實只爲本身記錄,回頭複習用css

  • 一、本文項目來自Martin404,本身只是臨摹大佬的項目。
  • 二、重要的是學習過程,而不是結果。但,結果一樣重要,加油。gogogo。
  • 三、框架搭建就略過了。配置文件太多。遇到的時候貼出來。也收藏起來,留着備用。
  • 四、Gist、Insight.io for GitHub必備吧,劃詞翻譯不懂的單詞劃一劃。
  • 五、代碼提交到這裏了GitHub。根據提交記錄找本身想要的類庫。
  • 六、只爲本身整理,大概的過了一邊,在Service層哪裏還需好好理解。。java

    目錄

    • 二、core.dao,service,web(重點是接口的設計)點這裏
    • 三、sps包~dto、enums、mq點這裏
    • 四、在Dao層定義了domian、mapper映射文件,想了解的能夠去看看。有助於理解整個系統。點這裏
    • 五、pay.util.app。 pay.stratege,支付工具類,和支付策略點這裏
    • 六、sps.service及實現類(重點)點這裏

首先看下支付的一些相關知識點mysql

(1)、支付方案:git

<img src="https://user-gold-cdn.xitu.io...;h=843&f=jpeg&s=113104" width = "300" height = "200"/>github

(2)、支付流程:web

通常流程說明: 原做者redis

  • 用戶在商戶網站選定商品並下單,在商戶支付頁面選擇對應支付平臺圖標,進行支付;
  • 商戶按照文檔提交支付請求接口組織報文,向支付平臺發送支付請求;
  • 若是是PC端,會跳轉到對應支付平臺的支付頁面,若是是移動端,會喚起對應的支付工具,用戶在支付平臺輸入支付信息,提交支付;
  • 支付平臺將支付結果通知商戶;
  • 若支付成功,則支付平臺將交易結果異步發送給商戶;
  • 商戶若未收到交易結果,則商戶按照文檔查詢接口向支付平臺發請求查詢該交易,以肯定消費交易的狀態,支付平臺收到 查詢請求時,將同步返回該筆消費交易的交易結果;
  • 商戶若收到交易結果,若是未向支付平臺反饋已收到交易結果,支付平臺會重複發送交易結果。

在這提一點,因爲網絡緣由等異常狀況支付平臺可能出現屢次發送支付結果的狀況,通知回調接口商戶要注意作好接口冪等,其他的再也不多說。spring

在線支付過程:sql

  • 01)建立合法的商業購物網站,且在易寶支付平臺申請成爲商家,並提供商家銀行卡號,等待審查
  • 02)若是審查經過,和易寶支付簽約,得向易寶支付必定的接口使用費或每筆交易的手續費,一般是交易額的1%左右
  • 03)付款後,易寶會給每一個商家一個惟一的商家編號,密鑰,和接口文檔和jar包
  • 04)當用戶請求來了,你得獲取客戶的相關信息,例如:訂單號,金額,支付銀行等14個信息chrome

    注意:其中hmac是由客戶訂單信息和商家密鑰生成,經過易寶提供的工具包自動生成
  • 05)用表單的方式,以POST或GET請求,使用GBK或GB2312向易寶發出支付請求,請求中帶有14個參數
  • 06)易寶若是驗成功,即客戶發送過來的信息與易寶生成的信息相同的話,易寶認爲是合法用戶請求,不然非法用戶請求

    注意:驗證是否成功,主要經過hmac和密鑰做用
  • 07)若是是合法用戶的支付請求的話,易寶再將請求轉發到客戶指定的銀行,例如:招商銀行

    注意:易寶必須支持招商銀行在線支付
  • 08)凡是轉帳,查詢,等等都由銀行後臺操做完成,是全封閉的,與易寶沒有任何關係,千萬不要認爲是易寶在處理資金結算
  • 09)銀行處理完畢後,將響應結果轉發到易寶在線支付平臺
  • 10)易寶在線支付通過加工處理後,再將結果響應到用戶指定的外網能夠訪問的Servlet或Jsp頁面
  • 11)商家網站能夠用GET方式接收易寶的響應數據,通過驗證合法後,再將付款結果,顯示在用戶的瀏覽器

    注意:驗證是否成功,主要經過hmac和密鑰做用

首先來看BaseController

public class BaseController {

    private Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 獲取用戶ID,用戶ID可能爲NULL,需自行判斷
     */
    protected Long getUserId(HttpServletRequest request) {
        String sId = request.getHeader("userId");
        if (!StringUtil.isEmpty(sId)) {
            try {
                Long userId = Long.parseLong(sId);
                return userId;
            } catch (NumberFormatException e) {
                logger.warn("請求頭userId參數格式錯誤:{}", sId);
            }
        }
        return null;
    }

    /**
     * 獲取用戶ID,當userId爲空的時候拋出異常
     */
    protected Long getNotNullUserId(HttpServletRequest request) throws BusinessException {
        Long userId = getUserId(request);
        if (userId == null) {
            throw new BusinessException("用戶ID不能爲空");
        }
        return userId;
    }

    /**
     * 獲取請求來源類型
     */
    protected RequestFrom getRequestFrom(HttpServletRequest request) throws BusinessException {
        String from = request.getHeader("from");
        if (StringUtil.isEmpty(from)) {
            throw new BusinessException("請求頭錯誤未包含來源字段");
        }
        try {
            int iFom = Integer.parseInt(from);
            return RequestFrom.getById(iFom);
        } catch (NumberFormatException e) {
            throw new BusinessException("請求頭來源字段類型錯誤");
        }

    }

    /**
     * 獲取移動端請求頭信息
     */
    protected MobileInfo getMobileInfo(HttpServletRequest request) throws BusinessException {
        String appVersion = request.getHeader("appVersion");
        String systemVersion = request.getHeader("appSystemVersion");
        String deviceId = request.getHeader("appDeviceId");
        Integer width = null;
        Integer height = null;
        int night = 0;
        try {
            width = Integer.parseInt(request.getHeader("appDeviceWidth"));
            height = Integer.parseInt(request.getHeader("appDeviceHeight"));
            if (request.getHeader("nightMode") != null) {
                night = Integer.parseInt(request.getHeader("nightMode"));
            }
        } catch (NumberFormatException e) {
            throw new BusinessException("移動端請求頭不符合約定");
        }
        if (StringUtil.isEmpty(appVersion) || width == null || height == null) {
            throw new BusinessException("移動端請求頭不符合約定");
        }
        return new MobileInfo(appVersion, systemVersion, deviceId, width, height, night != 0);
    }

}

控制層異常統一處理

/**
 * 控制層異常統一處理
 */
public class RestErrorHandler {
    private static Logger logger = LoggerFactory.getLogger(RestErrorHandler.class);

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public AjaxResult handleBindException(BindException exception) {
        AjaxResult result = AjaxResult.getError(ResultCode.ParamException);
        Set<ValidationError> errors = new HashSet<ValidationError>();
        for (FieldError er : exception.getFieldErrors()) {
            errors.add(new ValidationError(er.getObjectName(), er.getField(), er.getDefaultMessage()));
        }
        result.setData(errors);
        logger.warn("參數綁定錯誤:{}", exception.getObjectName());
        return result;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public AjaxResult handleBusinessException(BusinessException exception) {
        AjaxResult result = AjaxResult.getError(ResultCode.BusinessException);
        result.setMessage(exception.getMessage());
        logger.warn("業務錯誤:{}", exception.getMessage());
        return result;
    }

    @ExceptionHandler(SystemException.class)
    @ResponseBody
    public AjaxResult handleSystemException(SystemException exception) {
        AjaxResult result = AjaxResult.getError(ResultCode.SystemException);
        result.setMessage("系統錯誤");
        logger.error("系統錯誤:{}", exception);
        return result;
    }

    @ExceptionHandler(DBException.class)
    @ResponseBody
    public AjaxResult handleDBException(DBException exception) {
        AjaxResult result = AjaxResult.getError(ResultCode.DBException);
        result.setMessage("數據庫錯誤");
        logger.error("數據庫錯誤:{}", exception);
        return result;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public AjaxResult handleException(Exception exception) {
        AjaxResult result = AjaxResult.getError(ResultCode.UnknownException);
        result.setMessage("服務器錯誤");
        logger.error("服務器錯誤:{}", exception);
        return result;
    }
}

支付通知入口:

/**
 * 支付通知入口
 * Created by Martin on 2016/7/01.
 */
@RequestMapping(value = "/open/payNotify")
public class PayNotifyController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(PayNotifyController.class);


    /**
     * 國內支付寶app通知回調
     * @param request
     * @param response
     * @throws SystemException
     * @throws BusinessException
     */
    @RequestMapping(value = "/alipayNotifyMainApp", method = RequestMethod.POST)
    public void alipayNotifyMainApp(HttpServletRequest request, HttpServletResponse response) throws SystemException, BusinessException {
        alipayNotifyService.alipayNotifyMainApp(request, response);
    }
    /**
     * 國內支付寶web通知回調
     * @param request
     * @param response
     * @throws SystemException
     * @throws BusinessException
     */
    @RequestMapping(value = "/alipayNotifyMain", method = RequestMethod.POST)
    public void alipayNotifyMain(HttpServletRequest request, HttpServletResponse response) throws SystemException, BusinessException {
        alipayNotifyService.alipayNotifyMain(request, response);
    }
    /**
     * 國際支付寶app通知回調
     * @param request
     * @param response
     * @throws SystemException
     * @throws BusinessException
     */
    @RequestMapping(value = "alipayNotifyGlobalApp", method = RequestMethod.POST)
    public void alipayNotifyGlobalApp(HttpServletRequest request, HttpServletResponse response) throws SystemException, BusinessException {
        alipayNotifyService.alipayNotifyGlobalApp(request, response);
    }
}

支付請求相關接口

/**
 * 支付請求相關接口
 */
@Controller
@RequestMapping("/app/payRequest")
public class PayRequestController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(PayRequestController.class);
    @Autowired
    private IPayRouteService payRouteService;

    /**
     * 組裝支付請求報文
     * @param payRequestParam
     * @return
     * @throws BusinessException
     * @throws SystemException
     */
    @ResponseBody
    @RequestMapping(value = "/getPayParams", method = RequestMethod.POST)
    public AjaxResult getPayParams(@RequestBody PayRequestParam payRequestParam) throws BusinessException, SystemException {
        return AjaxResult.getOK(payRouteService.getPayRetMap(payRequestParam));
    }

}

接下來在看看配置文件,支付相關的暫時省略,由於俺沒有。

generatorConfig

<generatorConfiguration>

    <!-- 能夠用於加載配置項或者配置文件,在整個配置文件中就可使用${propertyKey}的方式來引用配置項
    resource:配置資源加載地址,使用resource,MBG從classpath開始找,好比com/myproject/generatorConfig.properties
    url:配置資源加載地質,使用URL的方式,好比file:///C:/myfolder/generatorConfig.properties.
    注意,兩個屬性只能選址一個;

    另外,若是使用了mybatis-generator-maven-plugin,那麼在pom.xml中定義的properties均可以直接在generatorConfig.xml中使用
    <properties resource="" url="" />
    -->
    <properties resource="server_config.properties"/>

       <!--
       context:生成一組對象的環境
       id:必選,上下文id,用於在生成錯誤時提示
       defaultModelType:指定生成對象的樣式
           1,conditional:相似hierarchical;
           2,flat:全部內容(主鍵,blob)等所有生成在一個對象中;
           3,hierarchical:主鍵生成一個XXKey對象(key class),Blob等單獨生成一個對象,其餘簡單屬性在一個對象中(record class)
       targetRuntime:
           1,MyBatis3:默認的值,生成基於MyBatis3.x以上版本的內容,包括XXXBySample;
           2,MyBatis3Simple:相似MyBatis3,只是不生成XXXBySample;
       introspectedColumnImpl:類全限定名,用於擴展MBG
       -->

    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <!-- 自動識別數據庫關鍵字,默認false,若是設置爲true,根據SqlReservedWords中定義的關鍵字列表;
        通常保留默認值,遇到數據庫關鍵字(Java關鍵字),使用columnOverride覆蓋
        -->
        <property name="autoDelimitKeywords" value="false"/>
        <!-- 生成的Java文件的編碼 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 格式化java代碼 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代碼 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>

        <!-- beginningDelimiter和endingDelimiter:指明數據庫的用於標記數據庫對象名的符號,好比ORACLE就是雙引號,MYSQL默認是`反引號; -->
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>


        <plugin type="com.github.abel533.generator.MapperPlugin">
            <property name="mappers" value="com.github.abel533.mapper.Mapper"/>
        </plugin>
        <!-- 必需要有的,使用這個配置連接數據庫 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="${master1.jdbc.url}"
                        userId="${master1.jdbc.username}"
                        password="${master1.jdbc.password}">
        </jdbcConnection>
        <!-- java模型建立器,是必需要的元素
        負責:1,key類(見context的defaultModelType);2,java類;3,查詢類
        targetPackage:生成的類要放的包,真實的包受enableSubPackages屬性控制;
        targetProject:目標項目,指定一個存在的目錄下,生成的內容會放到指定目錄中,若是目錄不存在,MBG不會自動建目錄
        -->
        <javaModelGenerator targetPackage="${targetModelPackage}" targetProject="${targetJavaProject}"/>

        <!-- 生成SQL map的XML文件生成器,
       注意,在Mybatis3以後,咱們可使用mapper.xml文件+Mapper接口(或者不用mapper接口),
        或者只使用Mapper接口+Annotation,因此,若是 javaClientGenerator配置中配置了須要生成XML的話,這個元素就必須配置
       targetPackage/targetProject:同javaModelGenerator
    -->
        <sqlMapGenerator targetPackage="${targetXMLPackage}" targetProject="${targetResourcesProject}"/>

        <!-- 對於mybatis來講,即生成Mapper接口,注意,若是沒有配置該元素,那麼默認不會生成Mapper接口
        targetPackage/targetProject:同javaModelGenerator
        type:選擇怎麼生成mapper接口(在MyBatis3/MyBatis3Simple下):
        1,ANNOTATEDMAPPER:會生成使用Mapper接口+Annotation的方式建立(SQL生成在annotation中),不會生成對應的XML;
        2,MIXEDMAPPER:使用混合配置,會生成Mapper接口,並適當添加合適的Annotation,可是XML會生成在XML中;
        3,XMLMAPPER:會生成Mapper接口,接口徹底依賴XML;
        注意,若是context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
         -->

        <javaClientGenerator targetPackage="${targetMapperPackage}" targetProject="${targetJavaProject}"
                             type="XMLMAPPER"/>

    </context>
</generatorConfiguration>

數據庫配置:

#MySQL
mysql.jdbc.url=jdbc:mysql://127.0.0.1:3306/sps_db?useUnicode=true&characterEncoding=UTF-8&amp;allowMultiQueries=true
mysql.jdbc.username=root
#鏈接數據庫的密碼.
mysql.jdbc.password=root
mysql.jdbc.initialSize=10
#鏈接池在空閒時刻保持的最大鏈接數.
mysql.jdbc.minIdle=10
#鏈接池在同一時刻內所提供的最大活動鏈接數。
mysql.jdbc.maxActive=100
#當發生異常時數據庫等待的最大毫秒數 (當沒有可用的鏈接時).
mysql.jdbc.maxWait=60000
mysql.jdbc.timeBetweenEvictionRunsMillis=60000
mysql.jdbc.minEvictableIdleTimeMillis=300000
mysql.jdbc.removeAbandonedTimeout=7200
mysql.jdbc.validationQuery=SELECT 'x'
mysql.jdbc.testWhileIdle=true
mysql.jdbc.testOnBorrow=false
mysql.jdbc.testOnReturn=false
mysql.jdbc.filters=slf4j
mysql.jdbc.removeAbandoned=true
mysql.jdbc.logAbandoned=true

#Redis
redis.ip=127.0.0.1
redis.port=6379
redis.timeout=6000
#Redis-pool
redis.pool.maxTotal=10000
redis.pool.maxIdle=1000
redis.pool.testOnBorrow=true

#RabbitMQ
rabbitmq.master.ip=127.0.0.1
rabbitmq.master.port=5672
rabbitmq.master.username=guest
rabbitmq.master.password=guest

接着再看這幾個

 applicationContext:

<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <context:component-scan base-package="com.guo.sps">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:server_config.properties</value>
                <value>classpath:sys_config.properties</value>
            </list>
        </property>
    </bean>

    <!-- 啓動AspectJ支持 -->
    <aop:aspectj-autoproxy/>

    <!-- jedis客戶端鏈接工廠 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.pool.maxTotal}"/>
        <property name="maxIdle"  value="${redis.pool.maxIdle}" />
        <property name="testOnBorrow"  value="${redis.pool.testOnBorrow}" />
    </bean>

    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.ip}" />
        <property name="port" value="${redis.port}" />
        <property name="usePool" value="true" />
        <property name="poolConfig" ref="jedisPoolConfig" />
        <property name="timeout" value="${redis.timeout}"/>
    </bean>
    <!-- redisTemplate模板 -->
    <bean id="stringRedisSerializer"
          class="org.springframework.data.redis.serializer.StringRedisSerializer" />
    <bean id="jdkRedisSerializer"
          class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
        <property name="KeySerializer" ref="stringRedisSerializer" />
        <property name="ValueSerializer" ref="stringRedisSerializer" />
        <property name="hashKeySerializer" ref="stringRedisSerializer"/>
        <property name="hashValueSerializer" ref="jdkRedisSerializer"/>
    </bean>

    <!--mysql datasource-->
    <bean id="dataSourceProxy" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${mysql.jdbc.url}" />
        <property name="username" value="${mysql.jdbc.username}" />
        <property name="password" value="${mysql.jdbc.password}" />
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${mysql.jdbc.initialSize}" />
        <property name="minIdle" value="${mysql.jdbc.minIdle}" />
        <property name="maxActive" value="${mysql.jdbc.maxActive}" />
        <!-- 配置獲取鏈接等待超時的時間 -->
        <property name="maxWait" value="${mysql.jdbc.maxWait}" />
        <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${mysql.jdbc.timeBetweenEvictionRunsMillis}" />
        <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${mysql.jdbc.minEvictableIdleTimeMillis}" />
        <property name="validationQuery" value="${mysql.jdbc.validationQuery}" />
        <property name="testWhileIdle" value="${mysql.jdbc.testWhileIdle}" />
        <property name="testOnBorrow" value="${mysql.jdbc.testOnBorrow}" />
        <property name="testOnReturn" value="${mysql.jdbc.testOnReturn}" />
        <property name="filters" value="${mysql.jdbc.filters}" />
        <!-- 打開removeAbandoned功能 -->
        <property name="removeAbandoned" value="${mysql.jdbc.removeAbandoned}" />
        <!-- 7200秒,也就是兩個小時 -->
        <property name="removeAbandonedTimeout" value="${mysql.jdbc.removeAbandonedTimeout}" />
        <!-- 關閉abanded鏈接時輸出錯誤日誌 -->
        <property name="logAbandoned" value="${mysql.jdbc.logAbandoned}" />
    </bean>

    <bean id="systemConfig" class="com.guo.core.common.constant.SystemConfig">
        <property name="guestUsername">
            <value>${shiro.guest.username}</value>
        </property>
    </bean>

    <!--事務管理DataSourceTransactionManager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSourceProxy" />
    </bean>
    <!-- mybatis session factory -->
    <bean id="sqlSessionFactory" class="com.guo.core.util.SqlSessionFactoryBeanUtil">
        <property name="configLocation" value="classpath:mybatis_config.xml" />
        <property name="dataSource" ref="dataSourceProxy" />
        <property name="mapperLocations" value="classpath*:com/guo/sps/dao/mapper/*.xml" />
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--如下方法,如save,update,insert等對數據庫進行寫入操做的方法,當產生Exception時進行回滾 -->
            <!--<tx:method name="*" propagation="REQUIRED" />-->
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="tx*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <aop:config expose-proxy="true">
        <!-- 只對業務邏輯層實施事務 -->
        <aop:pointcut id="txPointcut" expression="execution(public * com.guo.sps.services.*.*.*(..))" />
        <aop:pointcut id="subPointcut" expression="execution(public * com.guo.sps.services.*.*.*.*.*(..))" />
        <aop:pointcut id="basePointcut" expression="execution(public * com.guo.core.service.*.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="subPointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="basePointcut" />
    </aop:config>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.guo.sps.dao" />
    </bean>
</beans>

mybatis_config

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <typeAliases>
        <package name="com.guo.sps.dao.domain"/>
    </typeAliases>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql"/>
            <!-- 該參數默認爲false -->
            <!-- 設置爲true時,會將RowBounds第一個參數offset當成pageNum頁碼使用 -->
            <!-- 和startPage中的pageNum效果同樣-->
            <property name="offsetAsPageNum" value="true"/>
            <!-- 該參數默認爲false -->
            <!-- 設置爲true時,使用RowBounds分頁會進行count查詢 -->
            <property name="rowBoundsWithCount" value="true"/>
            <!-- 設置爲true時,若是pageSize=0或者RowBounds.limit = 0就會查詢出所有的結果 -->
            <!-- (至關於沒有執行分頁查詢,可是返回結果仍然是Page類型)-->
            <property name="pageSizeZero" value="true"/>
            <!-- 3.3.0版本可用 - 分頁參數合理化,默認false禁用 -->
            <!-- 啓用合理化時,若是pageNum<1會查詢第一頁,若是pageNum>pages會查詢最後一頁 -->
            <!-- 禁用合理化時,若是pageNum<1或pageNum>pages會返回空數據 -->
            <property name="reasonable" value="false"/>
            <!-- 3.5.0版本可用 - 爲了支持startPage(Object params)方法 -->
            <!-- 增長了一個`params`參數來配置參數映射,用於從Map或ServletRequest中取值 -->
            <!-- 能夠配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默認值 -->
            <property name="params"
                      value="pageNum=start;pageSize=limit;pageSizeZero=zero;reasonable=heli;count=contsql"/>
        </plugin>
        <plugin interceptor="com.github.abel533.mapperhelper.MapperInterceptor">
            <!--================================================-->
            <!--可配置參數說明(通常無需修改)-->
            <!--================================================-->
            <!--UUID生成策略-->
            <!--配置UUID生成策略須要使用OGNL表達式-->
            <!--默認值32位長度:@java.util.UUID@randomUUID().toString().replace("-", "")-->
            <!--<property name="UUID" value="@java.util.UUID@randomUUID().toString()"/>-->
            <!--主鍵自增回寫方法,默認值MYSQL,詳細說明請看文檔-->
            <property name="IDENTITY" value="MYSQL"/>
            <!--序列的獲取規則,使用{num}格式化參數,默認值爲{0}.nextval,針對Oracle-->
            <!--可選參數一共3個,對應0,1,2,分別爲SequenceName,ColumnName,PropertyName-->
            <property name="seqFormat" value="{0}.nextval"/>
            <!--主鍵自增回寫方法執行順序,默認AFTER,可選值爲(BEFORE|AFTER)-->
            <!--<property name="ORDER" value="AFTER"/>-->
            <!--通用Mapper接口,多個通用接口用逗號隔開-->
            <!-- <property name="mappers" value="com.github.abel533.mapper.Mapper"/>-->
            <property name="mappers" value="com.guo.core.dao.IBaseMapper"/>
            <!--<property name="enableUnderline" value="false"/>-->
        </plugin>
    </plugins>

</configuration>

spring_mvc

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">

    <!-- 啓用spring mvc 註解 -->
    <mvc:annotation-driven/>

    <!-- 設置使用註解的類所在的jar包 -->
    <context:component-scan base-package="com.guo.sps">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>

    <!--上傳文件解析器-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600"/>
        <property name="maxInMemorySize" value="4096"/>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
    <!-- 對轉向頁面的路徑解析。prefix:前綴, suffix:後綴 -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true"></property>
    </bean>
    <!--安全管理器-->
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"></property>
    </bean>


</beans>

spring_shiro

<?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:util="http://www.springframework.org/schema/util"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
       ">

    <!--配置securityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="statelessRealm"/>
    </bean>
    <!--statelessReealm-->
    <bean id="statelessRealm" class="com.guo.sps.realm.StatelessAuthRealm">
        <property name="cachingEnabled" value="false"/>
    </bean>
    <!--statelessFilter-->
    <bean id="statelessFilter" class="com.guo.sps.realm.filters.StatelessAuthcFilter"></bean>
    <!-- 基於Form表單的身份驗證過濾器 -->
    <bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
        <property name="usernameParam" value="username"/>
        <property name="passwordParam" value="password"/>
        <property name="rememberMeParam" value="rememberMe"/>
        <property name="loginUrl" value="/jsp/login"/>
    </bean>

    <!--配置shiroFilter-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="filters">
            <util:map>
                <entry key="stateless" value-ref="statelessFilter"/>
            </util:map>
        </property>
        <!--過濾鏈定義-->
        <property name="filterChainDefinitions">
            <value>
                /=anon
                /index.jsp=anon
                /app/**=stateless
            </value>
        </property>
    </bean>
    <!-- Shiro生命週期處理器-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

</beans>

Spring-rabbitmq

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

    <mvc:annotation-driven/>

    <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.master.ip}" port="${rabbitmq.master.port}"
                               username="${rabbitmq.master.username}" password="${rabbitmq.master.password}"/>
    <!-- 通用 template聲明 -->
    <rabbit:template id="amqpTemplate" connection-factory="connectionFactory"
                     exchange="order_topic_exchange" message-converter="gsonConverter"/>

    <rabbit:admin connection-factory="connectionFactory"/>
    <!-- queue 隊列聲明-->
    <rabbit:queue name="payRequestQueue" durable="true"/>
    <rabbit:queue name="payRequestCallbackQueue" durable="true"/>
    <rabbit:queue name="payNotifyQueue" durable="true"/>
    <!-- topic-exchange,做爲主題模式使用。
   匹配routingkey的模式,這裏匹配兩個queue
   queue_topic準備匹配key爲zhu.q1
   queue_topic2準備匹配key爲zhu.q2
    -->
    <rabbit:topic-exchange name="pay_topic_exchange">
        <rabbit:bindings>
            <rabbit:binding queue="payRequestQueue" pattern="payRequest.#"/>
            <rabbit:binding queue="payRequestCallbackQueue" pattern="payRequestCallback.#"/>
            <rabbit:binding queue="payNotifyQueue" pattern="payNotify.#"/>
        </rabbit:bindings>
    </rabbit:topic-exchange>
    <!--監聽器-->
    <rabbit:listener-container connection-factory="connectionFactory" acknowledge="manual" concurrency="10">
        <rabbit:listener queues="payRequestQueue" ref="payRequestQueueListener"/>
    </rabbit:listener-container>
    <!--MQ監聽支付請求入口消息-->
    <bean id="payRequestQueueListener" class="com.guo.sps.mq.PayRequestQueueListener"/>
    <!--MQ MSG序列化JSON轉換器-->
    <bean id="gsonConverter" class="com.guo.core.mq.Gson2JsonMessageConverter"/>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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"
         version="3.0">
    <display-name>Pay Map Service</display-name>
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>PayMap</param-value>
    </context-param>
    <!-- 加載配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml,classpath:spring_shiro.xml,classpath:spring_rabbitmq.xml
        </param-value>
    </context-param>

    <!-- LogBack Request MDC Filter -->
    <filter>
        <filter-name>MDCInsertingServletFilter</filter-name>
        <filter-class>
            ch.qos.logback.classic.helpers.MDCInsertingServletFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MDCInsertingServletFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- shiroFilter配置-->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 解決post亂碼 -->
    <filter>
        <description>字符集過濾器</description>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <description>字符集編碼</description>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>DruidWebStatFilter</filter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
        <init-param>
            <param-name>exclusions</param-name>
            <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>DruidWebStatFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>loggingFilter</filter-name>
        <filter-class>com.guo.core.web.system.filters.LoggingFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>loggingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <description>spring監聽器</description>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <description>Introspector緩存清除監聽器</description>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <listener>
        <description>request監聽器</description>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>                                 c
        <description>系統初始化監聽器</description>
        <listener-class>com.guo.core.web.system.listener.InitListener</listener-class>
    </listener>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/static/*</url-pattern>
    </servlet-mapping>
    <servlet>
        <description>spring mvc servlet</description>
        <servlet-name>springMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <description>spring mvc 配置文件</description>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring_mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <servlet-name>springMvc</servlet-name>
    </filter-mapping>

    <!-- session超時設置30分鐘 -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

這只是簡單的過來一遍,對大概的流程有個印象。須要配置文件的時候能找到。若是你有幸能看到這段話,那就好好加油吧。gogogo。

相關文章
相關標籤/搜索