首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

SSH 框架整合完整實戰:Struts2 + Spring + Hibernate 手把手搭建教程

     編輯:Java 綜合教學

SSH 框架整合完整實戰:Struts2 + Spring + Hibernate 手把手搭建教程

基於 MyEclipse 9 內置框架支持,記錄 Struts 2.3.24 + Hibernate 3.6.10 + Spring 4.3.2 + MySQL 5.5 整合全流程,含 JAR 管理、三層代碼、核心配置、事務管理、連接池優化、懶加載解決。

一、Web 項目創建與框架支持添加

  1. New → Web Project
  2. 右鍵項目 → MyEclipse → Add Framework Support → 勾選 Struts2、Hibernate、Spring
  3. 注意:Struts2 與 Hibernate 共用 antlr JAR,版本衝突需排除一份 (MyEclipse 9 有此問題,10 版本已修復)

新建 Web 項目 添加 Hibernate 添加 Struts2 添加 Spring Struts2 JAR Hibernate JAR antlr 衝突 排除 antlr Spring JAR

二、三層架構代碼實現

實體類與映射 (DB Browser 反向生成)

DB Browser 反向生成1 反向生成2

DAO 接口與實現 (兩種 HibernateTemplate 用法)

// 方式1:繼承 HibernateDaoSupport
public class UsersDaoImpl extends HibernateDaoSupport implements UsersDao {
    public Users loginCheck(Users u) {
        List<Users> list = getHibernateTemplate().find(
            "from Users where name=? and password=?", u.getName(), u.getPassword());
        return list.size()>0 ? list.get(0) : null;
    }
}

// 方式2:注入 HibernateTemplate
public class DistrictDaoImpl implements DistrictDao {
    private HibernateTemplate hibernateTemplate;
    public int addReg(District d) {
        try { hibernateTemplate.save(d); return 1; }
        catch (DataAccessException e) { return 0; }
    }
    // getter/setter
}

Service 接口與實現

public class UsersServiceImpl implements UsersService {
    private UsersDao udd;
    public Users loginCheck(Users u) { return udd.loginCheck(u); }
    // getter/setter
}

Action 控制器 (實現 RequestAware 存取 request)

public class UsersAction extends ActionSupport implements RequestAware {
    private Map<String,Object> request;
    private UsersService uss;
    public String login() {
        Users u = uss.loginCheck(getUser());
        if (u != null) { request.put("user", u); return SUCCESS; }
        return LOGIN;
    }
    // getter/setter
}

三、核心配置文件

web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<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>

<!-- 解決懶加載: OpenSessionInViewFilter -->
<filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>openSessionInViewFilter</filter-name>
    <url-pattern>*.action</url-pattern>
</filter-mapping>

struts.xml

<package name="user" namespace="/" extends="struts-default">
    <action name="*User" class="userAction" method="{1}">
        <result name="success">/success.jsp</result>
        <result name="login">/login.jsp</result>
    </action>
</package>

applicationContext.xml (完整版:數據源 + SessionFactory + 聲明式事務 AOP + Bean 裝配)

<beans xmlns="..." xmlns:aop="..." xmlns:tx="...">
    <!-- 1. C3P0 連接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="user" value="root"/>
        <property name="password" value="admin"/>
        <property name="initialPoolSize" value="1"/>
        <property name="minPoolSize" value="1"/>
        <property name="maxPoolSize" value="300"/>
        <property name="maxIdleTime" value="60"/>
        <property name="acquireIncrement" value="5"/>
        <property name="idleConnectionTestPeriod" value="60"/>
    </bean>

    <!-- 2. SessionFactory (掃描映射文件) -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>com/entity/District.hbm.xml</value>
                <value>com/entity/House.hbm.xml</value>
                <value>com/entity/Street.hbm.xml</value>
                <value>com/entity/Type2.hbm.xml</value>
                <value>com/entity/Users.hbm.xml</value>
            </list>
        </property>
    </bean>

    <!-- 3. 事務管理器 -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- 4. 事務通知 (AOP) -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="serviceMethod" expression="execution(* com.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
    </aop:config>

    <!-- 5. Bean 裝配 -->
    <bean id="userDaoImpl" class="com.dao.impl.UsersDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <bean id="userServiceImpl" class="com.service.impl.UsersServiceImpl">
        <property name="udd" ref="userDaoImpl"/>
    </bean>
    <bean id="userAction" class="com.action.UsersAction">
        <property name="uss" ref="userServiceImpl"/>
    </bean>
    <!-- District 同理 -->
</beans>

四、Spring 創建數據源圖解 (MyEclipse 可視化操作)

Spring DataSource 1 Spring DataSource 2 Spring DataSource 3 Spring DataSource 4

五、測試驗證與懶加載解決

  1. 部署 Tomcat 6
  2. 訪問 https://localhost:8080/ssh/user
  3. index.jsp 顯示 ${user.username} 成功
  4. 嘗試 ${user.dept.deptName} 拋出 LazyInitializationException
  5. 添加 OpenSessionInViewFilter 映射 *.action 解決

測試成功 懶加載異常 解決後

六、關鍵知識點總結

環節核心要點
JAR 衝突antlr 重複,排除 Struts2 中的
事務管理Spring AOP 織入 Service 層,方法名規則匹配
Struts-Spring 整合Action 在 Spring 定義 Bean,struts.xml class 指向 Bean ID
懶加載OpenSessionInViewFilter 延長 Session 至視圖渲染結束
連接池C3P0 替換默認 JDBC,配置核心參數
映射文件*.hbm.xml 放 classpath,SessionFactory 掃描 mappingResources
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved