java程序员程序员首页投稿

SSH框架之旅-spring(4)

2017-10-22  本文已影响113人  Wizey
spring.jpg

下面对 SSH 框架做一个整合,所用的三大框架的版本号 Struts2.3.x,Spring4.x,hibernate5.x。

1.回顾 SSH 框架知识点


1.1 Hibernate 框架

在 Spring 框架对 Hibernate 框架进行封装时,使用 HibernateTemplate 类。

1.2 Struts2 框架

1.3 Spring 框架

2.SSH框架整合


2.1 SSH 框架整合的思想

Java EE的三层架构.png

Struts2 负责和界面数据交互,路径跳转,拦截请求,调用 Service 层中的方法。Spring 负责另外两个框架中的对象创建,实现业务逻辑,调用 Dao 层中的数据操作的方法。Hibernate 负责和数据库交互,增删改查等等。

2.2 SSH 框架整合准备

创建一个文件夹,将之前三大框架的用到的 jar 包放进去,另外还要加入三个 jar 包。一个是整合整个 java web 项目的 spring-web.jar,一个是整合struts2的 struts2-spring-plugin.jar,一个是整合持久层框架的 spring-orm.jar

2.3 Spring 整合开发

下面通过添加学生的例子来说明。

实体类

package cc.wenshixin.entity;

public class Student {
    private int id;
    private String name;
    private String sex;
    //get和set方法

实体类的映射配置文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cc.wenshixin.entity.Student" table="student">
        <id name="id" type="int">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="sex" />
        </property>
    </class>
</hibernate-mapping>

Hibernate 的核心配置文件

Hibernate 的数据库配置部分放到 c3p0 连接池的配置中。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
      <!-- 配置hibernate -->
      <property name="hibernate.show_sql">true</property>
      <property name="hibernate.format_sql">true</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
      
      <!-- 引入映射文件 -->
      <mapping resource="cc/wenshixin/entity/Student.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

配置文件

首先是整个 web 项目的 web.xml 文件的配置,除了在 struts2 的拦截器,还要配置 spring 核心配置文件的位置,classpath 写spring核心配置文件的位置,一般都是直接放在 src 下,另外配置监听器,来在服务器启动时,就创建 Hibernate 的相关对象,解决第一次做数据库操作比较慢的问题。

<?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>ssh01</display-name>
  <!-- spring的配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:bean.xml</param-value>
  </context-param>
  
  <!-- struts2拦截器的配置 -->
  <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>
  
  <!-- 监听器的配置 -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

struts2 核心配置文件

<?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="demo" extends="struts-default" namespace="/">
    <action name="studentAction" class="studentAction"></action>
  </package>
</struts>

spring 的核心配置文件

Spring 框架中操作 JDBC 的是 JdbcTemplate,但对于其他持久层也封装了相应的类,操作 Hibernate 是 HibernateTemplate 类,但也需要注入 sessionFactory 属性,根据 c3p0 连接池来配置 sessionFactory 对象,另外还需要配置事务管理。

<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
  <!-- 配置数据库信息 -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!-- 注入属性值 -->
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useSSL=false"></property>
    <property name="user" value=""></property>
    <property name="password" value=""></property>
  </bean>
  
  <!-- 配置sessionFactory创建 -->
  <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <!-- 制定数据库的信息 -->
    <property name="dataSource" ref="dataSource"></property>
    <!-- 指定使用的hibernate核心配置文件的位置 -->
    <property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
  </bean>
  
  <!-- 配置事务管理器 -->
  <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <!-- 注入sessionFacory对象 -->
    <property name="sessionFactory" ref="sessionFactory"></property>
  </bean>
  
  <!-- 开启事务注解 -->
  <tx:annotation-driven transaction-manager="transactionManager"/>
  
  <!-- 配置hibernateTemplate对象 -->
  <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory"></property>  
  </bean>
  
  <!-- 配置三层结构对象 -->
  <bean id="studentAction" class="cc.wenshixin.action.StudentAction"></bean>
  <bean id="studentService" class="cc.wenshixin.service.StudentService"></bean>
  <bean id="studentDao" class="cc.wenshixin.dao.StudentDao"></bean>
  
  <!-- 开启注解扫描 -->
  <context:component-scan base-package="cc.wenshixin"></context:component-scan>
</beans>

Dao 类

package cc.wenshixin.dao;

import javax.annotation.Resource;

import org.springframework.orm.hibernate5.HibernateTemplate;

import cc.wenshixin.entity.Student;

public class StudentDao{
    @Resource(name="hibernateTemplate")
    private HibernateTemplate hibernateTemplate;
    
    public void add() {
        Student student = new Student();
        student.setName("james");
        student.setSex("男");
        hibernateTemplate.save(student);
    }
}

Service 类

package cc.wenshixin.service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;

import cc.wenshixin.dao.StudentDao;

@Transactional
public class StudentService {
    @Resource(name="studentDao")
    private StudentDao studentDao;
    
    public void add()
    {
        System.out.println("service...");
        studentDao.add();
    }
}

Action 类

package cc.wenshixin.action;

import javax.annotation.Resource;

import com.opensymphony.xwork2.ActionSupport;

import cc.wenshixin.service.StudentService;

public class StudentAction extends ActionSupport{
    @Resource(name="studentService")
    private StudentService studentService;
    
