Struts2+Spring4+Hibernate的整合(SSH整合)

xiaoxiao2021-02-28  19

1.  Spring与Hibernte的整合

1.1.  开发环境

Ø  sts(spring针对ecluspe的升级版本)、maven3、tomcat8

Ø  框架版本

Spring4.2.5+Struts2.3.24+Hibernate4.3.11+Druid 1.0.18

1.2.  Jar包的整理

1.2.1. Hibernate所需jar

Ø  截图

Ø  Maven依赖

    <!-- hibernate  start -->

    <dependency>

           <groupId>org.hibernate</groupId>

           <artifactId>hibernate-core</artifactId>

           <version>4.3.11.Final</version>

       </dependency>

       <dependency>

           <groupId>commons-collections</groupId>

           <artifactId>commons-collections</artifactId>

           <version>3.2.1</version>

       </dependency>

       <dependency>

           <groupId>javax.transaction</groupId>

           <artifactId>jta</artifactId>

           <version>1.1</version>

       </dependency>

       <!-- hibernate  end -->

1.2.2. 数据源所需jar

<dependency>

    <groupId>com.alibaba</groupId>

    <artifactId>druid</artifactId>

    <version>1.0.18</version>

</dependency>

1.2.3. 数据库驱动包

由于oracle的jdbc驱动包在maven上无法下载,我们使用jar的导入方式,如果想使用maven那么我们需要使用maven的命令将oracle的jdbc驱动加载到本地仓库

1.2.4. Spring所需jar

Ø  截图

Ø  Maven依赖

<!-- Spring start -->

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-orm</artifactId>

           <version>4.2.5.RELEASE</version>

       </dependency>

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-web</artifactId>

           <version>4.2.5.RELEASE</version>

       </dependency>

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-context</artifactId>

           <version>4.2.5.RELEASE</version>

       </dependency>

       <dependency>

           <groupId>org.aspectj</groupId>

           <artifactId>aspectjweaver</artifactId>

           <version>1.8.8</version>

       </dependency>

       <!-- Spring end -->

1.2.5. 日志相关jar

Ø  截图

Ø  Maven依赖

<dependency>

           <groupId>org.slf4j</groupId>

           <artifactId>slf4j-log4j12</artifactId>

           <version>1.7.21</version>

       </dependency>

1.3.  创建包、接口、类

1.3.1. 包结构如下

1.3.2. 实体层

Student

package com.wskj.entity;

 

import java.io.Serializable;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.SequenceGenerator;

import javax.persistence.Table;

/**

 *

 * @Description:students表实体类

 * @author lzl

 * @Date 201872日下午3:21:24

 */

@Entity

@Table(name="students")

publicclass Student implements Serializable {

 

    @Id

    @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="stu1_seq")

    @SequenceGenerator(allocationSize=1,name="stu1_seq",sequenceName="stu1_seq")

    private Integer stuid;

    @Column(name="stuname")

    private String stuname;

    @Column(name="age")

    private Integer age;

    public Integer getStuid() {

        returnstuid;

    }

    public Student(Integer stuid, String stuname, Integer age) {

        super();

        this.stuid = stuid;

        this.stuname = stuname;

        this.age = age;

    }

    publicvoid setStuid(Integer stuid) {

        this.stuid = stuid;

    }

    public String getStuname() {

        returnstuname;

    }

    publicvoid setStuname(String stuname) {

        this.stuname = stuname;

    }

    public Integer getAge() {

        returnage;

    }

    publicvoid setAge(Integer age) {

        this.age = age;

    }

    public Student() {

        super();

    }

    @Override

    public String toString() {

        return"Student [stuid=" + stuid + ", stuname=" + stuname + ", age="

                + age + "]";

    }

}

 

1.3.3. 数据访问层

1.3.3.1. BaseDao

package com.wskj.dao.impl;

 

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.orm.hibernate4.HibernateTemplate;

 

/**

 *

 * @Description:数据访问公共类

 * @author lzl

 * @Date 201872日下午3:28:13

 */

