SSH的框架整合


struts 控制用的   

hibernate 操作數據庫的 

spring 用解耦的 

 

 

第一步:先創建一個wed項目 。

 

 

 

第二步:配置struts2

1.添加Struts2所需要的基本jar包到 lib目錄下 包名如下圖:

 2.在web.xml 文件里添加struts的過濾器配置如下:《提示:struts2-2.3版本》

<?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</display-name>
  <welcome-file-list>
    <welcome-file>index.html</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>

 3.在web.xml 文件里添加struts的過濾器配置如下:《提示:struts2-2.5版本》

<?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</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
      <filter>
        <filter-name>struts-prepare</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareFilter</filter-class>
    </filter>

    <filter>
        <filter-name>struts-execute</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsExecuteFilter</filter-class>
    </filter>


    <filter-mapping>
        <filter-name>struts-prepare</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
        <filter-name>struts-execute</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 4.在src目錄下創建struts配置文件,struts.xml,內容如下:《提示:注意配置頭信息需要對應的版本》

<?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>
       <package name="struts2" extends="struts-default">
       </package>
   </struts> 

 

使用Struts2的好處:
1.實現了頁面和代碼的分離實現了mvc設計理念。
2.獲取表單內容,並組織生成參數對象
3.根據請求的參數轉發請求適當的控制器
4.在控制器中調用業務接口
5.將業務接口返回的結果包裝起來發送給指定的視圖,並由視圖完成處理結果的展現
6.做一些簡單的校驗或國際化工作



第三步:配置spring 

1.在lib目錄下導入spring相關的jar包如下:《提示:spring跟struts結合還需要2個struts的jar包分別是:

struts2-spring-plugin-2.3.30.jar和commons-logging-1.1.3.jar》

 

 2.在wed.xml文件下配置監聽器,配置如下:

 

 <!-- 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的好處:
(1)Spring能有效地組織你的中間層對象。
(2)Spring能消除在許多工程中常見的對Singleton的過多使用。
(3)Spring能消除各種各樣自定義格式的屬性文件的需要,使配置信息一元化。
(4)Spring能夠幫助我們真正意義上實現針對接口編程。
(5)在Spring應用中的大多數業務對象沒有依賴於Spring。
(6)使用Spring構建的應用程序易於單元測試
(7)Spring支持JDBC和O/R Mapping產品(Hibernate)
(8)MVC Web框架,提供一種清晰,無侵略性的MVC實現方式。
(9)JNDI抽象層,便於改變實現細節,可以方便地在遠程服務和本地服務間切換。
(10)簡化訪問數據庫時的例外處理。
(11)Spring能使用AOP提供聲明性事務管理,可以不直接操作JTA也能夠對事務進行管理。
(12)提供了JavaMail或其他郵件系統的支持。

 

第四步:配置hibernate

1.在lib目錄里導入hibernate相關的jar包如下:

 

2.在entity包下創建實體類

 

1 package ssh.entity;
 2 
 3 import java.math.BigDecimal;
 4 import java.util.Date;
 5 
 6 /*
 7  * 跟數據庫表一致,作為一個java對象
 8  * 1個對象代表的是數據庫表中的一行記錄
 9  * 1個屬性代表的是表中的一個字段
10  */
11 public class BookCard {
12     private int cid  ;
13     private String name;
14     private String sex ;
15     private Date cardDate;
16     private BigDecimal deposit;
17     
18     //定義get()、set()方法
19     public int getCid() {
20         return cid;
21     }
22     public void setCid(int cid) {
23         this.cid = cid;
24     }
25     public String getName() {
26         return name;
27     }
28     public void setName(String name) {
29         this.name = name;
30     }
31     public String getSex() {
32         return sex;
33     }
34     public void setSex(String sex) {
35         this.sex = sex;
36     }
37     public Date getCardDate() {
38         return cardDate;
39     }
40     public void setCardDate(Date cardDate) {
41         this.cardDate = cardDate;
42     }
43     public BigDecimal getDeposit() {
44         return deposit;
45     }
46     public void setDeposit(BigDecimal deposit) {
47         this.deposit = deposit;
48     }
49 
50 }

 

 

 

在entity創建實體類對應的xxx..hbm.xml映射文件。

 

 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC 
 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5 
 6 <hibernate-mapping>
 7     <class name="ssh.entity.BookCard" table="BookCard">
 8         <!-- 卡號 -->
 9         <id name="cid" column="cid">
10             <generator class="native"></generator>
11         </id>
12         <!-- 姓名 -->
13         <property name="name" column="name"></property>
14         <!-- 性別 -->
15         <property name="sex" column="sex"></property>
16         <!-- 辦卡日期 -->
17         <property name="cardDate" column="cardDate"></property>
18         <!-- 押金 -->
19         <property name="deposit" column="deposit"></property>
20     </class>
21 </hibernate-mapping>

 

 

 


3.應用IOC實現DAO接口

在Dao接口實現類里IndexDaoImpl定義一個sessionFactory的屬性提供一個set的方法,方便在spring里注入 注入方式如下:

 

  <bean id="myDao" class="dao.IndexDaoImpl" scope="prototype">
        <property name="sessionFactory" ref="mysessionFactory"></property> 
  </bean>
       
    <!-- mysql hibernate配置 -->
    <!-- 注入sessionFactory -->
    <bean id="mysessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 注入連接池,包含了數據庫用戶名,密碼等等信息 -->
        <property name="dataSource" ref="myDataSource2"></property>
        <!-- 配置Hibernate的其他的屬性 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.connection.autocommit">false</prop>
                <!-- 開機自動生成表 -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>entity/xxx.hbm.xml</value>
            </list>
        </property>    
    </bean>
    
    <bean id="myDataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/CardDB"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean> 

 使用hibernate的好處:

