SSH整合


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

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

    
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        
        
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
                <prop key="hibernate.show_sql">trueprop>
                <prop key="hibernate.format_sql">trueprop>
                <prop key="hibernate.hbm2ddl.auto">updateprop>
            props>
        property>

        
        <property name="mappingResources">
            <list>
                <value>com/jinke/ssh/domain/Customer.hbm.xmlvalue>
            list>
        property>
    bean>

    
    <bean id="customerAction" class="com.jinke.ssh.web.action.CustomerAction" scope="prototype">
        <property name="customerService" ref="customerService"/>

    bean>

    
    <bean id="customerService" class="com.jinke.ssh.service.impl.CustomerServiceImpl">
        <property name="customerDao" ref="customerDao"/>
    bean>

    
    <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.Driverproperty>
        <property name="hibernate.connection.url">
            jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
        property>
        <property name="hibernate.connection.username">rootproperty>
        <property name="hibernate.connection.password">1234property>
        
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialectproperty>

        
        
        <property name="hibernate.show_sql">trueproperty>
        
        <property name="hibernate.format_sql">trueproperty>
        
        <property name="hibernate.hbm2ddl.auto">updateproperty>

        
        <property name="connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProviderproperty>
        
        <property name="c3p0.min_size">5property>
        
        <property name="c3p0.max_size">20property>
        
        <property name="c3p0.timeout">120property>
        
        <property name="c3p0.idle_test_period">3000property>


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

    
    

    
    <package name="ssh1" extends="struts-default" namespace="/">
        <action name="customer_*" class="customerAction" method="{1}">
            <allowed-methods>save,findByIdallowed-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.jspwelcome-file>
    welcome-file-list>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>

    
    <filter>
        <filter-name>OpenSessionInViewFilterfilter-name>
        <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>OpenSessionInViewFilterfilter-name>
        <url-pattern>*.actionurl-pattern>
    filter-mapping>

    
    <filter>
        <filter-name>struts2filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>struts2filter-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 findAllByHQL() {
        List list = (List) this.getHibernateTemplate().find("from Customer");
        return list;
    }

    @Override
    public List findAllByQBC() {
        //自带分页
        DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
        List list = (List) this.getHibernateTemplate().findByCriteria(criteria);
        return list;
    }

    @Override
    public List findAllByName() {
        return (List) 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 findAllByHQL();

    List findAllByQBC();

    List 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 findAllByHQL() {
        System.out.println("Service中的findAllByHQL方法执行了");
        return customerDao.findAllByHQL();
    }

    @Override
    public List findAllByQBC() {
        System.out.println("Service中的方法执行了");
        return customerDao.findAllByQBC();
    }

    @Override
    public List 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 findAllByHQL();

    List findAllByQBC();

    List 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 customerList = customerService.findAllByHQL();
        for (Customer customer : customerList) {
            System.out.println(customer);
        }
    }

    @Test
    public void findAllByQBC() {
        List customerList = customerService.findAllByQBC();
        for (Customer customer : customerList) {
            System.out.println(customer);
        }
    }

    @Test
    public void findAllByName() {
        List 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 {
    //模型驱动使用的对象
    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

欢迎关注我的微信公众号:安卓圈

ssh