publicclass BaseDao {

 

    @Autowired

    private SessionFactory sessionFactory;

    @Autowired

    private HibernateTemplate hibernateTemplate;

   

    //提供一个共有的获取SessionFactory的方法

    public SessionFactory getSessionFactory(){

        returnsessionFactory;

    }

   

    //提供一个获取currentSession的方法

    public Session getCurrentSession(){

        returnsessionFactory.getCurrentSession();

    }

   

    //提供一个获取模板的方法

    public HibernateTemplate getHibernateTemplate(){

        returnhibernateTemplate;

    }

}

1.3.3.2. IStudentDao

package com.wskj.dao;

 

import java.util.List;

 

import com.wskj.entity.Student;

 

publicinterface IStudentDao {

    Boolean addStudent(Student stu);

    List<Student> findAll();

}

 

1.3.3.3. StudentDao

package com.wskj.dao.impl;

 

import java.util.List;

 

import org.springframework.stereotype.Repository;

 

import com.wskj.dao.IStudentDao;

import com.wskj.entity.Student;

/**

 *

 * @Description:学生数据访问实现类

 * @author lzl

 * @Date 201872日下午3:35:49

 */

@Repository

publicclass StudentDao extends BaseDao implements IStudentDao {

 

    @Override

    public Boolean addStudent(Student stu) {

        Integer row = (Integer) getCurrentSession().save(stu);

//      Serializable save = getHibernateTemplate().save(stu);

        returnrow>0?true:false;

    }

 

    @Override

    public List<Student> findAll() {

        //使用离线QBC查询所有

        DetachedCriteria dc=DetachedCriteria.forClass(Student.class);

        List<Student> list = (List<Student>) getHibernateTemplate().findByCriteria(dc);

        returnlist;

    }}

1.3.4. 业务逻辑层

1.3.4.1. IStudentBiz

package com.wskj.biz;

import java.util.List;

import com.wskj.entity.Student;

 

publicinterface IStudentBiz {

    String addStudent(Student stu);

    List<Student> findAll();

}

1.3.4.2. StudentBIz

package com.wskj.biz.impl;

 

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.wskj.biz.IStudentBiz;

import com.wskj.dao.IStudentDao;

import com.wskj.entity.Student;

@Service

publicclass StudentBiz implements IStudentBiz{

 

    @Autowired

    private IStudentDao studentDao;

    @Override

    public String addStudent(Student stu) {

        Boolean flag = studentDao.addStudent(stu);

        returnflag?"添加成功":"添加失败";

    }

    @Override

    public List<Student> findAll() {

        returnstudentDao.findAll();

    }

}

1.3.5. Web层(见下面Struts2时的资料)

1.4.  配置文件配置

1.4.1. 数据源文件(druid.properties)

#数据库驱动如果不配置,系统会根据url自动识别

#driverClassName=com.mysql.jdbc.Driver

#URL

druid.url=jdbc:oracle:thin:@localhost:1521:orcl

#用户名

druid.username=t150

#密码

druid.password=t150

filters=stat

druid.initialSize=5

#最大连接池数量

druid.maxActive=300

#获取连接时最大等待时间,单位毫秒

druid.maxWait=60000

#Destroy线程会检测连接的间隔时间

druid.timeBetweenEvictionRunsMillis=60000

minEvictableIdleTimeMillis=300000

#用来检测连接是否有效的sql,要求是一个查询语句

validationQuery=SELECT1

#建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,

#如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。

testWhileIdle=true

#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。

testOnBorrow=false

#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能

testOnReturn=false

#是否缓存preparedStatement,也就是PSCachePSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。

poolPreparedStatements=false

maxPoolPreparedStatementPerConnectionSize=200

 

1.4.2. 日志配置文件(log4j.properties)

# Global logging configuration

log4j.rootLogger=DEBUG,stdout

# Console output...

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p[%t]-%m%n

