Structs2+spring+hibernate整合

1.目录

2.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_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <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>
    
    <!-- 配置 Struts2 的 Filter -->
    <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.hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 配置 hibernate 的基本属性 -->
    
        <!-- 方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        
        <!-- 运行时是否打印 SQL -->
        <property name="hibernate.show_sql">true</property>
        <!-- 运行时是否格式化 SQL -->
        <property name="hibernate.format_sql">true</property>
    
        <!-- 生成数据表的策略 -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <!-- 二级缓存相关 -->
        
<!--         <mapping class="com.atguigu.ssh.entities.Employee"></mapping>
        <mapping class="com.atguigu.ssh.entities.Department"></mapping> -->
    </session-factory>
    
</hibernate-configuration>

4.db.properties

jdbc.user=root
jdbc.password=1234
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring7

jdbc.initPoolSize=5
jdbc.maxPoolSize=10
#...

5.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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    
    <!-- spring注解配置 -->
<!--     <context:annotation-config/>-->
    <context:component-scan base-package="com.atguigu.ssh"></context:component-scan> 

    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置 C3P0 数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        
        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>
    
    <!-- 配置 SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <!-- 自动扫描实体 -->
        <property name="packagesToScan"  value="com.atguigu.ssh.entities"/>
    </bean>
    
    <!-- 配置 Spring 的声明式事务 -->
    <!-- 1. 配置 hibernate 的事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 2. 配置事务属性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="lastNameIsValid" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 3. 配置事务切入点, 再把事务属性和事务切入点关联起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.atguigu.ssh.service.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

</beans>

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

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">
    
        <!-- 定义新的拦截器栈, 配置 prepare 拦截器栈的 alwaysInvokePrepare 参数值为 false -->
        <interceptors>
            <interceptor-stack name="sshStack">
                <interceptor-ref name="paramsPrepareParamsStack">
                    <param name="prepare.alwaysInvokePrepare">false</param>
                </interceptor-ref>
            </interceptor-stack>
        </interceptors>
        
        <!-- 使用新的拦截器栈 -->
        <default-interceptor-ref name="sshStack"></default-interceptor-ref>
    
        <action name="emp-*" class="employeeAction"
            method="{1}">
            <result name="list">/WEB-INF/views/emp-list.jsp</result>
            <result type="stream" name="ajax-success">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
            </result>    
            <result name="input">/WEB-INF/views/emp-input.jsp</result>
            <result name="success" type="redirect">/emp-list</result>
        </action>
            
    </package>

</struts>

7.entity

参考hibernate注解 

8.dao

public class BaseDao {
    @Autowired
    private SessionFactory sessionFactory;
    
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    public Session getSession(){
        return this.sessionFactory.getCurrentSession();
    }    
}
@Repository
public class DepartmentDao extends BaseDao{

    public List<Department> getAll(){
        String hql = "FROM Department";
        return getSession().createQuery(hql).list();
    }
}

9.Service

@Service
public class DepartmentService {
    @Autowired
    private DepartmentDao departmentDao;
    
    public void setDepartmentDao(DepartmentDao departmentDao) {
        this.departmentDao = departmentDao;
    }
    
    public List<Department> getAll(){
        return departmentDao.getAll();
    }
    
}

10.Actions

@Controller
public class EmployeeAction extends ActionSupport implements RequestAware,
 ModelDriven<Employee>, Preparable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Autowired
    private EmployeeService employeeService;

    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }
    @Autowired
    private DepartmentService departmentService;
    
    public void setDepartmentService(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    public String list() {
        request.put("employees", employeeService.getAll());
        return "list";
    }

    private Integer id;

    public void setId(Integer id) {
        this.id = id;
    }

    private InputStream inputStream;

    public InputStream getInputStream() {
        return inputStream;
    }

    public String delete() {
        try {
            employeeService.delete(id);
            inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
            try {
                inputStream = new ByteArrayInputStream("0".getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        }
        return "ajax-success";
    }
    
    public String input(){
        request.put("departments", departmentService.getAll());
        return INPUT;
    }
    
    public void prepareInput(){
        if(id != null){
            model = employeeService.get(id);
        }
    }
    
    public String save(){
        if(id == null){
            model.setCreateTime(new Date());            
        }
        //System.out.println(model);
        employeeService.saveOrUpdate(model);
        return SUCCESS;
    }
    
    /**
     * 可以根据 id 来判断为 save 方法准备的 model 是 new 的还是从数据库获取的!
     */
    public void prepareSave(){
        if(id == null){
            model = new Employee();
        }else{
            model = employeeService.get(id);
        }
    }
    
    private String lastName;
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
    public String validateLastName() throws UnsupportedEncodingException{
        if(employeeService.lastNameIsValid(lastName)){
            inputStream = new ByteArrayInputStream("1".getBytes("UTF-8")); 
        }else{
            inputStream = new ByteArrayInputStream("0".getBytes("UTF-8")); 
        }
        
        return "ajax-success";
    }

    private Map<String, Object> request;

    @Override
    public void setRequest(Map<String, Object> arg0) {
        this.request = arg0;
    }

    @Override
    public void prepare() throws Exception {}

    private Employee model;
    
    @Override
    public Employee getModel() {
        return model;
    }

}

注:以上代码源自尚硅谷的ssh视频教程学习整理

后续会整理一份完整的学习视频

原文地址:https://www.cnblogs.com/SI0301/p/11361965.html