歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Eclipse搭建SSH(Struts2+Spring+Hibernate)框架教程

Eclipse搭建SSH(Struts2+Spring+Hibernate)框架教程

日期:2017/3/1 9:09:26   编辑:Linux編程

前言

對於Eclipse搭建SSH(Struts2+Spring+Hibernate)框架這個陌生的東西還是有些許淡然。這是我的第一篇文章,希望能給你們有幫助,這就是我最大的樂趣!

好了下面進入正題:

SSH框架簡介:①SSH框架是由struts2、spring、hibernate三大框架組合起來的一套總框架,一般來說這三個東西我們不會單獨使用。

        ②在學習SSH框架之前建議讀者先學mvc,因為SSH是在mvc基礎上根據mvc的缺點而產生的一套比較成熟的框架,也比較穩定。

        ③SSH框架的流程:浏覽器(或客戶端)發送請求到服務器,先經過項目中web.xml中過濾器(<filter>和<filter-mapping>)審核,通過了再發送給action包中的IndexAction類,struts.xml根據IndexAction類中return的值再進行跳轉,跳轉的頁面是struts.xml中<result>配置的頁面名,然後頁面響應回客戶端(至於怎麼響應的就是當客戶敲回車之後就有一個頁面顯示)。

        ④struts的核心思想:實現mvc

        ⑤spring的核心思想:解耦,也就是代碼中不出現new實現類的代碼,我們創建了接口不用關心實現類是誰,實現類由spring幫我們注入,我們只需要在定義接口的時候給它一個set方法並且在配置文件裡改<property>中的id和ref就行

        ⑥hibernate的核心思想:連接數據庫,我們不用在數據庫寫創建表的語句,數據庫表的字段根據實體類中屬性的名字然後我們在BookCard.hbm.xml文件裡配置<property>以及<property>的相關屬性。

