服务器之家

服务器之家 > 正文

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)

时间:2020-11-27 10:53     来源/作者:kent鹏

一、整合原理

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)

二、导包(41个)

1.hibernate

(1)hibernate/lib/required

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)  

(2)hibernate/lib/jpa | java persist api java的持久化规范(接口)

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)  

(3)数据库驱动

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)  

2.struts2

(1)struts-blank.war/web-inf/lib/*

 注意:javassist-3.18.1-ga.jar包与hibernate中的重复(只保留高版本即可)

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)  

(2)struts整合spring插件包

注意:这个包一旦导入,那么struts2在启动时就会寻找spring容器.找不到将会抛出异常

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)  

3.spring

(1)基本:4+2

core | beans | context | expression | logging | log4j

(2)整合web:web包

spring-web

(3)整合aop:4个

spring-aop | spring-aspect | aop联盟 | aopweaving

(4)整合hibernate和事务:4个

spring-jdbc | spring-tx | c3p0 | spring-orm

(5)整合junit4测试:test包

spring-test

4.标签库

standard.jar | jstl-1.2.jar

三、单独配置spring容器

1.创建applicationcontext.xml,并导入约束(4个) beans | context | aop | tx

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    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-4.2.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
              http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
 
  <bean name="useraction" class="cn.xyp.web.action.useraction"></bean>
 
</beans>

2.配置spring随项目启动(web.xml)

?
1
2
3
4
5
6
7
8
9
<!-- 让spring随web启动而创建的监听器 -->
<listener>
  <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
</listener>
<!-- 配置spring配置文件位置参数 -->
<context-param>
  <param-name>contextconfiglocation</param-name>
  <param-value>classpath:applicationcontext.xml</param-value>
</context-param>

四、单独配置struts2

1.配置struts2主配置文件(struts.xml)

?
1
2
3
4
5
6
7
8
9
10
11
12
<?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="crm" namespace="/" extends="struts-default">
    <action name="useraction_*" class="cn.xyp.web.action.useraction" method="{1}">
      <result name="success">/success.jsp</result>
    </action>
  </package>
</struts>

2.配置struts2核心过滤器到web.xml

?
1
2
3
4
5
6
7
8
9
10
<!-- 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>

五、struts2与spring整合

1.导包(已经导入)

struts2-spring-plugin-2.3.24.jar

2.配置常量

查看默认配置文件从31行开始找到要配置的变量。

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)  

?
1
2
3
4
5
6
7
8
### if specified, the default object factory can be overridden here
### note: short-hand notation is supported in some cases, such as "spring"
###    alternatively, you can provide a com.opensymphony.xwork2.objectfactory subclass name here
# struts.objectfactory = spring
 
### specifies the autowiring logic when using the springobjectfactory.
### valid values are: name, type, auto, and constructor (name is the default)
struts.objectfactory.spring.autowire = name

 添加常量到struts.xml

?
1
2
3
4
<!-- # struts.objectfactory = spring  将action的创建交给spring容器 
    struts.objectfactory.spring.autowire = name spring负责装配action依赖属性
    -->
<constant name="struts.objectfactory" value="spring"></constant>

3.整合方案1:struts2自己创建action,spring负责组装依赖属性(了解)

?
1
2
3
4
5
6
7
<!-- 整合方案1:class属性上仍然配置action的完整类名
        struts2仍然创建action,由spring负责组装action中的依赖属性
     -->
    <action name="useraction_*" class="cn.xyp.web.action.useraction" method="{1}" >
      <result name="tohome" type="redirect" >/index.htm</result>
      <result name="error" >/login.jsp</result>
    </action>

不推荐理由:最好由spring完整管理action的生命周期.spring中功能才应用到action上.

4.整合方案2:spring负责创建action以及组装.(推荐)

applicationcontext.xml:

?
1
2
3
4
5
<!-- action -->
<!-- 注意:action对象作用范围一定是多例的.这样才符合struts2架构 -->
<bean name="useraction" class="cn.itcast.web.action.useraction" scope="prototype" >
  <property name="userservice" ref="userservice" ></property>
</bean>

struts.xml:

?
1
2
3
4
5
6
7
8
9
<!--
   整合方案2:class属性上填写spring中action对象的beanname
     完全由spring管理action生命周期,包括action的创建
     注意:需要手动组装依赖属性
 -->
<action name="useraction_*" class="useraction" method="{1}" >
  <result name="tohome" type="redirect" >/index.htm</result>
  <result name="error" >/login.jsp</result>
</action>

六、单独配置hibernate

1.导入实体类&orm元数据

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)  

举例:user.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package cn.xyp.web.domain;
 
import java.util.hashset;
import java.util.set;
 
public class user {
  private long user_id;
  private string user_code;
  private string user_name;
  private string user_password;
  private character user_state;
  public long getuser_id() {
    return user_id;
  }
  public void setuser_id(long user_id) {
    this.user_id = user_id;
  }
  public string getuser_code() {
    return user_code;
  }
  public void setuser_code(string user_code) {
    this.user_code = user_code;
  }
  public string getuser_name() {
    return user_name;
  }
  public void setuser_name(string user_name) {
    this.user_name = user_name;
  }
  public string getuser_password() {
    return user_password;
  }
  public void setuser_password(string user_password) {
    this.user_password = user_password;
  }
  public character getuser_state() {
    return user_state;
  }
  public void setuser_state(character user_state) {
    this.user_state = user_state;
  }
  @override
  public string tostring() {
    return "user [user_id=" + user_id + ", user_code=" + user_code + ", user_name=" + user_name + ", user_password="
        + user_password + "]";
  }
}

user.hbm.xml:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<!doctype hibernate-mapping public
  "-//hibernate/hibernate mapping dtd 3.0//en"
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.xyp.domain" >
  <class name="user" table="sys_user" >
    <id name="user_id" >
      <generator class="native"></generator>
    </id>
    <property name="user_code" ></property>
    <property name="user_name" ></property>
    <property name="user_password" ></property>
    <property name="user_state" ></property>
  
  </class>
</hibernate-mapping>

2.配置主配置文件(hibernate.xml)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?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>
  
     <!-- 数据库驱动 -->
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.driver</property>
     <!-- 数据库url -->
    <property name="hibernate.connection.url">jdbc:mysql:///crm_32</property>
     <!-- 数据库连接用户名 -->
    <property name="hibernate.connection.username">root</property>
     <!-- 数据库连接密码 -->
    <property name="hibernate.connection.password">1234</property>
    <!-- 数据库方言
      注意: mysql在选择方言时,请选择最短的方言.
     -->
    <property name="hibernate.dialect">org.hibernate.dialect.mysqldialect</property>
    
    
    <!-- 将hibernate生成的sql语句打印到控制台 -->
    <property name="hibernate.show_sql">true</property>
    <!-- 将hibernate生成的sql语句格式化(语法缩进) -->
    <property name="hibernate.format_sql">true</property>
    <!--
    自动导出表结构. 自动建表
     -->
    <property name="hibernate.hbm2ddl.auto">update</property>
     
     <!-- 引入实体配置文件 -->
    <mapping resource="cn/xyp/domain/customer.hbm.xml" />
    <mapping resource="cn/xypt/domain/linkman.hbm.xml" />
    <mapping resource="cn/xyp/domain/user.hbm.xml" />
    
  </session-factory>
</hibernate-configuration>

七、spring整合hibernate

1.整合原理

将sessionfactory对象交给spring容器管理

2.在spring中配置sessionfactory

(1)配置方案一:(了解) 

?
1
2
3
4
<!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 -->
  <bean name="sessionfactory" class="org.springframework.orm.hibernate5.localsessionfactorybean" >
    <property name="configlocation" value="classpath:hibernate.cfg.xml" ></property>
  </bean>

(2)配置方案二:(推荐)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!-- 加载配置方案2:在spring配置中放置hibernate配置信息 -->
<bean name="sessionfactory" class="org.springframework.orm.hibernate5.localsessionfactorybean" >
  <!-- 将连接池注入到sessionfactory, hibernate会通过连接池获得连接 -->
  <property name="datasource" ref="datasource" ></property>
  <!-- 配置hibernate基本信息 -->
  <property name="hibernateproperties">
    <props>
      <!-- 必选配置 -->
      <prop key="hibernate.connection.driver_class" >com.mysql.jdbc.driver</prop>
      <prop key="hibernate.connection.url" >jdbc:mysql:///crm_32</prop>
      <prop key="hibernate.connection.username" >root</prop>
      <prop key="hibernate.connection.password" >1234</prop>
      <prop key="hibernate.dialect" >org.hibernate.dialect.mysqldialect</prop>
      
      <!-- 可选配置 -->
      <prop key="hibernate.show_sql" >true</prop>
      <prop key="hibernate.format_sql" >true</prop>
      <prop key="hibernate.hbm2ddl.auto" >update</prop>
    </props>
  </property>
  <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
  <property name="mappingdirectorylocations" value="classpath:cn/itcast/domain" ></property>
</bean>

八、spring整合c3p0连接池

1.配置db.properties

?
1
2
3
4
jdbc.jdbcurl=jdbc:mysql:///xyp_crm
jdbc.driverclass=com.mysql.jdbc.driver
jdbc.user=root
jdbc.password=123456

2.引入连接池到spring中

?
1
2
3
4
5
6
7
8
9
<!-- 读取db.properties文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置c3p0连接池 -->
<bean name="datasource" class="com.mchange.v2.c3p0.combopooleddatasource" >
  <property name="jdbcurl" value="${jdbc.jdbcurl}" ></property>
  <property name="driverclass" value="${jdbc.driverclass}" ></property>
  <property name="user" value="${jdbc.user}" ></property>
  <property name="password" value="${jdbc.password}" ></property>
</bean>

3.将连接池注入给sessionfactory

?
1
2
3
<bean name="sessionfactory" class="org.springframework.orm.hibernate5.localsessionfactorybean" >
  <!-- 将连接池注入到sessionfactory, hibernate会通过连接池获得连接 -->
  <property name="datasource" ref="datasource" ></property>

九、spring整合hibernate环境操作数据库

1.dao类创建:继承hibernatedaosupport

注意:项目中要确保使用统一版本。

详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)

?
1
2
//hibernatedaosupport 为dao注入sessionfactory
public class userdaoimpl extends hibernatedaosupport implements userdao {

2.hibernate模板的操作

(1)execute
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@override
public user getbyusercode(final string usercode) {
  //hql
  return gethibernatetemplate().execute(new hibernatecallback<user>() {
    @override
    public user doinhibernate(session session) throws hibernateexception {
        string hql = "from user where user_code = ? ";
        query query = session.createquery(hql);
        query.setparameter(0, usercode);
        user user = (user) query.uniqueresult();
      return user;
    }
  });

(2)findbycriteria

?
1
2
3
4
5
6
7
8
9
10
11
12
//criteria
detachedcriteria dc = detachedcriteria.forclass(user.class);
 
dc.add(restrictions.eq("user_code", usercode));
 
list<user> list = (list<user>) gethibernatetemplate().findbycriteria(dc);
  
if(list != null && list.size()>0){
  return list.get(0);
}else{
  return null;
}

3.spring中配置dao

?
1
2
3
4
5
<!-- dao -->
<bean name="userdao" class="cn.xyp.dao.impl.userdaoimpl" >
  <!-- 注入sessionfactory -->
  <property name="sessionfactory" ref="sessionfactory"></property>
</bean>

十、spring的aop事务

1.准备工作

?
1
2
3
4
<!-- 核心事务管理器 -->
<bean name="transactionmanager" class="org.springframework.orm.hibernate5.hibernatetransactionmanager" >
  <property name="sessionfactory" ref="sessionfactory" ></property>
</bean>

2.xml配置aop事务

(1)配置通知

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- 配置通知 -->
<tx:advice id="txadvice" transaction-manager="transactionmanager" >
  <tx:attributes>
    <tx:method name="save*" isolation="repeatable_read" propagation="required" read-only="false" />
    <tx:method name="persist*" isolation="repeatable_read" propagation="required" read-only="false" />
    <tx:method name="update*" isolation="repeatable_read" propagation="required" read-only="false" />
    <tx:method name="modify*" isolation="repeatable_read" propagation="required" read-only="false" />
    <tx:method name="delete*" isolation="repeatable_read" propagation="required" read-only="false" />
    <tx:method name="remove*" isolation="repeatable_read" propagation="required" read-only="false" />
    <tx:method name="get*" isolation="repeatable_read" propagation="required" read-only="true" />
    <tx:method name="find*" isolation="repeatable_read" propagation="required" read-only="true" />
  </tx:attributes>
</tx:advice>

(2)配置织入

?
1
2
3
4
5
6
7
<!-- 配置将通知织入目标对象
配置切点
配置切面 -->
<aop:config>
  <aop:pointcut expression="execution(* cn.itcast.service.impl.*serviceimpl.*(..))" id="txpc"/>
  <aop:advisor advice-ref="txadvice" pointcut-ref="txpc" />
</aop:config>

3.注解配置aop事务

(1)开启注解事务

?
1
2
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="transactionmanager" />

(2)service类中使用注解

?
1
2
@transactional(isolation=isolation.repeatable_read,propagation=propagation.required,readonly=true)
public class userserviceimpl implements userservice{
?
1
2
3
4
5
@override
@transactional(isolation=isolation.repeatable_read,propagation=propagation.required,readonly=false)
public void saveuser(user u) {
  ud.save(u);
}

十一、扩大session作用范围

1.配置filter

为了避免使用懒加载时出现no-session问题.需要扩大session的作用范围。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- 扩大session作用范围
  注意: 任何filter一定要在struts的filter之前调用
  因为struts是不会放行的
 -->
 <filter>
  <filter-name>opensessioninview</filter-name>
  <filter-class>org.springframework.orm.hibernate5.support.opensessioninviewfilter</filter-class>
</filter>
 
<filter-mapping>
  <filter-name>opensessioninview</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

十二、练习:用户登录

1.struts.xml核心配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<struts>
  <!-- # struts.objectfactory = spring  将action的创建交给spring容器 
      struts.objectfactory.spring.autowire = name spring负责装配action依赖属性
      -->
  <constant name="struts.objectfactory" value="spring"></constant>
 
  <package name="crm" namespace="/" extends="struts-default" >
    <global-exception-mappings>
      <exception-mapping result="error" exception="java.lang.runtimeexception"></exception-mapping>
    </global-exception-mappings>
 
     <!--
       整合方案:class属性上填写spring中action对象的beanname
         完全由spring管理action生命周期,包括action的创建
         注意:需要手动组装依赖属性
     -->
    <action name="useraction_*" class="useraction" method="{1}" >
      <result name="tohome" type="redirect" >/index.htm</result>
      <result name="error" >/login.jsp</result>
    </action>
  </package>
</struts>

2.action代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class useraction extends actionsupport implements modeldriven<user> {
  private user user = new user();
  
  private userservice userservice ;
  
  public void setuserservice(userservice userservice) {
    this.userservice = userservice;
  }
 
  public string login() throws exception {
      //1 调用service执行登陆逻辑
      user u = userservice.getuserbycodepassword(user);
      //2 将返回的user对象放入session域
      actioncontext.getcontext().getsession().put("user", u);
      //3 重定向到项目首页
    return "tohome";
  }
 
  @override
  public user getmodel() {
    return user;
  }
 
}

2.service核心代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public user getuserbycodepassword(user u) {
  // 1 根据登陆名称查询登陆用户
  user existu = ud.getbyusercode(u.getuser_code());
  // 2 判断用户是否存在.不存在=>抛出异常,提示用户名不存在
  if (existu == null) {
    throw new runtimeexception("用户名不存在!");
  }
  // 3 判断用户密码是否正确=>不正确=>抛出异常,提示密码错误
  if (!existu.getuser_password().equals(u.getuser_password())) {
    throw new runtimeexception("密码错误!");
  }
  // 4 返回查询到的用户对象
  return existu;
}

3.dao核心代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public user getbyusercode(final string usercode) {
 
  //criteria
  detachedcriteria dc = detachedcriteria.forclass(user.class);
  dc.add(restrictions.eq("user_code", usercode));
  
  list<user> list = (list<user>) gethibernatetemplate().findbycriteria(dc);
  
  if(list != null && list.size()>0){
    return list.get(0);
  }else{
    return null;
  }
  
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/xieyupeng/p/7108141.html?utm_source=tuicool&utm_medium=referral

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
最新idea2020注册码永久激活(激活到2100年)
最新idea2020注册码永久激活(激活到2100年) 2020-07-29
返回顶部