spring学习笔记(ssh整合 -- 上)

接下来详细分析一下 ssh的整合,我将分步骤进行解释。
一、导包

1.hibernate 的包
在源码包中required 包中的所有包
还有 hibernate-jpa-2.1-api-1.0.0.Final.jar
数据库驱动包

2.Struts2 的包
在源码包中 blank.war中lib下的所有包
struts2-spring 包

3.spring 的包
基本的包:4+2 (spring-core spring-context spring-expression spring-beans logging log4j)
整合jdbc事务:4(spring-tx spring-jdbc c3p0 spring-orm)
整合aop:(spring-aop spring-aspects weaver aopalliance)
整合web : spring-web

全部导入后,检查重复的去掉低版本的,总共有41个 ,然后导入约束,具体的可以看下面的代码。

二、写代码测试

  1. 编写配置文件:在src下配置 ApplicationContext.xml
<?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 ">

<!-- 配置action 要配置成 prototype -->
<bean name="userAction" class="com.tz.web.action.UserAction" scope="prototype">
    <property name="userService" ref="userService"></property>
</bean>
<bean name="userService" class="com.tz.service.Impl.UserServiceImpl"></bean>

配置struts2.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>
    <!-- 将action对象交给 spring容器  -->
    <constant name="struts.objectFactory" value="spring"></constant>
    <package name="user" namespace="/" extends="struts-default">
        <action name="userAction_*" class="userAction" method="{1}">
            <result name="success">/index.jsp</result>
        </action>
    </package>
</struts>
  1. 创建User实体类,service类
public class User implements Serializable{
    /**
     */ 
    private Long   user_id;
    private String user_name;

    public Long getUser_id() {
        return user_id;
    }

    public void setUser_id(Long user_id) {
        this.user_id = user_id;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

}
public class UserServiceImpl implements UserService {

    @Override
    public User checkCode(User user) {
        System.out.println("登录成功!!!");
        return user;
    }

}
  1. 创建aciton类
public class UserAction extends ActionSupport{

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String login(){
        System.out.println("hello"+userService);
        return SUCCESS;
    }

}

通过测试,spring能够整合struts2管理aciton 对象。


接下来我们来整合hibernate:

  1. 配置User.hbm.xml
<?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="com.tz.domain">
        <class name="User" table="sys_user">
            <id name="user_id">
                <generator class="native"></generator>
            </id>
            <property name="user_name"></property>
        </class>
    </hibernate-mapping>

2.将sessionFactory配置到spring中,有两种方法:第一种是还是使用hibernate的主配置文件,在spring配置文件中指定路径。但是不推荐使用这种方式,因为比较繁琐。接下来使用第二种方式:

<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

    <property name="hibernateProperties">
        <props>
        <prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop>
            <prop key="hibernate.connection.url" >jdbc:mysql:///ssh_xxx?useUnicode=true&amp;characterEncoding=UTF-8</prop>
            <prop key="hibernate.connection.username" >root</prop>
            <prop key="hibernate.connection.password" >xxx</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元数据  -->
    <property name="mappingDirectoryLocations" value="classpath:com/tz/domain">
    </property>

这样的话,我们就将hibernate和spring整合到一起了,下面通过测试类测试一下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:ApplicationContext.xml")
public class hibernateTest {
   @Resource(name="sessionFactory")
   private SessionFactory sFactory;
   @Test
   public void test(){
      Session session = sFactory.openSession();  //此处使用spring 帮我们创建的sessionFactory
       Transaction tz = session.beginTransaction();

       User user = new User();
       user.setUser_name("啦啦啦");
       session.save(user);
       tz.commit();
       session.close();
      }

查看数据库,有此记录表示整合成功了。

还有一种常用的方式:c3p0 连接池,也来学习一下:
我们只需创建db.properties文件 ,并在spring中配置进去就行了

db.properties代码:

jdbc.jdbcUrl= jdbc:mysql:///数据库名xxxx
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=你的密码xxx

在spring中的修改如下:

把刚才配置的内容修改为c3p0的连接

<!-- 配置c3p0连接池 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <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>

<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <!-- 引入dataSource连接池  ,下面的hibernate的连接就不需要了  -->
    <property name="dataSource" ref="dataSource"></property>
    <property name="hibernateProperties">
        <props>
            <!-- <prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop>
            <prop key="hibernate.connection.url" >jdbc:mysql:///ssh_crm?useUnicode=true&amp;characterEncoding=UTF-8</prop>
            <prop key="hibernate.connection.username" >root</prop>
            <prop key="hibernate.connection.password" ></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元数据  -->
    <property name="mappingDirectoryLocations" value="classpath:com/tz/domain">
    </property>

同样进行测试:

 @Test
   public void test3(){
       Session session = sFactory.openSession();
       Transaction tz = session.beginTransaction();
       User user = session.get(User.class, 3L);
       System.out.println(user.getUser_name());
       tz.commit();
       session.close();

   }

好了,这次的整合就先到这里,下篇文章继续介绍。

猜你喜欢

转载自blog.csdn.net/weixin_38008100/article/details/81513216