搭建前需要注意事項(搭建前應准備):

  1.需要用到的技術(必須了解):Struts2/spring(新版spring官網不能直接下載,可以百度下載別人打包好的)/hibernate(S-S-H

  2.需要用到的工具:eclipse

  3.需要用到的包:①structs2.3.30 ②spring-framework-4.2.2.RELEASE-dist ③hibernate-release-5.2.2.Final

  4.建議運行環境:①Windows 7-64位 ②Tomcat 8.0 ③jdk1.8.0_91 ④SQL server2008 ⑤Eclipse JavaEE環境下

博主建議:1.讀者在看本文之前讀者必須了解mvc

      2.讀者必須按照文的步驟來閱讀和操作

     3.博主不會寫沒有作用的注釋代碼,讀者要好好體會每一句注釋代碼的意義(綠色的字體代表的是注釋)

      4.本文Struts、spring、hibernate中所有導的包都放在WEB-INF-->lib目錄下

      5.軟件工程思想(靈魂):高內聚、低耦合

      6.必須熟知每個包的作用:action包(跳轉),service包(服務/業務邏輯),dao包(訪問數據庫),entity包(實體類),util包(工具包)。在創建包的同時我們要新建的接口以及實現類有: ①在service包創建接口IndexService(名字隨意但最好有意義)以及實現類IndexServiceImpl(名字隨意但最好有意義) ②在dao包新建接口IndexDao以及實現類IndexDaoImpl ③在util包新建接口MyConnection以及實現類MyConnectionImpl

      7.本來util包有兩個作用:工具包、連接數據庫包,但加入了hibernate之後取代了連接數據庫的功能,現在的util包只做工具包。

正式開始:

  第一步:新建一個web項目,並勾上Generate web.xml deployment descriptor。如下圖:

    

-----------------------------------------------------------------------

               

  第二步:導入struts的所有jar包放在lib目錄下(structs2.3.30\struts-2.3.30-apps\struts-2.3.30\apps\struts2-showcase\WEB-INF\lib)

            

  第三步: 打開web.xml文件。

       目錄:【WebContent-->WEB-INF目錄-->web.xml】 如下圖:

             

打開web.xml之後出現如下代碼:

<?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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" id="WebApp_ID" version="3.0">
    <display-name>TestSSH</display-name>
    <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      <welcome-file>default.html</welcome-file>
      <welcome-file>default.htm</welcome-file>
      <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
 </web-app>

改成如下(直接把以下代碼拷貝覆蓋原來的代碼)

<?xml version="1.0" encoding="UTF-8"?>

 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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" id="WebApp_ID" version="3.0">

  <display-name>TestSSH</display-name>
  
  //配置首頁
  <welcome-file-list>     <welcome-file>index.action</welcome-file>   </welcome-file-list>   //配置過濾器   <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> </web-app>

  第四步:在src目錄下新建五個包:action(跳轉)包、service(服務/業務邏輯)包、dao(訪問數據庫)包、entity(實體類)包、util(工具)包。如下圖:

            

  第五步:在action包下新建IndexAction類並繼承Actionsupport,目的是為了讓本類擁有ActionSupport類的方法

package action;

import com.opensymphony.xwork2.ActionSupport;

public class IndexAction extends ActionSupport{
    //定義Struts默認的方法
    public String execute(){
        //返回字符串類型給struts.xml文件接收
        return "success";
    }
    //定義錯誤時應調用方法
    public String error(){
        //返回字符串類型給struts.xml文件接收
        return "error";
    }
} 

第六步:在src目錄下創建struts.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<!-- 上面的頭,注意版本,從樣例裡復制過來 showcase.war\WEB-INF\src\java\struts.xml -->

<struts>
    <!-- 第1步:先定義一個包,名字任意取 並繼承struts-default-->
    <package name="mypck" extends="struts-default">
        <!-- 第2步:①定義一個action,配置跳轉信息 name 類似於Servlet,這個name是浏覽器要訪問的name,很重要,②class的值:包名.類名 
            http://xxxx/xxx/Index.action http://xxxx/xxx/Index class 對應於自己寫的Action類 當不寫method屬性時,默認調用的是execute -->
        <action name="Index" class="ssh.IndexAction" method="exe2">
             <!-- 跳轉是forward /WEB-INF/是防止jsp不經過action就可以訪問  -->
              <!-- success和error是從action類中return回的值,要與action類return值一樣 -->
              <!-- index2.jsp和error.jsp表示要跳轉的頁面 -->
            <result name="success">/WEB-INF/index2.jsp</result>
            <result name="error">/WEB-INF/error.jsp</result>
        </action>
    </package>
</struts> 

經過以上步驟我們SSH中的struts2已經配置好了,下面是配置Spring:

第七步:導jar包(\spring-framework-4.2.2.RELEASE\libs全部拷貝 以Javadoc和source為後綴的不要

      如下圖:

           

第八步:在web.xml文件裡配置監聽器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>ssh_001</display-name>
    <welcome-file-list>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <!-- Struts過濾器 -->
    <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的監聽器配置開始 -->
    <!-- spring監聽器的作用:提供實例 -->
    <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>
    <!-- spring的監聽器配置結束 -->
</web-app> 

第九步:在struts.xml文件裡配置<constant name="struts.objectFactory" value="spring" />

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<!-- 上面的頭,注意版本,從樣例裡復制過來 showcase.war\WEB-INF\src\java\struts.xml -->

<struts>
    <!-- 這裡是spring配置 -->
    <!-- 告知Struts2運行時使用Spring來創建對象 -->
    <constant name="struts.objectFactory" value="spring" />

    <!-- 第1步:先定義一個包,名字任意取 -->
    <package name="mypck" extends="struts-default">
        <!-- 第2步:定義一個action,配置跳轉信息 name 類似於Servlet,這個name是浏覽器要訪問的name,很重要,class的值:包名.類名       
            http://xxxx/xxx/Index.action http://xxxx/xxx/Index class 對應於自己寫的Action類 當不寫method屬性時,默認調用的是execute -->
        <action name="Index" class="ssh.IndexAction" method="exe2">
             <!-- 跳轉是forward /WEB-INF/是防止jsp不經過action就可以訪問  -->
              <!-- success和error是從action類中return回的值,要與action類return值一樣 -->
              <!-- index2.jsp和error.jsp表示要跳轉的頁面 -->
            <result name="success">/WEB-INF/index2.jsp</result>
            <result name="error">/WEB-INF/error.jsp</result>
        </action>
    </package>
</struts> 

第十步:在src目錄下新建application.xml文件


<?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">    <!-- ①一個bean標簽對應一個類,id為myIndexAction的bean就對應項目中的IndexAction類 ②id的值是隨便起,但最好有意義 ③class的值是包名.類名 ④scope="prototype"是非單例,不用理解,但一定要寫這句代碼,記住有這回事就行 --> <bean id="myIndexAction" class="ssh.action.IndexAction" scope="prototype">    <!-- ①name的值是要注入的變量名 ②ref是引用類的類名,name為“is”的變量引用的是myIndexService的值 --> <property name="is" ref="myIndexService"/> </bean>    <!-- myIndexService = new ssh.service.IndexServiceImpl() id為myIndexService的bean對應項目中的IndexService類--> <bean id="myIndexService" class="ssh.service.IndexServiceImpl" scope="prototype">
    <!-- name為id的變量引用的是myIndexDao的值 --> <property name="id" ref="myIndexDao"/> </bean> <bean id="myIndexDao" class="ssh.dao.IndexDaoImpl" scope="prototype"> <property name="c" ref="myConnection"></property> </bean>

   <!-- 下面這個bean是對應項目中的connection類,class的值是包名.類名 --> <bean id="myConnection" class="ssh.util.MyConnectionImpl_SQLSERVER" scope="prototype">    <!-- 這裡沒有<property>是因為connection這個類已經是連接數據庫的類,我們已經不需要通過new實現類了 --> </bean>
</beans>

以上就是struts和spring的使用,接下來是SSH中的最後一個,也是最重要的一個:hibernate

  第十一步:導jar包(hibernate-release-5.2.2.Final\lib\required所有包)

         

  第十二步:把(hibernate-release-5.2.2.Final\project\hibernate-core\src\test\resources)目錄下的hibernate.cfg.xml文件放在src目錄下。

          

  第十三步:在hibernate.cfg.xml文件裡最頂部加上<?xml version="1.0" encoding="utf-8"?>

    如圖:

  

  第十四步:配置hibernate.cfg.xml文件,並配置映射文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC 
"-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- hibernate配置文件 -->
     <!-- 配置數據庫名,以及用戶名,密碼 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/CardDB</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- 每個數據庫都有1個 --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="connection.pool_size">5</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- 配置映射文件 --> <mapping resource="ssh/entity/BookCard.hbm.xml"/> </session-factory> </hibernate-configuration>

   第十五步:配置BookCard.hbm.xml(實體類配置)文件

<?xml version="1.0" encoding="UTF-8"?>
<hibernate-mappingxmlns="http://www.hibernate.org/xsd/hibernate-mapping">
<!-- ①class的值是包名.實體類名 ②table的值是數據庫表名-->
<classname="ssh.entity.BookCard" table="BookCard">
<!-- ①<id>標簽是要作為主鍵的屬性或字段才能用 ②column是數據庫的字段名-->
<idname="cid" column="cid">
<generatorclass="native"></generator>
</id>
<!-- <property>標簽對應於屬性(數據庫字段)在<property>標簽中設置數據庫相關的屬性,比如長度、類型、是否為空、列名...等等-->
<propertyname="name" type="string" length="50" column="name" not-null="true"></property>
<propertyname="sex" type="string" length="2" column="sex"></property>
<propertyname="cardDate" type="date" column="cardDate"></property>
<propertyname="deposit" type="double" column="deposit"></property>
</class>
</hibernate-mapping> 第十六步:在IndexDaoImpl實現類中構造SessionFactory
package ssh.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

public class IndexDaoImpl implements IndexDao {
  <!-- SessionFactory是hibernate的內置對象 --> private SessionFactory sessionFactory;
  <!-- 給SessionFactory一個set方法,便於spring注入 --> public void setSessionFactory(SessionFactory sf) { this.sessionFactory = sf; } @Override public List<BookCard> getAllBookCard() { <!-- sessionFactory這個實例可以自己按常規的hibernate傳統寫法創建也可以交給spring去托管sessionFactory = new Configuration().configure().buildSessionFactory(); --> Session session = sessionFactory.openSession(); } }

以上就是eclipse搭建SSH框架的全過程,接下來就可以在service相關類以及dao相關類編寫我們的代碼!

有不懂的或者要提意見的可以關注博主,我們來互相探討。

Copyright © Linux教程網 All Rights Reserved