SSH整合

  • 2019 年 10 月 7 日
  • 筆記

Struts2的配置文件是struts.xml和web.xml

Spring的配置文件是applicationContext.xml和web.xml

Hibernate的配置文件是實體映射配置文件和hibernate.cfg.xml和jdbc.properties

總的流程大致是web層調用Service層,Service層調用DAO層,然後返回

詳細流程就是:

1.jsp頁面提交表單,通過web.xml里配置的過濾器找到struts.xml里對應的action和方法

2.web層通過applicationContext.xml注入了Service層的對象,從而調用Service層的方法

3.Service層通過applicationContext.xml注入了DAO層的對象,從而調用DAO層的方法

4.DAO層資料庫連接的配置在applicationContext.xml中(或hibernate.cfg.xml),連接到資料庫後,使用模板執行sql

文件結構圖

配置內容:

實體映射配置文件

<?xml version='1.0' encoding='utf-8'?>  <!DOCTYPE hibernate-mapping PUBLIC          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"          "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">  <hibernate-mapping>      <!--建立類與表的映射-->      <!--如果類中的屬性名和表中的欄位名一直,column可以省略-->      <class name="com.jinke.ssh.domain.Customer" table="customer">          <!--建立類中的屬性與表中的主鍵對應-->          <id name="id" column="id">              <generator class="native"/>          </id>            <!--建立類中的普通屬性和標的欄位的對應-->          <property name="name" column="name"/>          <property name="source" column="source"/>          <property name="industry" column="industry"/>          <property name="level" column="level"/>          <property name="phone" column="phone"/>          <property name="mobile" column="mobile"/>      </class>        <query name="queryAll">from Customer</query>  </hibernate-mapping>

applicationContext.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: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/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">        <!--配置C3P0連接池-->      <context:property-placeholder location="classpath:jdbc.properties"/>        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">          <property name="driverClass" value="${jdbc.driverClass}"/>          <property name="jdbcUrl" value="${jdbc.url}"/>          <property name="user" value="${jdbc.username}"/>          <property name="password" value="${jdbc.password}"/>      </bean>        <!--Spring整合hibernate-->      <!--引入hibernate的配置資訊-->      <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">          <!--引入hibernate的配置文件-->          <!--<property name="configLocation" value="classpath:hibernate.cfg.xml"/>-->          <!--注入連接池-->          <property name="dataSource" ref="dataSource"/>          <!--配置hibernate相關屬性-->          <property name="hibernateProperties">              <props>                  <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>                  <prop key="hibernate.show_sql">true</prop>                  <prop key="hibernate.format_sql">true</prop>                  <prop key="hibernate.hbm2ddl.auto">update</prop>              </props>          </property>            <!--設置映射文件-->          <property name="mappingResources">              <list>                  <value>com/jinke/ssh/domain/Customer.hbm.xml</value>              </list>          </property>      </bean>        <!--配置Action 方法二-->      <bean id="customerAction" class="com.jinke.ssh.web.action.CustomerAction" scope="prototype">          <property name="customerService" ref="customerService"/>        </bean>        <!--配置service-->      <bean id="customerService" class="com.jinke.ssh.service.impl.CustomerServiceImpl">          <property name="customerDao" ref="customerDao"/>      </bean>        <!--配置DAO-->      <bean id="customerDao" class="com.jinke.ssh.dao.impl.CustomerDaoImpl">          <property name="sessionFactory" ref="sessionFactory"/>      </bean>        <!--配置事務管理器-->      <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">          <property name="sessionFactory" ref="sessionFactory"/>      </bean>        <!--開啟註解事務-->      <tx:annotation-driven transaction-manager="transactionManager"/>    </beans>

hibernate.cfg.xml(如果DAO層是由Spring配置的話,此文件可不寫)