1.4.3. Spring的事务配置文件:applicationContext-tx.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:context="http://www.springframework.org/schema/context"

        xmlns:aop="http://www.springframework.org/schema/aop"

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

        http://www.springframework.org/schema/context/spring-context.xsd

        http://www.springframework.org/schema/aop

        http://www.springframework.org/schema/aop/spring-aop.xsd

        http://www.springframework.org/schema/tx

        http://www.springframework.org/schema/tx/spring-tx.xsd">

  <!--   事务管理器 -->

  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

          <!-- 管理数据源 -->

       <property name="dataSource" ref="dataSource"></property>

  </bean>

  <!-- 通知 -->

  <tx:advice id="txAdvice" transaction-manager="transactionManager">

       <!-- 事务的传播行为 -->

       <tx:attributes>

          <!-- 必须开启事务 -->

          <tx:method name="add*" propagation="REQUIRED"/>

          <tx:method name="save*" propagation="REQUIRED"/>

          <tx:method name="update*" propagation="REQUIRED"/>

          <tx:method name="modify*" propagation="REQUIRED"/>

          <tx:method name="delete*" propagation="REQUIRED"/>

          <tx:method name="remove*" propagation="REQUIRED"/>

          <!-- 只读事务 -->

          <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>

          <tx:method name="query*" propagation="SUPPORTS" read-only="true"/>

          <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>

          <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>

       </tx:attributes>

  </tx:advice>

<!--   配置切面 -->

<aop:config>

   <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.wskj.biz..*.*(..))"/>

</aop:config>

</beans>

1.4.4. Spring全局配置文件: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:context="http://www.springframework.org/schema/context"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:jee="http://www.springframework.org/schema/jee"

    xsi:schemaLocation="

       http://www.springframework.org/schema/beans

       http://www.springframework.org/schema/beans/spring-beans.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

       http://www.springframework.org/schema/aop

       http://www.springframework.org/schema/aop/spring-aop.xsd

       http://www.springframework.org/schema/jee

       http://www.springframework.org/schema/jee/spring-jee.xsd">

       <!-- 引入外部资源文件 -->

       <context:property-placeholder location="classpath:druid.properties"/>

       <!-- 引入事务配置文件 -->

       <import resource="classpath:applicationContext-tx.xml"/>

       <!-- 开启注解扫描 -->

       <context:component-scan base-package="com.wskj"></context:component-scan>

      

       <!-- 配置数据源 -->

       <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

              <!-- 数据库连接地址 -->

              <property name="url" value="${druid.url}"></property>

              <!-- 用户名 -->

              <property name="username" value="${druid.username}"></property>

              <!-- 密码 -->

              <property name="password" value="${druid.password}"></property>

              <!-- 最大连接池数量 -->

              <property name="maxActive" value="${druid.maxActive}"></property>

              <!-- 初始化连接数 -->

              <property name="initialSize" value="${druid.initialSize}"></property>

              <!-- 获取连接时最大等待时间,单位毫秒 -->

              <property name="maxWait" value="${druid.maxWait}"></property>

              <!-- Destroy线程会检测连接的间隔时间 -->

              <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}"></property>

       </bean>

       <!-- Session工厂配置 -->

       <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

           <property name="dataSource" ref="dataSource"></property>

              <!-- 通过configLocations可以加载并读取hibernate的全局配置文件 -->

              <!-- <property name="configLocations" value="classpath:hibernate.cfg.xml"></property> -->

           <!-- hibernate相关配置 -->

           <property name="hibernateProperties">

              <props>

                  <!-- 数据库方言 -->

                  <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>

                  <!-- 是否显示sql -->

                  <prop key="hibernate.show_sql">true</prop>

                  <!--是否让sql格式化  -->

                  <prop key="hibernate.format_sql">true</prop>

                  <!-- 是否通过实体类自动生成数据库表 -->

                  <prop key="hibernate.hbm2ddl.auto">update</prop>

                  <!-- 因为是oracle数据库我们要设置默认的用户  否则自动生成数据库表时可能会有问题-->

                  <prop key="default_schema">t150</prop>

              </props>

           </property>

           <!-- 如果使用配置映射文件的方式 -->

           <!-- <property name="mappingResources">

              <list>

                  <value>xxxx.hbm.xml</value>

              </list>

           </property> -->

           <!-- 扫描实体类注解所在包 -->

           <property name="packagesToScan" value="com.wskj.entity"></property>

       </bean>

       <!-- Spring 整合Hibernate提供的实用的模板类 -->

       <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">

              <property name="sessionFactory" ref="sessionFactory"></property>

       </bean>

</beans>

2.  SSH的整合

2.1.  Struts2所需jar

Ø  截图

Ø  Maven依赖

<!-- sturts2 start -->

       <dependency>

           <groupId>org.apache.struts</groupId>

           <artifactId>struts2-spring-plugin</artifactId>

           <version>2.3.24</version>

           <exclusions>

              <exclusion>

                  <groupId>org.springframework </groupId>

                  <artifactId>spring-beans</artifactId>

              </exclusion>

              <exclusion>

                  <groupId>org.springframework </groupId>

                  <artifactId>spring-core</artifactId>

              </exclusion>

              <exclusion>

                  <groupId>org.springframework </groupId>

                  <artifactId>spring-context</artifactId>

              </exclusion>

              <exclusion>

                  <groupId>org.springframework </groupId>

                  <artifactId>spring-web</artifactId>

              </exclusion>

              <exclusion>

                  <groupId>commons-io</groupId>

                  <artifactId>commons-io</artifactId>

              </exclusion>

           </exclusions>

       </dependency>

       <dependency>

           <groupId>commons-io</groupId>

           <artifactId>commons-io</artifactId>

           <version>2.2</version>

       </dependency>

       <!-- sturts2 end -->

2.2.  Web层

2.2.1.1. StudentAction

package com.wskj.web;

 

import java.io.IOException;

import java.util.List;

 

import javax.servlet.http.HttpServletResponse;

 

import org.apache.struts2.ServletActionContext;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Scope;

import org.springframework.stereotype.Controller;

 

import com.opensymphony.xwork2.ActionSupport;

import com.wskj.biz.IStudentBiz;

import com.wskj.entity.Student;

@Controller

@Scope("prototype")//因为action不能是单例的,所有需要加上此选项