1.連接數據庫不用我們來管理。

2.原來是對表操作,現在是對對象操作。

 

環境第搭好了下面可寫代碼了

 

第五步 編寫IndexAction(action類)。

 

1 package ssh.action;
 2 
 3 import java.text.DecimalFormat;
 4 import java.util.List;
 5 
 6 import com.opensymphony.xwork2.ActionContext;
 7 import com.opensymphony.xwork2.ActionSupport;
 8 
 9 import ssh.entity.BookCard;
10 import ssh.service.IndexService;
11 
12 //創建IndexAction(action類)繼承ActionSupport接口
13 public class IndexAction extends ActionSupport {
14     
15     private static final long serialVersionUID = 1L;
16     
17     //聲明service,但不給它創建具體的實現類的實例,
18     private IndexService is = null;
19     //添加set()方法
20     public void setIs(IndexService is) {
21         this.is = is;
22     }
23     
24     //編寫execute()方法
25     public String execute() {
26         
27         //獲取IndexService實例,調用getAllBookCard()方法
28         //將結果保存到List集合里
29         List<BookCard> myBookCardList = is.getAllBookCard();
30         
31         //將查詢出來的結構集打印到控制台
32         System.out.println("結果集:"+myBookCardList.size());
33         
34         //獲取Context上下文對象
35         ActionContext ac = ActionContext.getContext();
36         //將myBookCardList集合添加到上下文對象里
37         ac.put("myBookCardList", myBookCardList);
38         
39         //返回一個字符串
40         return "success";
41     }
42     
43     //金額格式轉換
44     public String formatDouble(double s){
45         DecimalFormat fmat=new DecimalFormat("\u00A4##.0"); 
46         return fmat.format(s);
47     }
48     
49 }

 

 

 

第六步:在ssh.service包里編寫IndexService(接口類)和IndexServiceImpl(實現類)。

IndexService(接口類):

1 package ssh.service;
 2 
 3 import java.util.List;
 4 
 5 import ssh.dao.IndexDao;
 6 import ssh.entity.BookCard;
 7 
 8 //創建一個IndexService接口類
 9 public interface IndexService {
10     
11     
12     public List<BookCard> getAllBookCard();
13 
14 }
復制代碼

IndexServiceImpl(實現類):

1 package ssh.service;
 2 
 3 import java.util.List;
 4 
 5 import ssh.dao.IndexDao;
 6 import ssh.entity.BookCard;
 7 
 8 //創建IndexServiceImpl(實現類)實現IndexService接口
 9 public class IndexServiceImpl implements IndexService {
10 
11     //dao實例使用注入方式
12     private IndexDao id;
13     //用於注入使用
14     public void setId(IndexDao id) {
15         this.id = id;
16     }
17 
18 
19     @Override
20     public List<BookCard> getAllBookCard() {
21         //本類應該編寫業務邏輯的代碼,
22         //但本例沒有業務邏輯,就不用寫。
23         
24         //訪問數據庫的代碼,不會出現在service這一層
25         //交給dao來操作數據庫
26         List<BookCard> myBookCardList = id.getAllBookCard();
27         
28         //進行其它的業務邏輯操作,比如增加多一個選項,是否過期
29         //本例不需要
30         //....
31         
32         return myBookCardList;
33     }
34 
35 }

 IndexDao(接口類):

 1 package ssh.dao;
 2 
 3 import java.util.List;
 4 
 5 import ssh.entity.BookCard;
 6 
 7 //創建IndexDao(接口類)
 8 public interface IndexDao {
 9     
10     public List<BookCard> getAllBookCard();
11     
12 }

IndexDaoImpl(實現類):

1 package ssh.dao;
 2 
 3 import java.util.List;
 4 
 5 import org.hibernate.Session;
 6 import org.hibernate.SessionFactory;
 7 import org.hibernate.query.Query;
 8 
 9 import ssh.entity.BookCard;
10 
11 //創建IndexDaoImpl(實現類)實現IndexDao接口
12 public class IndexDaoImpl implements IndexDao {
13     
14     //在SSH的設計理念:要使用某個實例,那么就定義聲明一個對象,然后
15     //給它添加set方法(用於spring注入進來)
16     //實現不要關注這個實例來自於那里,以及怎么創建,或者它是誰    
17     private SessionFactory sessionFactory;
18     
19     public void setSessionFactory(SessionFactory sessionFactory) {
20         this.sessionFactory = sessionFactory;
21     }
22 
23 
24     @Override
25     public List<BookCard> getAllBookCard() {
26         
27         //sessionFactory這個實例可以自己按常規的hibernate傳統寫法創建
28         //也可以交給spring去托管
29         /*
30         Configuration cfg = new Configuration().configure();
31         sessionFactory = cfg.buildSessionFactory();*/
32         
33         //獲取session
34         Session session = sessionFactory.openSession();
35             
36         //后面當使用JPA的時候,EntityManager 類似於 Session
37         Query query = session.createQuery("from BookCard");
38         
39         //將所有的數據查詢出來並放到List集合里
40         List<BookCard> list = query.getResultList();
41         
42         //將集合遍歷循環
43         for(BookCard bookCard:list){
44             //打印輸出到控制台
45             System.out.println(bookCard);
46         }
47         
48         //關閉session
49         session.close();
50         //關閉sessionFactory
51         sessionFactory.close();
52         //返回list集合
53         return list;
54         
55     }
56 
57 }

運行結果:

  瀏覽器顯示:

   

  控制台輸出:

   

   


免責聲明!

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



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