<?xml version='1.0' encoding='utf-8'?>  <!DOCTYPE hibernate-configuration PUBLIC          "-//Hibernate/Hibernate Configuration DTD//EN"          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  <hibernate-configuration>      <session-factory>          <!--必須配置===============-->          <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>          <property name="hibernate.connection.url">              jdbc:mysql://localhost:3306/ssh?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT          </property>          <property name="hibernate.connection.username">root</property>          <property name="hibernate.connection.password">1234</property>          <!--配置Hibernate的方言-->          <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>            <!--可選配置===============-->          <!--列印sql-->          <property name="hibernate.show_sql">true</property>          <!--格式化sql-->          <property name="hibernate.format_sql">true</property>          <!--自動創建表-->          <property name="hibernate.hbm2ddl.auto">update</property>            <!--配置C3P0連接池-->          <property name="connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>          <!--在連接池中可用的資料庫連接的最少數目-->          <property name="c3p0.min_size">5</property>          <!--在連接池中所有資料庫的最大數目-->          <property name="c3p0.max_size">20</property>          <!--設定資料庫連接的過期時間,以秒為單位,如果連接池中的某個資料庫連接處於空閑狀態的時間超過了timeout時間,就會從連接池中清除-->          <property name="c3p0.timeout">120</property>          <!--每3000秒檢查所有連接池中的空閑連接 以秒為單位-->          <property name="c3p0.idle_test_period">3000</property>              <!--映射文件的引用===============-->          <mapping resource="com/jinke/ssh/domain/Customer.hbm.xml"/>        </session-factory>  </hibernate-configuration>

jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver  jdbc.url=jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT  jdbc.username=root  jdbc.password=1234

struts2.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">    <struts>      <constant name="struts.action.extension" value="action"/>        <!--配置Action  方法一-->      <!--  <package name="ssh1" extends="struts-default" namespace="/">            <action name="customer_*" class="com.jinke.ssh.web.action.CustomerAction" method="{1}">                <allowed-methods>save</allowed-methods>            </action>        </package>-->        <!--配置action 方法二-->      <package name="ssh1" extends="struts-default" namespace="/">          <action name="customer_*" class="customerAction" method="{1}">              <allowed-methods>save,findById</allowed-methods>          </action>      </package>  </struts>

web.xml

<?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_4_0.xsd"           version="4.0">      <welcome-file-list>          <welcome-file>index.jsp</welcome-file>      </welcome-file-list>      <!--Spring核心監聽器-->      <listener>          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>      </listener>        <!--載入Spring配置文件的路徑,默認載入WEB-INF/applicationContext.xml-->      <context-param>          <param-name>contextConfigLocation</param-name>          <param-value>classpath:applicationContext.xml</param-value>      </context-param>        <!--用來解決延遲載入問題的過濾器-->      <filter>          <filter-name>OpenSessionInViewFilter</filter-name>          <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>      </filter>      <filter-mapping>          <filter-name>OpenSessionInViewFilter</filter-name>          <url-pattern>*.action</url-pattern>      </filter-mapping>        <!--Struts2核心過濾器-->      <filter>          <filter-name>struts2</filter-name>          <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>      </filter>      <filter-mapping>          <filter-name>struts2</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping>  </web-app>

下面是java文件

