前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SSH框架之旅-spring(4)

SSH框架之旅-spring(4)

作者头像
Wizey
发布2018-08-30 09:42:02
6180
发布2018-08-30 09:42:02
举报
文章被收录于专栏:编程心路编程心路

spring.jpg

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

1.回顾 SSH 框架知识点


1.1 Hibernate 框架

  • Hibernate 的核心配置文件:数据库信息,Hibernate信息,映射配置。如果单纯使用 Hibernate 框架,核心配置文件的名称(hibernate.cfg.xml)和位置(src 下面)都是固定的。但是在和 Spring 整合的时候,Hibernate 的核心配置文件名称和位置是没有固定要求的。
  • Hibernate 的映射配置文件:orm思想,对象关系映射。实体类和数据表映射关系——使用orm思想。

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

1.2 Struts2 框架

  • Action 操作:Action 创建的三种方式,一般使用继承 ActionSupport 类来创建 Action类。配置 创建 struts.xml 配置文件来配置 Action 的访问路径,配置文件的名称和位置(src下面)都是固定的。配置Action 类中的多个方法使用通配符的方式。在使用 Action 类获取表单提交的数据时,一般使用 ServletActionContext 类来获取,还有属性封装,模型驱动,表达式封装。在 Action 中操作域对象时使用 ServletActionContext 来获取。另外还有Struts2 的过滤器配置
  • 值栈:向值栈中放数据,set 方法和 push 方法,定义变量,生成 get 方法。从值栈中获取数据,在jsp中使用 Struts2 标签加上 OGNL 表达式来获取。标签 <s:propertity><s:iterator>
  • 拦截器:AOP 思想和责任链模式,自定义拦截器继承 MethodFilterInterceptor 类,重写父类里面的方法,配置拦截器和 Action 关联。

1.3 Spring 框架

  • Spring 核心配置文件:名称和位置没有固定的要求,在 Spring 核心配置文件中引入 scheme 约束。
  • 创建对象:xml 配置方式,<bean id="" class="" scope=""/>;注解方式,四个注解,@Component,@Repostiry,@Service,@Controller。
  • 属性注入:xml 配置方式,<property name="" ref="">;注解方式,两个注解,@AutoWired,@Resource。
  • 使用 ServletContext 对象和监听器,实现在服务器启动时就加载 Spring 的配置文件创建对象,配置 Spring 的监听器,指定 Spring 配置文件的位置。
  • JdbcTemplate
  • Spring 的事务管理:xml 方式和注解方式。

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 整合开发

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

实体类

代码语言:javascript
复制
package cc.wenshixin.entity;

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

实体类的映射配置文件

代码语言:javascript
复制
<?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 连接池的配置中。

代码语言:javascript
复制
<?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 的相关对象,解决第一次做数据库操作比较慢的问题。

代码语言:javascript
复制
<?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 核心配置文件

代码语言:javascript
复制
<?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 对象,另外还需要配置事务管理。

代码语言:javascript
复制
<?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 类

代码语言:javascript
复制
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 类

代码语言:javascript
复制
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 类

代码语言:javascript
复制
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 分模块开发

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

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

实体类

代码语言:javascript
复制
package cc.wenshixin.entity;

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

实体类的映射文件

代码语言:javascript
复制
<?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 项目的配置文件

代码语言:javascript
复制
<?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 类实现这个类中的方法。

代码语言:javascript
复制
package cc.wenshixin.dao;

public interface AbstractDao {
    public void add(Object object);
}
代码语言:javascript
复制
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 类

代码语言:javascript
复制
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 类

代码语言:javascript
复制
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 类。

代码语言:javascript
复制
<?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 类中的方法的配置

代码语言:javascript
复制
<?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 核心配置文件

代码语言:javascript
复制
<?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 核心配置文件

代码语言:javascript
复制
<?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 框架之旅到这里才刚刚开始。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.10.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.回顾 SSH 框架知识点
    • 1.1 Hibernate 框架
      • 1.2 Struts2 框架
        • 1.3 Spring 框架
        • 2.SSH框架整合
          • 2.1 SSH 框架整合的思想
            • 2.2 SSH 框架整合准备
              • 2.3 Spring 整合开发
                • 2.3 SSH 分模块开发
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档