SSH框架整合項目(一)——搭建平台和引入依賴


前言:這個項目是我的第一個實驗性項目,最初的立意是制作一個個性化的BBS。由於BBS能夠綜合大部分功能,因此作為練手的項目來說再好不過。從寫第一行代碼到完成測試版大概歷時2周。中間遇到了不少以前在學習中沒有想到的問題,當然通過解決這些難題也更加深了對MVC模型的理解。本來打算至少完成1.0版本以后再發布出來,可惜由於新工作的原因估計短時間內很難繼續完成。所以就湊合把兩周中間我經歷的種種記錄於此。

項目后台通過Struts2+Spring+Hibernate搭建,前台使用了比較簡單的Div+CSS+jQuery作為展示。

一、通過Maven管理依賴

這個過程比較復雜,雖然在網上能夠查到不少現成的Maven依賴配置。但出於學習考慮,我還是手動添加並通過不斷測試盡量將引入的依賴最小化。除了對基本框架的依賴以外,還有不少依賴關系是跟隨項目開發進程不斷引入的。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.learnhow</groupId>
    <artifactId>bbs2016</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>bbs2016 Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <!-- 添加上傳依賴,自動添加io依賴 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- 添加json-lib依賴 -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <!-- 添加tomcat -->
        <dependency>
            <groupId>tomcat</groupId>
            <artifactId>jasper-runtime</artifactId>
            <version>5.5.23</version>
        </dependency>
        <!-- 特別添加jdom,由於此依賴包並非從maven庫中下載,因此事先需要在本地的maven庫中添加此版本的jar包 -->
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom</artifactId>
            <version>2.0.6</version>
        </dependency>
        <!-- 添加jstl依賴 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
            <scope>compile</scope>
        </dependency>
        <!-- 添加spring整合hibernate依賴包 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <!-- 添加hibernate基礎依賴 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.11.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.36</version>
        </dependency>
        <!-- 添加struts整合spring依賴包 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.3.24</version>
        </dependency>
        <!-- 添加spring-web包的依賴,主要是為了以后開發方便 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <!-- 添加spring基礎依賴包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <!-- 添加struts依賴包 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.24</version>
            <!-- 這里排除掉隊javassist的依賴,通過hibernate包引入 -->
            <exclusions>
                <exclusion>
                    <groupId>javassist</groupId>
                    <artifactId>javassist</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- 添加junit依賴包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>bbs2016</finalName>
    </build>
</project>
Maven

二、配置文件

SSH搭建框架的關鍵主要有三點:

(1)Struts2通過Spring提供的ObjectFactory獲取各種Action實例

(2)Hibernate使用Spring的控制翻轉來注入SessionFactory,並集成事務管理

(3)使用Tomcat監聽器對Spring容器初始化

首先應該配置的是Tomcat容器,這里千萬不要使用由IDE自動為你產生的web.xml文件。注意文件頭的部分,我的建議是從Tomcat里找到相關的配置信息復制過來。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1" metadata-complete="true">

    <!-- 盡量使用web.xml的標准寫法 -->
    <display-name>bbs2016 by learnhow</display-name>
    <!-- 設置歡迎頁面 -->
    <welcome-file-list>
        <welcome-file>home_browseHome</welcome-file>
    </welcome-file-list>
    <!-- 配置struts2核心轉發器 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 配置spring前端監聽器,當服務器啟動的時候初始化xml配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>framework.ApplicationScopeLoaderListener</listener-class>
    </listener>
    <context-param>
        <!-- 所有需要初始化的xml都可以在這里配置 -->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml,classpath:springhibernate.xml</param-value>
    </context-param>
</web-app>
web.xml

