[有人@我]SSH框架整合教程

前言:

SSH:Struts2+Spring+Hibernate整合的web应用程序开源框架。

Struts2:封装MVC设计模式的框架,控制web应用的前后端交互流程。 Spring:IOC管理整合Struts2和Hibernate,AOP处理事务。 Hiernate:对JDBC进行封装,控制Java程序与数据库的交互。

它们之间的关系可以用下面这张图表示。

SSH框架优点: 1.Spring管理对象的实例化,把对象的创建和获取放到配置文件中,便于维护。 2.Hibernate避免了JDBC连接数据库的冗余繁杂。 3.各层分工明细,实现了各层之间的解耦,代码更加灵活。

接下来说如何整合,首先对SSH框架进行分析。

我们以对象为切入点分析,整个web应用程序,后台代码部分需要用到的对象大致如下。

Struts2:Controller。

Hibernate:SessionFactory。

业务层:Service,Dao。

调用关系如下图。

业务流程:

1.Struts2获取客户端请求,并映射到Controller。

2.Controller调用业务层代码,一直到DAO层。

3.DAO层与数据库交互的工作交给Hibernate。

4.最终返回模型数据到Controller层,再响应到客户端。

我们会发现上述业务流程并没有提到Spring,那么Spring框架的作用是什么?

Spring是设计层面的框架,负责管理和整合Struts2,Hibernate,或者说的直接一点就是创建Struts2和Hibernate需要用到的对象。

按照这个思路,SSH框架可以这么理解:由Spring创建对象,Struts2和Hibernate从IOC容器中获取需要的对象,进行调用,完成业务需求。

搞清楚这个关系后,我们来写代码完成SSH框架的整合。

我们采用基于注解的方式来开发,以查询Classes对象为例。

代码:

1.环境搭建

创建maven工程,配置SSH框架依赖jar包。

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>test21</groupId>
  <artifactId>test21</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>test21 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <!-- junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>
    <!--JSONObject-->
    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>${json-lib.version}</version>
        <classifier>jdk15</classifier>
    </dependency>
    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>${commons-beanutils.version}</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>${commons-logging.version}</version>
    </dependency>
    <dependency>
        <groupId>net.sf.ezmorph</groupId>
        <artifactId>ezmorph</artifactId>
        <version>${ezmorph.version}</version>
    </dependency>

    <!--Struts 依赖组件-->
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>2.5.14.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-convention-plugin</artifactId>
        <version>2.5.14.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-spring-plugin</artifactId>
        <version>2.5.14.1</version>
    </dependency>

    <dependency>
        <groupId>org.ow2.asm</groupId>
        <artifactId>asm</artifactId>
        <version>5.2</version>
    </dependency>
    <dependency>
        <groupId>org.ow2.asm</groupId>
        <artifactId>asm-commons</artifactId>
        <version>5.2</version>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>2.1_3</version>
    </dependency>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>ognl</groupId>
        <artifactId>ognl</artifactId>
        <version>3.1.15</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.6</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.9.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.9.1</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts-annotations</artifactId>
        <version>1.0.6</version>
    </dependency>
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.26-incubating</version>
    </dependency>
    <!--Spring dependencies-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.1.9.RELEASE</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.4</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.7</version>
    </dependency>
    <!--Hibernate Dependencies-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.10.3</version>
    </dependency>
    <dependency>
        <groupId>antlr</groupId>
        <artifactId>antlr</artifactId>
        <version>2.7.7</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml</groupId>
        <artifactId>classmate</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.common</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>4.0.5.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.18.1-GA</version>
    </dependency>
    <dependency>
        <groupId>org.jboss</groupId>
        <artifactId>jandex</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.apache.ant</groupId>
        <artifactId>ant</artifactId>
        <version>1.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.logging</groupId>
        <artifactId>jboss-logging</artifactId>
        <version>3.1.3.GA</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.logging</groupId>
        <artifactId>jboss-logging-annotations</artifactId>
        <version>1.2.0.Beta1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.spec.javax.transaction</groupId>
        <artifactId>jboss-transaction-api_1.2_spec</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.2</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.spec.javax.transaction</groupId>
        <artifactId>jboss-transaction-api_1.2_spec</artifactId>
        <version>1.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>aopalliance</groupId>
        <artifactId>aopalliance</artifactId>
        <version>1.0</version>
    </dependency>
    <!--MySQL Driver-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.25</version>
    </dependency>
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>test21</finalName>
  </build>
    <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
       <junit.version>4.12</junit.version>
       <!--JSONObject-->
       <json-lib.version>2.4</json-lib.version>
       <commons-lang.version>2.5</commons-lang.version>
       <commons-collections.version>3.2.1</commons-collections.version>
       <commons-beanutils.version>1.8.0</commons-beanutils.version>
       <commons-logging.version>1.2</commons-logging.version>
       <ezmorph.version>1.0.6</ezmorph.version>
    </properties>
</project>

2.Hibernate需要的相关代码。

1.创建Classes实体类。

public class Classes {
    private int id;
    private String name;
    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;
    }
    @Override
    public String toString() {
        return "Classes [id=" + id + ", name=" + name + "]";
    }
    public Classes(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public Classes() {
        super();
    }

}