    @Override
    public String execute() throws Exception {
        System.out.println("action...");
        studentService.add();
        return NONE;
    }
}

访问 http://localhost:8080/ssh01/studentAction.action

2.3 SSH 分模块开发

在开发中,通常要进行分模块开放,也就是把核心配置文件中的内容拆开,在核心配置文件中包含其他的配置文件,减少对核心配置文件的改动,将一个项目分成小的模块,多人一起开发。

下面通过一个表单提交学生信息的例子来说明。

实体类

package cc.wenshixin.entity;

public class Student {
    private String id; //学号
    private String name; //姓名
    private String banji; //班级
    //get和set方法

实体类的映射文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cc.wenshixin.entity.Student" table="student">
        <id name="id" type="java.lang.String">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>
        <property name="banji" type="java.lang.String">
            <column name="banji" />
        </property>
    </class>
</hibernate-mapping>

整个 web 项目的配置文件

<?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>ssh02</display-name>
  
  <!-- Spring核心配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>
  
  <!-- 过滤器 -->
  <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>
  
  <!-- 监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Dao 类

创建一个 Dao 类的接口,其他 Dao 类实现这个类中的方法。

package cc.wenshixin.dao;

public interface AbstractDao {
    public void add(Object object);
}
package cc.wenshixin.dao;

import javax.annotation.Resource;

import org.springframework.orm.hibernate5.HibernateTemplate;

import cc.wenshixin.entity.Student;

public class StudentDao implements AbstractDao{
    @Resource(name="hibernateTemplate")
    private HibernateTemplate hibernateTemplate;

    @Override
    public void add(Object object) {
        System.out.println("dao。。。");
        hibernateTemplate.save((Student)object);
    }
}

Service 类

package cc.wenshixin.service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;

import cc.wenshixin.dao.StudentDao;
import cc.wenshixin.entity.Student;

@Transactional
public class StudentService {
    @Resource(name="studentDao")
    private StudentDao studentDao;
    
    public void add(Student student)
    {
        System.out.println("service。。。");
        studentDao.add(student);
    }
}

Action 类

package cc.wenshixin.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import cc.wenshixin.entity.Student;
import cc.wenshixin.service.StudentService;

public class StudentAction extends ActionSupport {
    @Resource(name="studentService")
    private StudentService studentService;
    private HttpServletRequest request = ServletActionContext.getRequest();
    
    public String add() throws Exception 
    {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String banji = request.getParameter("banji");
        Student student = new Student();
        student.setId(id);
        student.setName(name);
        student.setBanji(banji);
        System.out.println("action。。。");
        studentService.add(student);
        return NONE;
    }
}

单独创建一个包来存放非核心的配置文件,spring 和 struts2 的核心配置文件仍旧放在 src 目录下,另外在 spring 中配置 hibernate 的选项和引入映射文件,可以不再单独写 Hibernate的配置文件。

student-spring.xml

放 student 相关的 Action 类,Service 类,DAO 类。

<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
  <!-- 配置对象 -->
  <bean id="studentAction" class="cc.wenshixin.action.StudentAction" scope="prototype"></bean>
  <bean id="studentService" class="cc.wenshixin.service.StudentService"></bean>
  <bean id="studentDao" class="cc.wenshixin.dao.StudentDao"></bean>
</beans>

student-struts.xml

放 Action 类中的方法的配置

<?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="student" extends="struts-default" namespace="/">
    <action name="addStudent" class="studentAction" method="add"></action>
  </package>
</struts>

Spring 核心配置文件

<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
        
  <!-- 配置数据库信息 -->      
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!-- 注入属性值 -->
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useSSL=false"></property>
    <property name="user" value=""></property>
    <property name="password" value=""></property>
  </bean>
  
  <!-- 配置sessionFactory创建 -->
  <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <!-- 指定数据库的信息 -->
    <property name="dataSource" ref="dataSource"></property>  
    <!-- 配置hibernate选项 -->
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.format_sql">true</prop>
        <prop key="hibernate.hbm2ddl.auto">update</prop>
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
      </props>
    </property>
    <!-- 引入映射文件 -->
    <property name="mappingResources">
      <list>
        <value>cc/wenshixin/entity/Student.hbm.xml</value>
      </list>
    </property>
  </bean>
  
  <!-- 配置事务管理器 -->
  <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <!-- 注入sessionFactory对象 -->
    <property name="sessionFactory" ref="sessionFactory"></property>
  </bean>
  
  <!-- 开启事务注解 -->
  <tx:annotation-driven transaction-manager="transactionManager"/>
  
  <!-- 配置对象 -->
  <bean id="studentAction" class="cc.wenshixin.action.StudentAction"></bean>
  <bean id="studentService" class="cc.wenshixin.service.StudentService"></bean>
  <bean id="studentDao" class="cc.wenshixin.dao.StudentDao"></bean>
  
  <!-- 开启属性注入注解 -->
  <context:component-scan base-package="cc.wenshixin"></context:component-scan>
    
  <!-- 配置hibernateTemplate对象 -->
  <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory"></property>  
  </bean>

  <!-- 引入对象配置文件 -->
  <import resource="classpath:cc/wenshixin/config/student-spring.xml"/>
</beans>

Struts 核心配置文件

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

  <include file="cc/wenshixin/config/student-struts.xml"></include>
</struts>

整个项目的结构

项目目录结构.png

log4j的配置文件不是必须的,但建议使用,便于查找错误。

SSH 框架之旅到这里才刚刚开始。

上一篇 下一篇

猜你喜欢

热点阅读