publicclass StudentAction extends ActionSupport {

    privatestaticfinallongserialVersionUID = 1L;

 

    @Autowired

    private IStudentBiz studentBiz;

   

    private Student student;

    publicvoid setStudent(Student student) {

        this.student = student;

    }

 

    /*

     *

     * 跳转到登录页面

     */

    public String login(){

        return"add";

    }

   

    /*

     * 新增学生

     */

    publicvoid addStudent(){

        String result = studentBiz.addStudent(student);

        HttpServletResponse response = ServletActionContext.getResponse();

        try {

            response.getWriter().write(result);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    /*

     * 查询所有学生

     */

    publicvoid findAllStudents(){

        List<Student> list = studentBiz.findAll();

        //没有做展示页面,直接在控制台输出

        System.out.println(list);

    }

}

2.3.  配置文件配置

2.3.1. 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">

  <display-name>ssh__project</display-name>

    <!--  加载Spring的配置文件 -->

       <context-param>

           <param-name>contextConfigLocation</param-name>

           <param-value>classpath:applicationContext.xml</param-value>

       </context-param>

       <!-- spring监听 -->

       <listener>

           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

       </listener>

       <!-- struts2前端控制器 -->

       <filter>

           <filter-name>struts</filter-name>

           <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

       </filter>

       <filter-mapping>

           <filter-name>struts</filter-name>

           <url-pattern>/*</url-pattern>

       </filter-mapping>

      

       <!-- openSessionInView -->

       <filter>

           <filter-name>openSessionInView</filter-name>

           <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>

       </filter>

       <filter-mapping>

           <filter-name>openSessionInView</filter-name>

           <url-pattern>/*</url-pattern>

       </filter-mapping>

</web-app>

2.3.2. 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.i18n.encoding" value="utf-8"></constant>

<!-- 配置此常量修改struts.xml就无需再重启服务器 -->

<constant name="struts.configuration.xml.reload" value="true"></constant>

 

<package name="demo" extends="struts-default" namespace="/">

    <!-- 如果想要交给Struts2来管理aciton -->

    <!-- <action name="stu_*" class="com.wskj.web.StudentAction" method="{1}"></action> -->

   

    <!-- 交给spring来管理  推荐使用 -->

    <action name="stu_*" class="studentAction" method="{1}">

           <result name="add">/add.jsp</result>

    </action>

</package>

</struts>

2.4.  Jsp页面

Ø  login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>新增页面</title>

</head>

<body>

<form action="${pageContext.request.contextPath}/stu_addStudent" method="post">

    <table>

       <tr>

           <td>学生姓名:</td>

           <td><input type="text" name="student.stuname"/></td>

       </tr>

       <tr>

           <td>年龄:</td>

           <td><input type="number" name="student.age"/></td>

       </tr>

       <tr>

           <td></td>

           <td><button>新增</button></td>

       </tr>

    </table>

</form>

</body>

</html>

访问地址:

新增http://127.0.0.1:8080/ssh/stu_login.action

查询所有:http://127.0.0.1:8080/ssh/stu_findAllStudents.action

3.  所有的jar包依赖汇总

<!-- hibernate start -->

       <dependency>

           <groupId>org.hibernate</groupId>

           <artifactId>hibernate-core</artifactId>

           <version>4.3.11.Final</version>

       </dependency>

       <dependency>

           <groupId>commons-collections</groupId>

           <artifactId>commons-collections</artifactId>

           <version>3.2.1</version>

       </dependency>

       <dependency>

           <groupId>javax.transaction</groupId>

           <artifactId>jta</artifactId>

           <version>1.1</version>

       </dependency>

       <!-- hibernate end -->

       <!-- 数据源开始 -->

       <dependency>

           <groupId>com.alibaba</groupId>

           <artifactId>druid</artifactId>

           <version>1.0.18</version>

       </dependency>

       <!-- 数据源结束 -->

       <!-- Spring start -->

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-orm</artifactId>

           <version>4.2.5.RELEASE</version>

       </dependency>

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-web</artifactId>

           <version>4.2.5.RELEASE</version>

       </dependency>

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-context</artifactId>

           <version>4.2.5.RELEASE</version>

       </dependency>

       <dependency>

           <groupId>org.aspectj</groupId>

           <artifactId>aspectjweaver</artifactId>

           <version>1.8.8</version>

       </dependency>

       <!-- Spring end -->

       <!-- 日志相关 start -->

       <dependency>

           <groupId>org.slf4j</groupId>

           <artifactId>slf4j-log4j12</artifactId>

           <version>1.7.21</version>

       </dependency>

       <!-- 日志相关 end -->

 

       <!-- sturts2 start -->

       <dependency>

           <groupId>org.apache.struts</groupId>

           <artifactId>struts2-spring-plugin</artifactId>

           <!-- <version>2.3.15.3</version> -->

           <version>2.3.24</version>

           <exclusions>

              <exclusion>

                  <groupId>org.springframework </groupId>

                  <artifactId>spring-beans</artifactId>

              </exclusion>

              <exclusion>

                  <groupId>org.springframework </groupId>

                  <artifactId>spring-core</artifactId>

              </exclusion>

              <exclusion>

                  <groupId>org.springframework </groupId>

                  <artifactId>spring-context</artifactId>

              </exclusion>

              <exclusion>

                  <groupId>org.springframework </groupId>

                  <artifactId>spring-web</artifactId>

              </exclusion>

              <exclusion>

                  <groupId>commons-io</groupId>

                  <artifactId>commons-io</artifactId>

              </exclusion>

           </exclusions>

       </dependency>

       <dependency>

           <groupId>commons-io</groupId>

           <artifactId>commons-io</artifactId>

           <version>2.2</version>

       </dependency>

       <!-- sturts2 end -->

 

转载请注明原文地址: https://www.6miu.com/read-2250252.html

最新回复(0)