2.创建Classes.hbm.xml。

<?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="com.southwind.entity.Classes" table="classes">
        <id name="id" type="int">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>
    </class>
</hibernate-mapping>

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>

    </session-factory>

</hibernate-configuration>

hibernate.cfg.xml不配置dataSource对象,交给Spring容器来创建。

现在来配置spring.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/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
        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-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school?useUnicode=true&amp;characterEncoding=UTF-8"></property>
        <property name="initialPoolSize" value="5"></property>
        <property name="maxPoolSize" value="10"></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="mappingLocations" value="classpath:com/southwind/entity/*.hbm.xml"></property>
    </bean>

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.southwind"></context:component-scan>

</beans>

首先配置两个bean,分别是dataSource和sessionFactory,sessionFactory是Hibernate框架需要用到的对象,dataSource是创建sessionFactory所必需的对象。

同时自动将com.southwind包下的类扫描到IOC容器中。

    <!-- 配置 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="mappingLocations" value="classpath:com/southwind/entity/*.hbm.xml"></property>
    </bean>

将创建好的dataSource对象注入到sessionFactory对象中,同时将hibernate.cfg.xml和hbm.xml配置文件注入到sessionFactory bean中,这样Spring的IOC就会根据此配置生成对应的sessionFactory对象供Hibernate框架调用。

Hibernate与Spring的整合完毕,现在来整合Struts2和Spring。

1.创建Sturts2的ClassesController类。

@Controller
public class ClassesController {

    @Autowired
    private ClassesService classesService;

    private int id;
    private Classes classes;

    public Classes getClasses() {
        return classes;
    }

    public void setClasses(Classes classes) {
        this.classes = classes;
    }

    public int getId() {
        return id;
    }

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

    public Classes getById(int id){
        return classesService.getById(id);
    }

    public String queryClasses(){
        classes = classesService.getById(id);
        return "index";
    }
}

类名处添加@Controller注解,该类就会交给IOC容器来管理,创建对象,同时Controller类中需要调用Service对象,所以创建成员变量,使用@Autowired进行自动装载。

2.创建ClassesService接口以及ClassesServiceImpl实现类。

public interface ClassesService {
    public Classes getById(int id);
}
@Service
public class ClassesServiceImpl implements ClassesService{

    @Autowired
    private ClassesDAO classesDAO;

    @Override
    public Classes getById(int id) {
        // TODO Auto-generated method stub
        return classesDAO.getById(id);
    }

}

ClasseServiceImpl类名处添加@Service注解,该类也交给IOC容器管理创建对象。Service层中调用DAO,所以创建ClassesDAO成员变量,同样@Autowired自动装载。

3.创建ClassesDAO接口和ClassesDAOImpl实现类。

public interface ClassesDAO {
    public Classes getById(int id);
}
@Repository
public class ClassesDAOImpl implements ClassesDAO{

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public Classes getById(int id) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.openSession();
        String hql = "from Classes where id = ?";
        Query query = session.createQuery(hql);
        query.setInteger(0, id);
        Classes classes = (Classes) query.uniqueResult();
        session.close();
        return classes;
    }

}

ClassesDAOImpl中需要调用sessionFactory对象,所以创建成员变量,并使用@Autowired自动装载,这样会自动将IOC容器中创建的sessionFactory对象赋值给该成员变量。

好了,Controller层,Service层,DAO层,数据库的对接已经完成,接下来就是将Controller层与客户端进行对象。

配置struts.xml。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="struts2" extends="struts-default">

        <action name="queryClasses" class="classesController" method="queryClasses">
            <result name="index">/index.jsp</result>
        </action>

    </package>
</struts>

action标签配置URL请求与Controller的映射,

name属性配置URL请求,class属性配置Controller对象,此时Controller已经交给Spring的IOC容器来创建,所有直接将IOC容器中的classesController对象与URL映射即可。

index.jsp中使用EL表达式展示模型数据信息。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
      班级编号: ${classes.id }<br/>
      班级名称: ${classes.name }
  </body>
</html>

SSH框架搭建完成,启动tomcat,打开浏览器输入URL请求进行测试。

成功。

代码写到这里,我们只是使用了Spring的IOC,AOP并没有使用到,AOP到底应用在哪里?项目中的事务管理会交给Spring的AOP来完成。

在spring.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/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
        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-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school?useUnicode=true&amp;characterEncoding=UTF-8"></property>
        <property name="initialPoolSize" value="5"></property>
        <property name="maxPoolSize" value="10"></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="mappingLocations" value="classpath:com/southwind/entity/*.hbm.xml"></property>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 配置通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置AOP切面 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.southwind.dao.impl.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.southwind"></context:component-scan>
</beans>

配置文件中,横切关注点是com.southwind.dao.impl包中所有类的所有方法,即在调用这些方法时,Spring的AOP会自动在这些位置添加事务管理,如果执行成功,提交事务,如果抛出异常,回滚事务。

SSH框架整合完成。

原文发布于微信公众号 - Java大联盟(javaunion)

原文发表时间:2018-02-01

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券