接下來就可以配置struts.xml,同樣建議從Struts2提供的配置文件中復制相關文件頭。注意我在Maven里引入的Struts版本為2.3。(注:最初引入配置文件的時候只需要清空package標簽內部的action)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <!-- 這個配置是用來指定struts2框架對於上傳文件的臨時路徑,如果不指定會采用servlet容器的默認路徑。 <constant name="struts.multipart.saveDir" 
        value=""/> -->
    <!-- 指定由spring容器產生action實例,這樣才能注入需要服務 -->
    <constant name="struts.objectFactory" value="spring" />
    <!-- struts配置文件改動后,是否重新加載(生產環境中建議設置為false) -->
    <constant name="struts.configuration.xml.reload" value="true" />
    <!-- 關閉動態方法調用 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <!-- 請求參數的編碼方式 -->
    <constant name="struts.i18n.encoding" value="utf-8" />
    <package name="default" namespace="/" extends="struts-default">
        <!-- 配置默認請求轉發地址 -->
        <default-action-ref name="home" />
        <global-results>
            <result name="home" type="redirect">home_browseHome</result>
            <result name="error">/WEB-INF/jsp/error.jsp</result>
        </global-results>
        <action name="home">
            <result type="redirect">home_browseHome</result>
        </action>
        <action name="register">
            <result>/WEB-INF/jsp/register.jsp</result>
        </action>
        <action name="custom">
            <result>/WEB-INF/jsp/custom.jsp</result>
        </action>
        <!-- 使用通配符的方法調用 -->
        <action name="home_*" class="action.HomeAction" method="{1}">
            <result name="home">/WEB-INF/jsp/home.jsp?page=${pageIndex}</result>
            <result name="success">/WEB-INF/jsp/success.jsp</result>
            <result name="error">/WEB-INF/jsp/error.jsp</result>
        </action>
        <action name="login_*" class="action.LoginAction" method="{1}">
            <result name="success" type="stream">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
            </result>
        </action>
        <action name="ajax_*" class="action.AjaxAction" method="{1}">
            <result name="success" type="stream">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
            </result>
        </action>
        <action name="register_*" class="action.RegisterAction" method="{1}">
            <result name="repeat" type="stream">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
            </result>
        </action>
        <action name="post_*" class="action.PostAction" method="{1}">
            <result name="browse" type="redirect">browse_browse?msgid=${msgid}
            </result>
        </action>
        <action name="browse_*" class="action.BrowseAction" method="{1}">
            <result name="browse">/WEB-INF/jsp/browse.jsp</result>
        </action>
        <action name="upload_*" class="action.UploadAction" method="{1}">
            <result name="success" type="redirect">custom</result>
        </action>
    </package>
</struts>
struts.xml

順帶插一句有關jsp中文亂碼的解決方案。上面引入的是struts2文件中的配置方法,另一種更簡單的方法是采用Tomcat容器提供的filter。

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
</filter>
web.xml

然后開始配置Hibernate,由於是通過Spring整合的Hibernate,這個部分的配置實際上已經屬於Spring的范疇。

<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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 配置數據源 -->
    <bean id="dataSource" destroy-method="close"
        class="org.apache.commons.dbcp2.BasicDataSource">
        <!-- 連接信息通過spring.xml文件引入 -->
        <property name="driverClassName" value="${mysql.driver}" />
        <property name="url" value="${mysql.url}" />
        <property name="username" value="${mysql.username}" />
        <property name="password" value="${mysql.password}" />
    </bean>

    <!-- 通過數據源初始化sessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 包掃描,不用單獨配置.hbm.xml文件 -->
        <property name="packagesToScan">
            <list>
                <value>model</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=${hibernate.dialect}
                hibernate.show_sql=${hibernate.show_sql}
                hibernate.hbm2ddl.auto=${hibernate.hbm2ddl.auto}
                hibernate.format_sql=${hibernate.format}
            </value>
        </property>
    </bean>

    <!-- 通過注入sessionFactory獲取事務控制器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- 事務建言:事務控制器的詳細配置 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 啟用事物的方法前綴 -->
            <tx:method name="add*" />
            <tx:method name="save*" />
            <tx:method name="update*" />
            <tx:method name="delete*" />
            <tx:method name="remove*" />
            <!-- 僅適用只讀事物的方法前綴 -->
            <tx:method name="get*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="load*" read-only="true" />
            <!-- 默認其他方法不開啟事物 -->
            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>

    <!-- 注解方式配置事物 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- 配置需要添加事務控制的切點 -->
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* service.impl.*.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
            advice-ref="txAdvice" />
    </aop:config>
    
    <!-- 配置dao上的事務管理,主要是為了調試底層,方便數據庫實現的操作,最后應該刪除切記!!! -->
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* dao.nimpl.*.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
            advice-ref="txAdvice" />
    </aop:config>
    
</beans>
springhibernate.xml

有關database.properties的配置選項在下面(密碼請填寫自己的MySQL登錄密碼)

#config mysql
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/bbs2016
mysql.username=root
mysql.password=
#config hibernate 
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=update
hibernate.format=true
database.properties

最后是引入包掃描和占位符文件的配置信息,這個部分在Spring中又被稱為Root 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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 掃描數據庫配置文件 -->
    <context:property-placeholder location="classpath:database.properties" />
    
    <context:component-scan base-package="dao,service,model" />

</beans>
spring.xml

 

篇幅所限,先寫到這里。有關配合方面的說明基本到這里結束,下一章開始寫一些設計和代碼方面的東西,更多干貨可以期待哦。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM