SSH的整合大全(练习:用户登录)

            SSH的整合大全(练习:用户登录)    

一、前言 

  一个SSH项目的开始避免不了要做项目搭建的过程,这个过程对于那些做过几个项目的IT猿来说:轻而易举。所以,本文对刚学完Hibernate、Struts2、Spring框架且想快速搭建环境,有了个很好的帮助。此搭建的步骤有点多,当时通过自己手动搭建并且快速掌握,对于SSM等环境的搭建,有着举一反三的效果。

二、三大框架架构(整合原理)

  

三、导包

  1)hibernate包

  

 

 

 

 

 

   2)Struts2包

  

 

   3)String包

  

  完成这个就完成整合了80%

四、单独配置Spring容器

  1)创建配置文件,并导入约束(4个)

  application.xml:先弄四大约束(beans|context|aop|tx)

  详细链接:https://blog.csdn.net/richard1997/article/details/81290029

  然后弄成application.xml的效果:导入约束主要是生成这一部分:

  

<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="http://www.springframework.org/schema/beans"
     xsi:schemaLocation="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
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">

 

  

 

 

  创建一个Action包下的UserAction.class类,用来在application.xml里面给他一个bean(测试用的) 

  

  需要在web.xml里面配置启动spring容器。

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

 

  启动服务器,看有没有报错;

五、单独配置Struts2

  1、单独配置struts主配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2    <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5     
 6 <struts>
 7     <package name="crm" namespace="/" extends="struts-default">
 8         <action name="UserAction_*" class="cn.fei.com.fei.UserAction" method="{1}">
 9             <result name="success">/success.jsp</result>
10         </action>
11     </package>
12 </struts>

 

  2、配置struts的过滤器(位置:web.xml)

  <!-- 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整合

  (注意:需要导入一个struts2和Spring的整合包:struts2-spring-plugin-2.3.24.jar)

  1、在struts.xml配置常量

    <!-- struts.objectFactory=spring 将action的创建交给spring容器
         struts.objectFactory.spring.autoWire=name spring负责装配action依赖属性
    -->
    <constant name="struts.objectFactory" value="spring"></constant>

 

  2、整合:有两种整合方案:

    第一种:struts2自己创建action,spring负责组装依赖属性

      不推荐(理由:最好由Spring完整管理action的生命周期,spring中的功能才能用到struts中)

    <package name="crm" namespace="/" extends="struts-default">
        <!-- 
            整合方案1:class属性上仍然配置action的完整类名
                Struts2仍然创建action,由spring负责组装Action中的依赖属性
         -->
        <action name="UserAction_*" class="cn.fei.com.action.UserAction" method="{1}">
            <result name="success">/success.jsp</result>
        </action>
    </package>

application.xml
<bean name="us" class="cn.fei.com.service.impl.UserServiceImpl"> </bean>

    第二种:spring负责创建action以及组装。

  

    
  struts.xml文件
  <package name="crm" namespace="/" extends="struts-default"> <!-- 整合方案2:class属性上填写Spring中action对象的BeanName 完全由spring管理action声明周期,包括Action的创建 注意:需要手动组装依赖属性 --> <action name="UserAction_*" class="userAction" method="{1}"> <result name="success">/success.jsp</result> </action> </package>

  application.xml文件
    <!-- action -->
    <!-- 注意:Action对象作用范围一定是多例的,这样才符合struts2架构 -->
    <bean name="userAction" class="cn.fei.com.action.UserAction">
        <property name="us" ref="us"></property>
    </bean>
    <bean name="us" class="cn.fei.com.service.impl.UserServiceImpl"></bean> 

 

    启动测试:

  

    

 

 

 

 表示成功。

七、单独配置Hibernate

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

  2、配置hibernate

<hibernate-configuration>
    <session-factory>
        <!-- 必要的配置信息:连接数据库的基本参数 -->
        <!-- 将hibernate生成的sql语句打印到控制台 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 将hibernate生成的sql语句格式化(语法缩进) -->
        <property name="hibernate.format_sql">true</property>
        <!-- 
        ## auto schema export  自动导出表结构. 自动建表
        #hibernate.hbm2ddl.auto create        自动建表.每次框架运行都会创建新的表.以前表将会被覆盖,表数据会丢失.(开发环境中测试使用)
        #hibernate.hbm2ddl.auto create-drop 自动建表.每次框架运行结束都会将所有表删除.(开发环境中测试使用)
        #hibernate.hbm2ddl.auto update(推荐使用) 自动生成表.如果已经存在不会再生成.如果表有变动.自动更新表(不会删除任何数据).
        #hibernate.hbm2ddl.auto validate    校验.不自动生成表.每次启动会校验数据库中表是否正确.校验失败.
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
         <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
         <!-- 数据库url -->
        <property name="hibernate.connection.url">jdbc:mysql:///crm</property>
         <!-- 数据库连接用户名 -->
        <property name="hibernate.connection.username">root</property>
         <!-- 数据库连接密码 -->
        <property name="hibernate.connection.password">123</property>
        <!-- 数据库方言
            不同的数据库中,sql语法略有区别. 指定方言可以让hibernate框架在生成sql语句时.针对数据库的方言生成.
            sql99标准: DDL 定义语言  库表的增删改查
                      DCL 控制语言  事务 权限
                      DML 操纵语言  增删改查
            注意: MYSQL在选择方言时,请选择最短的方言.
         -->
         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
         
        <!-- Hibernate加载映射 -->
        <mapping resource="cn/fei/com/domain/Customer.hbm.xml"/>
        <mapping resource="cn/fei/com/domain/LinkMan.hbm.xml"/>
        <mapping resource="cn/fei/com/domain/User.hbm.xml"/>
        <mapping resource="cn/fei/com/domain/Role.hbm.xml"/> 
        <!-- <class-cache
            class="org.hibernate.test.legacy.Simple"
            region="Simple"
            usage="read-write"/> -->
    </session-factory>
</hibernate-configuration>

 

  3、测试

 1 public class HibernateTest {
 2     @Test
 3     public void fun1() {
 4         Configuration conf=new Configuration().configure("hibernate.cfg.xml");
 5         
 6         SessionFactory sf = conf.buildSessionFactory();
 7         
 8         Session session = sf.openSession();
 9         
10         Transaction tx = session.beginTransaction();
11         //---------------------------
12         User user=new User();
13         user.setUser_code("tom");
14         user.setUser_name("汤姆");
15         user.setUser_password("1234567");
16         session.save(user);
17         //---------------------------
18         tx.commit();
19     }
20 }

八、Spring整合Hibernate

  核心整合原理:将sessionFactory对象交给Spring容器管理

  1、applicationContext.xml配置

1     <!-- 将sessionFactory配置到spring容器中 -->
2     <!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 -->
3     <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
4          <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
5     </bean>

 

  2、在原来的基础上测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
//测试Hibernate框架
public class HibernateTest {
    @Resource(name="sessionFactory")
    private SessionFactory sf;
  
    @Test
    public void fun2() {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        //---------------------------
        User user=new User();
        user.setUser_code("jeddddy");
        user.setUser_name("汤姆da");
        user.setUser_password("1234567");
        session.save(user);
        //---------------------------
        tx.commit();
    }

 

  3、方案二:(推荐使用,那么原来的hibernate.cfg.xml就不用了)

  

九、Spring整合c3p0连接池(可以不用搭建)

  1、对applicationContext.xml进行配置修改

 

 

 

   在sessionFactory里面注入属性dataSource

  

  2、注意点:增删改的时候,都是要提交事务的。hibernate是自动提交事务的,而从c3p0里面或者连接池,则要配置手动提交事务

十、Spring整合Hibernate环境操作数据库

  1、dao类创建:继承HibernateDaoSupport

  

  2、hibernate模板的操作

    a、HQL

    

    b、Criteria

  3、spring中配置dao

  4、测试类

十一、Spring的aop事务

  1、applicationContext.xml配置核心事务管理器

  2、配置aop事务(也是有两种操作)

    1)xml配置aop事

    

    2)注解配置aop事务(我使用的

      开始注解事务:applicationContext.xml 

    <!-- 开启注解事务 -->
     <tx:annotation-driven transaction-manager="transactionManager"/>

 

      Service使用注解:

 

  

   3、遇到的问题

    在applicationContext.xml管理hibernate时,由于DataSource配置是从Hibernate.cgf.xml里面获取的,当添加事务transactionManager,那么原来的查询都会报错,具体的错误分析链接:https://blog.csdn.net/u014403008/article/details/44774665,需要在applicationContext.xml里面配置获取dataSource等属性,hibernate主配置文件都可以在里面配置,所以hibernate的主配置文件是没有用的。

十二、扩大Session的作用范围

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

  配置filter:

  <!-- 打开OpenSessionInView ,扩大session作用范围
      注意:Opensession要在struts的filter前面
  -->
  <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、Action类的编辑

  

  2、service的编辑

  3、Struts.xml添加异常处理

  4、结果显示

 

 

十四、总结  

  第一次整合,确实有觉得比较多,也等过了几天的时间就忘记配置的原理和步骤,但是不需要再重新看着教程接着配置一遍,单单看这篇文章就很快的回忆起来,比较这些都是没有什么难度的,最好熟悉配置的步骤和实现细节,方便接下来的开发出现的问题,排错比较快。这是我的第一编博客文章,水平有限,写的不是特别的好,请各位多多谅解。接下来就是对SSM框架的整合了。尽情期待。小生告辞。

posted @ 2020-01-06 15:15  薯餠  阅读(138)  评论(0)    收藏  举报