import com.jinke.ssh.dao.CustomerDao;  import com.jinke.ssh.domain.Customer;  import org.hibernate.criterion.DetachedCriteria;  import org.springframework.orm.hibernate5.support.HibernateDaoSupport;    import java.util.List;    /**   * DAO層的實現類   */  public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {      @Override      public void save(Customer customer) {          System.out.println("DAO中的save方法被執行了");          this.getHibernateTemplate().save(customer);      }        @Override      public void update(Customer customer) {          this.getHibernateTemplate().update(customer);      }        @Override      public void delete(Customer customer) {          this.getHibernateTemplate().delete(customer);      }        @Override      public Customer findById(int id) {          Customer customer = this.getHibernateTemplate().load(Customer.class, id);          return customer;      }        @Override      public List<Customer> findAllByHQL() {          List<Customer> list = (List<Customer>) this.getHibernateTemplate().find("from Customer");          return list;      }        @Override      public List<Customer> findAllByQBC() {          //自帶分頁          DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);          List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByCriteria(criteria);          return list;      }        @Override      public List<Customer> findAllByName() {          return (List<Customer>) this.getHibernateTemplate().findByNamedQuery("queryAll");      }  }
import com.jinke.ssh.domain.Customer;    import java.util.List;    /**   * DAO層的介面   */  public interface CustomerDao {      void save(Customer customer);        void update(Customer customer);        void delete(Customer customer);        Customer findById(int id);        List<Customer> findAllByHQL();        List<Customer> findAllByQBC();        List<Customer> findAllByName();  }  public class Customer {      private int id;      private String name;      private String source;      private String industry;      private String level;      private String phone;      private String mobile;        public int getId() {          return id;      }        public void setId(int id) {          this.id = id;      }        public String getName() {          return name;      }        public void setName(String name) {          this.name = name;      }        public String getSource() {          return source;      }        public void setSource(String source) {          this.source = source;      }        public String getIndustry() {          return industry;      }        public void setIndustry(String industry) {          this.industry = industry;      }        public String getLevel() {          return level;      }        public void setLevel(String level) {          this.level = level;      }        public String getPhone() {          return phone;      }        public void setPhone(String phone) {          this.phone = phone;      }        public String getMobile() {          return mobile;      }        public void setMobile(String mobile) {          this.mobile = mobile;      }        @Override      public String toString() {          return "Customer{" +                  "id=" + id +                  ", name='" + name + ''' +                  ", source='" + source + ''' +                  ", industry='" + industry + ''' +                  ", level='" + level + ''' +                  ", phone='" + phone + ''' +                  ", mobile='" + mobile + ''' +                  '}';      }  }
import com.jinke.ssh.dao.CustomerDao;  import com.jinke.ssh.domain.Customer;  import com.jinke.ssh.service.CustomerService;  import org.springframework.transaction.annotation.Transactional;    import java.util.List;    /**   * 業務層的實現類   */  @Transactional  public class CustomerServiceImpl implements CustomerService {        //注入DAO      private CustomerDao customerDao;        public void setCustomerDao(CustomerDao customerDao) {          this.customerDao = customerDao;      }        @Override      public void save(Customer customer) {          System.out.println("Service中的save方法執行了");          customerDao.save(customer);      }        @Override      public void update(Customer customer) {          System.out.println("Service中的update方法執行了");          customerDao.update(customer);      }        @Override      public void delete(Customer customer) {          System.out.println("Service中的delete方法執行了");          customerDao.delete(customer);      }        @Override      public Customer findById(int id) {          System.out.println("Service中的findById方法執行了");          return customerDao.findById(id);      }        @Override      public List<Customer> findAllByHQL() {          System.out.println("Service中的findAllByHQL方法執行了");          return customerDao.findAllByHQL();      }        @Override      public List<Customer> findAllByQBC() {          System.out.println("Service中的方法執行了");          return customerDao.findAllByQBC();      }        @Override      public List<Customer> findAllByName() {          return customerDao.findAllByName();      }  }
import com.jinke.ssh.domain.Customer;    import java.util.List;    /**   * 客戶管理的業務層的介面   */  public interface CustomerService {        void save(Customer customer);        void update(Customer customer);        void delete(Customer customer);        Customer findById(int id);        List<Customer> findAllByHQL();        List<Customer> findAllByQBC();        List<Customer> findAllByName();  }
import com.jinke.ssh.domain.Customer;  import com.jinke.ssh.service.CustomerService;  import org.junit.Test;  import org.junit.runner.RunWith;  import org.springframework.test.context.ContextConfiguration;  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;    import javax.annotation.Resource;  import java.util.List;    @RunWith(SpringJUnit4ClassRunner.class)  @ContextConfiguration("classpath:applicationContext.xml")  public class SSHdemo {        @Resource      private CustomerService customerService;        @Test      public void update() {          Customer customer = customerService.findById(3);          customer.setName("三石");          customerService.update(customer);      }        @Test      public void delete() {          Customer customer = customerService.findById(1);          customerService.delete(customer);      }        @Test      public void findAllByHQL() {          List<Customer> customerList = customerService.findAllByHQL();          for (Customer customer : customerList) {              System.out.println(customer);          }      }        @Test      public void findAllByQBC() {          List<Customer> customerList = customerService.findAllByQBC();          for (Customer customer : customerList) {              System.out.println(customer);          }      }        @Test      public void findAllByName() {          List<Customer> customerList = customerService.findAllByName();          for (Customer customer : customerList) {              System.out.println(customer);          }      }  }
import com.jinke.ssh.domain.Customer;  import com.jinke.ssh.service.CustomerService;  import com.opensymphony.xwork2.ActionSupport;  import com.opensymphony.xwork2.ModelDriven;    /**   * 客戶管理的Action的類   */  public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {      //模型驅動使用的對象      private Customer customer = new Customer();        @Override      public Customer getModel() {            return customer;      }        //注入customerService      private CustomerService customerService;        public void setCustomerService(CustomerService customerService) {          this.customerService = customerService;      }        /**       * 報錯客戶的方法       */      public String save() {          System.out.println("Action中的save方法執行了...");          customerService.save(customer);          return NONE;      }        public String findById() {          Customer customer = customerService.findById(2);          customer.setName("延遲");          return NONE;      }  }

demo地址:https://github.com/king1039/SSH