首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SSH整合

SSH整合

作者头像
用户3112896
发布2019-09-26 14:56:36
1.4K0
发布2019-09-26 14:56:36
举报
文章被收录于专栏:安卓圈安卓圈安卓圈

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 安卓圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档