最新版ssh hibernate spring struts2環境搭建

最新版ssh hibernate spring struts2環境搭建

最新版spring Framework下載地址:spring4.0.0RELEASE環境搭建
http://repo.spring.io/release/org/springframework/spring/4.0.0.RELEASE/html

最新版hibernate下載地址:hibernate4.2.21
https://sourceforge.net/projects/hibernate/postdownload?source=dlpjava

最新版struts2下載地址:struts2 2.5.2
https://struts.apache.org/mysql

上面的版本就是本次搭建環境所用到的版本,若是爲了學習使用的能夠經過連接下載。由於如今ssh框架跟新,然而網絡上最新版的ssh環境搭建的教程尚未,雖然版本變換都差很少,可是仍是簡單的介紹下,記錄本身學習的過程,也做爲一種分享。程序員

簡單介紹本次教程(適合簡單入門):
使用的開發環境是intelliJ Idea
先介紹單個的搭建案例,而且給出小型的Demo
而後再整合框架,例子的話就是簡單的測試Demoweb

在看教程以前,我想您須要瞭解hibernate Spring struts2都是幹什麼的,有什麼做用,至少要知道定義吧,如今這篇教程只是講解手動的去搭建環境,沒有使用maven等等項目構建工具,以後會寫試用項目構架工具構建項目。spring


一、hibernate

簡單說說hibernate,hibernate是一個基於JDBC的封裝框架,解決的問題天然就是數據的增刪改查所謂的持久化操做,讓JDBC操做變得更加面向對象,一切的操做均可以面向對象化。sql

1)、依賴jar包

hibernate-release-4.2.21.Final/lib/required/  下面全部的jar
        antlr-2.7.7.jar
        dom4j-1.6.1.jar
        hibernate-commons-annotations-4.0.2.Final.jar
        hibernate-core-4.2.21.Final.jar
        hibernate-jpa-2.0-api-1.0.1.Final.jar
        javassist-3.18.1-GA.jar
        jboss-logging-3.1.0.GA.jar      
        jboss-transaction-api_1.1_spec-1.0.1.Final.jar

上面帶有jboss的兩個jar是須要的,以前測試過,我認爲沒有使用到jboss因此去掉兩個jar以後會報錯,除了這些jar咱們還須要mysql驅動,上面的jar在hibernate-release-4.2.21.Final/lib/required/路徑下,全部的都須要導入。數據庫

上面這張圖就是個人目錄結構,很是簡單的目錄結構,若是你是使用intelliJ Idea那簡直就更好了express

這裏我就不去過多的簡紹,每個jar有什麼做用,可是會在spring的時候回去講,由於這裏的jar都比較簡單,沒有不少,相信只要知道一點單詞就能知道jar是什麼意思了吧。apache

好了,若是你是用的是eclipse那麼必定記得要把jar變成小奶瓶哦!!


2)、配置

要搭建hibernate還須要配置文件的支持,在這裏就稍微講解hibernate的配置文件:

hibernate.cfg.xml配置文件,這個配置文件再練習的時候放在src目錄下面

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
      <session-factory>
        <!--
            下面兩個是使用的數據庫鏈接方式和數據庫驅動,固定寫法,根據你使用的數據庫決定,我使用的是mysql
        -->
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernateDemo1</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    
        <!--這個是在控制檯打印sql語句的時候進行格式化的,程序調試期間建議加上-->
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <!--打印顯示sql語句-->
        <property name="show_sql">true</property>
        <!--用戶名密碼-->
        <property name="connection.username">root</property>
        <property name="connection.password">123</property>
        
        <!--每新建一個映射文件都須要-->
        <mapping resource="com/cn/ljh/domain/Person.hbm.xml"/>
      </session-factory>
    </hibernate-configuration>

上面這些配置在作簡單的搭建環境這裏是足夠使用的,這裏面還有不少參數,做爲入門暫時先了解那麼多,在未來可能還會降到其餘的參數。

下面先看一下個人目錄結構:

能夠看到,這個是很是簡單的文件結構,那麼只是爲了測試搭建是否成功作的測試

建立一個工具類HibernateUtils用於讀取hibernate.cfg.xml配置文件,而且獲取SessionFactory對象

package com.cn.ljh.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Created by ljh on 16/8/15.
 */
public class HibernateUtils {
    public static SessionFactory sessionFactory;
    static {
        Configuration configuration = new Configuration();
        configuration.configure();
        configuration.buildSessionFactory();
    }
}

上面就是HibernateUtils中的代碼,主要用於初始化的時候獲取配置文件和sessionfactory對象。

注意:上面讀取hibernate.cfg.xml文件的路徑是在項目根路徑,由於咱們將配置文件放在src目錄下,因此直接這樣寫就能夠。若是你是放在其餘的路徑那麼就不是這樣寫。
package com.cn.ljh.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Created by ljh on 16/8/15.
 */
public class HibernateUtils {
    public static SessionFactory sessionFactory;
    static {
        Configuration configuration = new Configuration();
        configuration.configure("(假設文件路徑)/com/cn/config");
        configuration.buildSessionFactory();
    }
}

若是你是講配置文件放在上圖中的路徑,那麼就是上面的寫法。

接下來就是建立javaBean對象Person

package com.cn.ljh.domain;

/**
 * Created by ljh on 16/8/15.
 */
public class Person {
    private Long pid;       //id做爲主鍵
    private String username;
    private String password;
    private String sex;

    public Long getPid() {
        return pid;
    }

    public void setPid(Long pid) {
        this.pid = pid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

上面就是最簡單的javaBean,常見好一個javaBean以後咱們還須要建立對應的映射文件Person.hbm.xml通常以類名.hbm.xml做爲文件名方便管理。

接下來就是建立Person映射文件:

<?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>
       <class name="com.cn.ljh.domain.Person" table="person">
           <id name="pid" type="java.lang.Long" length="10">
               <generator class="increment"/>
           </id>
           <property name="password" type="java.lang.String" length="10"/>
           <property name="username" type="java.lang.String" length="10"/>
           <property name="sex" type="java.lang.String" length="10"/>
       </class>
    </hibernate-mapping>

上面的映射文件算是最簡單的映射文件了,沒有一對多,多對多,一對一這些內容,自有簡單的一張表,簡單的設置了id做爲主鍵,而且讓主鍵自動增加,其次是其餘字段做爲表中的屬性,這裏就很少解釋,若是不知道,那麼就跟着動手作起來,慢慢去嘗試總會懂得。

最後就是測試環境是否搭建成功:

編寫測試類

package com.cn.ljh.test;

import com.cn.ljh.utils.HibernateUtils;
import org.junit.Test;

/**
 * Created by ljh on 16/8/15.
 */
public class HibernateTest extends HibernateUtils{
    @Test
    public void test1(){

    }
}

很是簡單的測試類,咱們繼承HibernateUtils,而後執行一個測試方法,只要文件Hibernateutils被加載,那麼就會建立你文件的映射,在數據庫中建立person表,那麼前提是你得安裝了數據庫,而且建立好一個空的數據庫。

到如今這個簡單的測試完成了,結果圖:

到這裏就說明環境搭建是沒有問題的,就能夠與開心的學習hibernate了。


二、spring

就簡單說說spring,提供了ioc依賴注入、aop面向切面編程,是輕量級的框架,可以管理javaBean的生命週期,能夠單獨進行使用也能夠很不少主流框架結合使用,好比hibernate、struts、Mybatis等等,而且和spring MVC的無縫銜接更是堪稱完美。

1)、依賴jar包

//用於支持aop面向切面編程
        spring-aop-4.0.0.RELEASE.jar
        //提供對AspectJ的支持,以即可以方便的將面向方面的功能集成進IDE中
        spring-aspects-4.0.0.RELEASE.jar
        //這個jar 文件是全部應用都要用到的,它包含訪問配置文件、建立和管理bean 以及進行Inversion of Control / Dependency Injection(IoC/DI)操做相關的全部類。若是應用只需基本的IoC/DI 支持,引入spring-core.jar 及spring-beans.jar 文件就能夠了。
外部依賴spring-core,(CGLIB)。
        spring-beans-4.0.0.RELEASE.jar
        //這個看名字也該知道吧,build src
        spring-build-src-4.0.0.RELEASE.jar
        //下面兩個Spring-context的擴展支持,用於MVC方面
        spring-context-4.0.0.RELEASE.jar
        spring-context-support-4.0.0.RELEASE.jar
        //這個就不用說了spring的核心jar
        spring-core-4.0.0.RELEASE.jar
        //這個看名字也知道,Spring表達式語言
        spring-expression-4.0.0.RELEASE.jar
        //這個是後來隨着spring發展纔出現的,解決spring多依賴問題,能夠去搜索spring bom
        spring-framework-bom-4.0.0.RELEASE.jar
        //spring4.0對服務器的代理接口
        spring-instrument-4.0.0.RELEASE.jar
        //spring4.0對tomcat的集成
        spring-instrument-tomcat-4.0.0.RELEASE.jar
        //對jdbc簡單的封裝
        spring-jdbc-4.0.0.RELEASE.jar
        //爲了簡化jms API簡單的封裝
        spring-jms-4.0.0.RELEASE.jar
        //這個是國際化的支持
        spring-messaging-4.0.0.RELEASE.jar
        //爲了整合第三方框架,如hibernate等
        spring-orm-4.0.0.RELEASE.jar
        //spring對object/xml的映射支持
        spring-oxm-4.0.0.RELEASE.jar
        //對Junit等測試框架的簡單封裝
        spring-test-4.0.0.RELEASE.jar
        //這個是有關事務管理的
        spring-tx-4.0.0.RELEASE.jar
        //下面這三個不就是和web mvc有關的嗎
        spring-web-4.0.0.RELEASE.jar
        spring-webmvc-4.0.0.RELEASE.jar
        spring-webmvc-portlet-4.0.0.RELEASE.jar
        //這個是spring和websocket有關的
        spring-websocket-4.0.0.RELEASE.jar

上面這些jar是全部的spring 4.0.0.RELEASE jar,若是隻是單獨使用的話沒有必要將這些jar都加進來,像web這些就不須要,其實咱們看名字就能看出不少jar是作什麼用的,在spring這裏咱們仍是要詳細介紹一下每個jar具體是什麼做用,如今看到jar你還有選擇恐懼整嘛,什麼是能夠缺乏的什麼是不能缺乏的不就一目瞭然了,若是對上面的解釋還還以爲不夠詳細能夠參考:

http://blog.csdn.net/w_wind/article/details/18370715

http://www.cnblogs.com/leehongee/archive/2012/10/01/2709541.html

寫的很好的,我也有借鑑他們的不少東西。

下面上一張圖,看看個人目錄結構是什麼樣子的吧:

上面我將全部的release的jar都加上了,有些是用不上的,好比websocket這樣的,可是看了下真實項目中其實上面這些基本上都能用上,因此仍是都加上來吧。


2)、配置

applicationContext.xml

<!--bean.xml或者applicationContext.xml(根據本身的喜愛選擇Spring的配置文件名字)-->
        <!--spring框架很是靈活,因此該配置文件也很是靈活-->
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
                "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

        <beans>
            <bean id="..." class="...">
                <property name="isolation">
                    <bean id="java.sql.Connection.TRANSACTION_SERIALIZABLE"
                            class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" />
                </property>
            </bean>
        </beans>

上面這個只是簡單的實例,並非具體的配置。

接下來,經過我本身簡單的例子來

如今來建立dao daoimpl domain,而後經過spring來管理這些對象

dao

public interface StudentDao {

    public void addStudent(Student student);

    public void delStudent(Long pid);

    public void updateStudent(Student student);


}

建立daoimpl

package com.cn.ljh.dao.impl;

import com.cn.ljh.dao.StudentDao;
import com.cn.ljh.domain.Student;

/**
 * Created by ljh on 16/8/17.
 */
public class StudentDaoImpl implements StudentDao {
    @Override
    public void addStudent(Student student) {
        System.out.println("addStudent");
    }

    @Override
    public void delStudent(Long pid) {
        System.out.println("delStudent");
    }

    @Override
    public void updateStudent(Student student) {
        System.out.println("udateStudent");
    }
}

建立javaBean

package com.cn.ljh.domain;

import com.opensymphony.xwork2.ActionSupport;

import java.io.Serializable;

/**
 * Created by ljh on 16/8/17.
 */
public class Student extends ActionSupport implements Serializable {
    private Long sid;
    private String name;
    private String sex;
    private int age;
    private Course course;

    public Long getSid() {
        return sid;
    }

    public void setSid(Long sid) {
        this.sid = sid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

        
    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", course=" + course +
                '}';
    }
}

如今想要須要將對象注入到spring容器中,經過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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="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-4.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       ">


  
   

    <bean name="student" class="com.cn.ljh.domain.Student">
        <property name="name" value="小紅"/>
        <property name="age" value="12"/>
        <property name="sex" value="男"/>
    </bean>

    <bean name="studentDao" class="com.cn.ljh.dao.impl.StudentDaoImpl"/>
</beans>

可能會注意到,beans中有不少頭部信息,這些都是本身添加進去的,簡單介紹一下:

xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       
       
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd

上面這些頭部信息的做用就是你須要使用到spring什麼相關的技術就在上面添加相應的頭部請求便可:

那麼我在下面整理出spring經常使用的技術和所對應的頭部信息:

咱們打開下載好的spring而且解壓成文件夾後:

上面這幅圖中就是全部spring中的技術,每用到一個組件技術,咱們都須要在beans上面去添加頭部信息,咱們看到還有版本號,spring-aop-4.0.xsd,我建議用什麼版本的spring就用什麼版本的,這樣才能用到新版本的特性,固然你用其餘版本也是兼容的,可是在有的時候兼容也不是很好。隨便打開一個看看:

1).這個就是要導入的
2).這個和下面兩個消息對比一下你就知道要怎麼寫啦

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

對比對比,你在下去嘗試打開其餘的文件,對比對比我導入的你就會發現,全都是套路,那還怕什麼呢。

可是仍是整理一下方便本身吧

The util schema

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

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd

The jee schema

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

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

The lang schema

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

http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd

The jms schema

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

http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd

The tx (transaction) schema

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

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

The aop schema

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

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

The context schema

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

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

OK,總結結束,接着繼續,如今該辦的事情都辦啦,開始測試咱們的環境到底搭建得對不對:

測試類

個人applicationContext.xml是放在src目錄下面的

package com.cn.ljh.test;

import com.cn.ljh.dao.StudentDao;
import com.cn.ljh.domain.Student;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;

/**
 * Created by ljh on 16/8/17.
 */
public class SpringTest {

    
    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student)context.getBean("student");
        System.out.println(student.toString());
    }

    @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
       StudentDao studentDao = (StudentDao)context.getBean("studentDao");
        studentDao.addStudent(new Student());
    }

}

運行結果:

test1

test2

到這裏呢,spring的單獨搭建基本就完成了。


三、struts2

其實我是故意把struts2放到最後來講的,這貨簡直是太坑了,你造嗎,搭建的時候奶奶個熊的各類報錯,其實struts2 2.5.2變更仍是有點大的,對於第一次搭建仍是走了很多彎路的。

來時老規矩吧,先從jar開始介紹

1)、依賴jar包

```

    asm-3.3.jar
    asm-commons-3.3.jar
    asm-tree-3.3.jar
    commons-beanutils-1.9.2.jar
    commons-connections-3.2.2.jar  (能夠去)集合和數據結構的加強包
    commons-digester-2.1.jar
    commons-fileupload-1.3.2.jar
    commons-io-2.4.jar
    commons-lang3-3.4.jar
    commons-logging-1.1.3.jar
    freemarker-2.3.23.jar
    javassist-3.20.0-GA.jar (這裏hibernate也有,不用管)
    //這個不用json也能夠去
    json-lib-2.3-jdk15.jar          (能夠去)
    log4j-api-2.5.jar
    //注意啦:這個jar很重要哦,可是struts2中沒有,須要外部導入,而且版本不能比上面的api版本高
    log4j-core-2.3.jar
    ognl-3.1.10.jar
    slf4j-api-1.7.12.jar
    //這個是有關注解的
    struts2-convention-plugin-2.5.2.jar(使用註解配置action)
    struts2-core-2.5.2.jar
    //若是不適用json能夠直接去掉就能夠
    struts2-json-plugin-2.5.2.jar     (能夠去)

```

看到什麼不一樣沒有,和以前的版本有什麼不同,其實也是大同小異的,可是xwork那個jar沒了,這個仍是有點印象的。

下面就開始被坑的道路吧,哦,struts2中的這些jar不講解啦,其實和以前版本的都差很少,可是這個版本廢棄了一些api。


2)、配置

首先是web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

注意:重點來啦,版本改變以後,我說的中央過濾器類變啦,變成org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter,原來的類直接被廢棄咯。

其次,struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
    <!--設置開發者模式-->
    <constant name="struts.devMode" value="true"/>
    <!--設置主題-->
    <constant name="struts.ui.theme" value="simple"/>
    <!--設置請求方式爲.dao-->
    <constant name="struts.action.extension" value="dao"/>
    
    <package name="default" namespace="/" extends="struts-default">

    </package>

</struts>

簡單的配置下

接下來,上面的配置基本就完成啦,你能夠啓動你的tomcat去測試你的環境是否正確,tomcat的配置我就不列出來啦,不會的能夠去參考其餘文章。建立一個index.jsp做爲測試頁面,而後啓動,沒有報錯就說明你成功啦。其實很簡單,只是由於是新版本,改動仍是有的。若是看到測試頁面就說明你成功啦

個人通過無數次的折騰成功啦,我相信你也許也會遇到一些或多或少的問題,可是也要面對去解決。

那麼接下來就是框架整合啦,首先你必須可以讓上面的這些都能單獨的跑起來,本身必定要一步一步的測試過來,爲了讓後面你能安安靜靜的作一個美男子


四、spring和hibernate整合

框架整合篇呢,重頭戲纔剛剛開始,上面的問題呢,仍是須要你親自動手的,至少要知道每一個框架是能夠獨立運行的,這樣也方便之後面對其餘框架上的整合。
三大框架的整合,其實就是兩兩配對,spring+hibernate、spring+struts2,先整合那個徹底取決於你的心情。

好啦,不瞎扯淡啦,開始吧。

1)、依賴jar包

以來的jar呢其實基本就是上面的spring+hibernate的jar,可是爲了更加明確,我仍是列出來吧:

hibernate-release-4.2.21.Final/lib/required/  下面全部的jar
        antlr-2.7.7.jar
        dom4j-1.6.1.jar
        hibernate-commons-annotations-4.0.2.Final.jar
        hibernate-core-4.2.21.Final.jar
        hibernate-jpa-2.0-api-1.0.1.Final.jar
        javassist-3.18.1-GA.jar
        jboss-logging-3.1.0.GA.jar      
        jboss-transaction-api_1.1_spec-1.0.1.Final.jar
        
        
        //用於支持aop面向切面編程
        spring-aop-4.0.0.RELEASE.jar
        //提供對AspectJ的支持,以即可以方便的將面向方面的功能集成進IDE中
        spring-aspects-4.0.0.RELEASE.jar
        //這個jar 文件是全部應用都要用到的,它包含訪問配置文件、建立和管理bean 以及進行Inversion of Control / Dependency Injection(IoC/DI)操做相關的全部類。若是應用只需基本的IoC/DI 支持,引入spring-core.jar 及spring-beans.jar 文件就能夠了。
外部依賴spring-core,(CGLIB)。
        spring-beans-4.0.0.RELEASE.jar
        //這個看名字也該知道吧,build src
        spring-build-src-4.0.0.RELEASE.jar
        //下面兩個Spring-context的擴展支持,用於MVC方面
        spring-context-4.0.0.RELEASE.jar
        spring-context-support-4.0.0.RELEASE.jar
        //這個就不用說了spring的核心jar
        spring-core-4.0.0.RELEASE.jar
        //這個看名字也知道,Spring表達式語言
        spring-expression-4.0.0.RELEASE.jar
        //這個是後來隨着spring發展纔出現的,解決spring多依賴問題,能夠去搜索spring bom
        spring-framework-bom-4.0.0.RELEASE.jar
        //spring4.0對服務器的代理接口
        spring-instrument-4.0.0.RELEASE.jar
        //spring4.0對tomcat的集成
        spring-instrument-tomcat-4.0.0.RELEASE.jar
        //對jdbc簡單的封裝
        spring-jdbc-4.0.0.RELEASE.jar
        //爲了簡化jms API簡單的封裝
        spring-jms-4.0.0.RELEASE.jar
        //這個是國際化的支持
        spring-messaging-4.0.0.RELEASE.jar
        //爲了整合第三方框架,如hibernate等
        spring-orm-4.0.0.RELEASE.jar
        //spring對object/xml的映射支持
        spring-oxm-4.0.0.RELEASE.jar
        //對Junit等測試框架的簡單封裝
        spring-test-4.0.0.RELEASE.jar
        //這個是有關事務管理的
        spring-tx-4.0.0.RELEASE.jar
        //下面這三個不就是和web mvc有關的嗎
        spring-web-4.0.0.RELEASE.jar
        spring-webmvc-4.0.0.RELEASE.jar
        spring-webmvc-portlet-4.0.0.RELEASE.jar
        //這個是spring和websocket有關的
        spring-websocket-4.0.0.RELEASE.jar
        
        
        //注意這個jar,我後面會詳細講
        aopalliance-.jar
        
        //千萬不要忘了把數據庫驅動加進來
        mysql-connector-java-5.1.18-bin.jar

上面就是spring+hibernate須要的jar

2)、配置

2.1 hibernate配置

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.username">root</property>
        <property name="connection.password">123</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/sshDemo1</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

        <!--方言-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>


<!--這裏的測試類我就先加進來啦-->
        <mapping resource="com/cn/ljh/domain/Student_bean.xml"/>
        <mapping resource="com/cn/ljh/domain/Course_bean.xml"/>
        <mapping resource="com/cn/ljh/domain/User_hbm.xml"/>
    </session-factory>
</hibernate-configuration>

上面的mapping你會發現有Student_bean.xml Course_bean.xml User_hbm.xml 其實名字是不影響的,bean和hbm都是不影響的,可是通常仍是用hbm規範些,那麼我這裏就用User來測試hibernate是否搭建成功。

首先,建立一個數據庫,建立數據庫以前必定要把全部的編碼都設置爲UTF-8,一面忘記發生亂碼問題:

create database sshdemo;

編碼的問題就本身解決吧,這裏再也不贅述。

接下來建立User類,而且建立映射文件User_hbm.xml

User

package com.cn.ljh.domain;

/**
 * Created by ljh on 16/8/22.
 */
public class User {
    private Long id;

    public Long getId() {
        return id;
    }

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

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>
    <class name="com.cn.ljh.domain.User" table="oa_test_user">
        <id name="id" type="java.lang.Long" length="10">
            <generator class="native"/>
        </id>
    </class>

</hibernate-mapping>

建立一個util類用於測試

package com.cn.ljh.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Created by ljh on 16/8/17.
 */
public class HibernateUtils {

    public static  SessionFactory sessionFactory;

    static {
        Configuration configuration = new Configuration();
        configuration.configure();
        sessionFactory = configuration.buildSessionFactory();
    }
}

ok,就用上面這個簡單的實例來測試hibernate是否搭建成功,仍是老規矩建立JunitTest測試類:

package com.cn.ljh.test;

import com.cn.ljh.utils.HibernateUtils;
import org.hibernate.cfg.Configuration;
import org.testng.annotations.Test;

/**
 * Created by ljh on 16/8/17.
 */
public class hibernateUtilsTest extends HibernateUtils{

    @Test
    public void test1(){
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        configuration.buildSessionFactory();
    }

}

點擊運行吧,看建立表成功沒有,個人結果成功啦:

那麼就沒有問題咯,接下來就是spring

2.2 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:tx="http://www.springframework.org/schema/tx"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="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-4.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-4.0.xsd
           ">


<!--自動掃描與裝配bean-->
<context:component-scan base-package="com.cn.ljh"/>


<!--加載jdbc配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置數據源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="${jdbcUrl}"/>
    <property name="driverClass" value="${driverClass}"/>
    <property name="user" value="${username}"/>
    <property name="password" value="${password}"/>

    <!--初始化時建立三個連接-->
    <property name="initialPoolSize" value="3"/>
    <!--最大連接數量10,默認15-->
    <property name="maxPoolSize" value="10"/>
    <!--最小連接數量3,默認3-->
    <property name="minPoolSize" value="3"/>
    <!--當池中連接數量用完後,一次建立10個連接,默認爲3-->
    <property name="acquireIncrement" value="10"/>
    <!--當maxStatements和maxStatementsPerConnection都爲0是,則緩存被關閉,默認爲0-->
    <property name="maxStatements" value="8"/>
    <property name="maxStatementsPerConnection" value="8"/>
    <!--1000秒沒有使用連接則被丟失-->
    <property name="maxIdleTime" value="1000"/>
</bean>

<!--配置spring管理事務-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>

<!--配置申明事務管理(使用註解的方式)-->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>


<!--事務aop配置,這裏先註釋啦,若是你不知道是什麼能夠去搜怎麼配置,這裏咱們暫時不用配-->
<!--<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">-->
    <!--<property name="dataSource" ref="dataSource" />-->
<!--</bean>-->
<!--<tx:advice id="txAdvice" transaction-manager="txManager">-->
    <!--<tx:attributes>-->
        <!--<tx:method name="save*" propagation="REQUIRED"/>-->
        <!--<tx:method name="add*" propagation="REQUIRED"/>-->
        <!--<tx:method name="create*" propagation="REQUIRED"/>-->
        <!--<tx:method name="insert*" propagation="REQUIRED"/>-->
        <!--<tx:method name="*" read-only="true" />-->
    <!--</tx:attributes>-->
<!--</tx:advice>-->

<!--<aop:config proxy-target-class="true">-->
    <!--<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.cn.ljh.dao ..*.*(..))" />-->
<!--</aop:config>-->




<!--採用註解管理事務-->
<tx:annotation-driven transaction-manager="transactionManager"/>

<!--<bean name="student" class="com.cn.ljh.domain.Student">-->
    <!--<property name="name" value="小紅"/>-->
    <!--<property name="age" value="12"/>-->
    <!--<property name="sex" value="男"/>-->
<!--</bean>-->

<!--<bean name="studentDao" class="com.cn.ljh.dao.impl.StudentDaoImpl"/>-->
</beans>

```

jdbc.propertise

jdbcUrl     = jdbc:mysql://localhost:3306/sshDemo1
driverClass = com.mysql.jdbc.Driver
username    = root
password    = 123

這個配置是爲了使applicationContext.xml中可以找到相應的配置


如今來說講我遇到的配置問題:

<context:component-scan base-package="com.cn.ljh"/>
這個配置的意思就是,你須要那個基包的內容被spring容器自動掃描管理,多個基包,用逗號隔開。
什麼是被spring容器自動掃描管理?
通俗的講,就是在這個基包下面所能又被建立對象實例的類都會被spring容器管理,不須要在applicationContext.xml中配置bean,這裏使用的是註解的形式將類注入到spring中。
註解也是一個重點(簡單說幾個):
@Service 有關service層的類注入
@Controller 有關servlet控制器層的類注入
@Repository 有關持久化層的注入
@Component 其餘的一些組件類注入

註解是一個重要內容,這裏就不展開,初次介紹簡單的一些註解,想要深刻能夠去參考其餘博客

注意:上面這四個註解,其實你用哪個都是能夠的,只是爲了給程序員區分,有一個分層的概念,以後查找代碼,看到註解也能知道這個類屬於那一層的。

經過上面這四個註解註釋而且在applicationContext.xml中配置了component-scan,那麼你就能夠取出對象啦,例如:

創建一個測試dao 和daoimpl

package com.cn.ljh.dao.impl;

import com.cn.ljh.dao.StudentDao;
import com.cn.ljh.domain.Student;
import org.springframework.stereotype.Service;

/**
 * Created by ljh on 16/8/17.
 */
 //注意這裏使用的註解(和持久化相關,方便閱讀和管理)
@Repository
public class StudentDaoImpl implements StudentDao {
    @Override
    public void addStudent(Student student) {
        System.out.println("addStudent");
    }

    @Override
    public void delStudent(Long pid) {
        System.out.println("delStudent");
    }

    @Override
    public void updateStudent(Student student) {
        System.out.println("udateStudent");
    }
}
package com.cn.ljh.dao;

import com.cn.ljh.domain.Student;

/**
 * Created by ljh on 16/8/17.
 */
public interface StudentDao {

    public void addStudent(Student student);

    public void delStudent(Long pid);

    public void updateStudent(Student student);


}

建立測試類

package com.cn.ljh.test;

import com.cn.ljh.dao.StudentDao;
import com.cn.ljh.dao.impl.StudentDaoImpl;
import com.cn.ljh.domain.Student;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;

/**
 * Created by ljh on 16/8/17.
 */
public class SpringTest {

//    private ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //這裏獲取實體對象,bean的id是類名(類名第一個單詞小寫)
       StudentDao studentDao = (StudentDao)context.getBean("studentDaoImpl");
        studentDao.addStudent(new Student());
    }
   
    
}

測試以後可以獲得StudentDaoImpl對象就說明配置正確,你也能夠toString();

這裏在測試的時候須要將<tx:annotation-driven transaction-manager="transactionManager"/>註釋掉,單獨測試看效果。

個人測試結果:


<tx:annotation-driven transaction-manager="transactionManager"/>

上面這個配置是經過註解來管理事務的,很關鍵的哦,先不去介紹怎麼用,先給你們看一個錯誤:(這也是我在配置的時候遇到的錯誤)

org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [applicationContext.xml]; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

這個錯誤我估計會有不少人會遇到,在第一次配置的時候,看上面我講的有一個很重要的jar,這裏就是由於jar沒有導入齊全形成的 aopalliance-.jar,這個是第三方的,因此還要去下載,不少人也會忽略這一步。

關於這個錯誤的一些說法:

http://stackoverflow.com/questions/22282107/noclassdeffounderror-org-aopalliance-intercept-methodinterceptor

如今,開始測試hibernate和spring是否成功(假設如今是service層的代碼):

建立一個TestService

package com.cn.ljh.test;

import com.cn.ljh.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by ljh on 16/8/22.
 */
@Service    //service層管理
public class TestService {

    //經過註解獲取SessionFactory
    @Resource
    private SessionFactory sessionFactory;
    //經過註解給方法使用事務
    @Transactional
    public void saveUser(){


        Session session = sessionFactory.getCurrentSession();

        session.save(new User());

//        int i = 1/0;  //這裏拋出異常

        session.save(new User());
        System.out.println(session);
    }
}

這裏就稍微講解這兩個註解的做用:

@Resource :這個註解能夠放在字段上,這個時候至關於給這個字段添加了setting,那麼經過這個字段的名字去spring容器中獲取bean的id爲字段名字的bean經過依賴注入對象中,一樣也能夠在setting方法上面使用,做用恰好相反。
@Transactional:這個就是給方法添加事務管理的,能夠在類上面使用。

若是想更加深刻的去理解,歡迎去搜索新的知識點的博客和文檔

建立測試類:

package com.cn.ljh.test;

import com.cn.ljh.dao.StudentDao;
import com.cn.ljh.dao.impl.StudentDaoImpl;
import com.cn.ljh.domain.Student;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;

/**
 * Created by ljh on 16/8/17.
 */
public class SpringTest {


    /**
     * 測試SessionFactory
     */
    @Test
    public void test3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
        System.out.println(sessionFactory.openSession());
    }

     /**
     * 測試事務
     */
    @Test
    public void test4(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        TestService testService = (TestService)context.getBean("testService");
        testService.saveUser();
   }
   
    
}

首先測試是否能獲取SessionFactory,測試完成後測試事務,將TestService中的異常代碼註釋測試一次,添加成功,將註釋代碼解開再進行測試,發現數據庫表中沒有數據,說明咱們的事務是配置正確的,如圖是個人測試:

將異常信息註釋的測試

將異常代碼註釋解開的測試

上面數據庫中是從9開始的,由於以前我已經走了不少次,因此我刪除了數據,可是數據庫native仍是從9開始。這樣就說明配置成功啦。

這裏spring和hibernate配置就基本完成。


五、struts2與spring整合

1)、依賴 jar包

這裏的依賴jar包基本就是struts中的jar,可是要添加struts2的spring插件的jar

asm-3.3.jar
        asm-commons-3.3.jar
        asm-tree-3.3.jar
        commons-beanutils-1.9.2.jar
        commons-connections-3.2.2.jar  (能夠去)集合和數據結構的加強包
        commons-digester-2.1.jar
        commons-fileupload-1.3.2.jar
        commons-io-2.4.jar
        commons-lang3-3.4.jar
        commons-logging-1.1.3.jar
        freemarker-2.3.23.jar
        javassist-3.20.0-GA.jar (這裏hibernate也有,不用管)
        //這個不用json也能夠去
        json-lib-2.3-jdk15.jar          (能夠去)
        log4j-api-2.5.jar
        //注意啦:這個jar很重要哦,可是struts2中沒有,須要外部導入,而且版本不能比上面的api版本高
        log4j-core-2.3.jar
        ognl-3.1.10.jar
        slf4j-api-1.7.12.jar
        //這個是有關注解的
        struts2-convention-plugin-2.5.2.jar(使用註解配置action)
        struts2-core-2.5.2.jar
        //若是不適用json能夠直接去掉就能夠
        struts2-json-plugin-2.5.2.jar     (能夠去)
        
        //添加struts2的spring插件jar
        struts2-spring-plugin-2.5.2.jar

3)、整合

整合以前你要先測試你的struts2框架單獨在訪問的時候有沒有問題,能不能經過action訪問到頁面,若是能成功再接着進行框架的整合,千萬要記得一步一步來,測試時必不可少的,否則真的所有弄好了以後,你會發現有你好受的。

若是你struts測試經過了,就開始接着整合啦,測試上面講的單獨單獨配置struts2的時候就已經講過啦:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">


    <!--配置spring監聽對象applicationContext-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>

    <!--配置struts2-->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

繼續使用以前建立的service

package com.cn.ljh.test;

import com.cn.ljh.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by ljh on 16/8/22.
 */


@Service    
public class TestService {


    @Resource
    private SessionFactory sessionFactory;


    @Transactional
    public void saveUser(){


        Session session = sessionFactory.getCurrentSession();

        session.save(new User());

        int i = 1/0;  //這裏拋出異常

        session.save(new User());
        System.out.println(session);
    }
}

接着就是建立一個action對象

package com.cn.ljh.action;

import com.cn.ljh.test.TestService;
import com.opensymphony.xwork2.ActionSupport;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * Created by ljh on 16/8/23.
 */
@Controller
public class UserAction extends ActionSupport implements Serializable{

    @Resource
    private TestService testService;



    @Override
    public String execute() throws Exception {
        System.out.println("測試-------action");
        testService.saveUser();
        return "success";
    }
}

接着就是struts.xml的配置啦,要注意和沒有整合的區別

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
    <!--設置開發者模式-->
    <constant name="struts.devMode" value="true"/>
    <!--設置主題-->
    <constant name="struts.ui.theme" value="simple"/>
    
    <constant name="struts.enable.DynamicMethodInvocation" value="true"/>

    <package name="aaa" namespace="" extends="struts-default">
        <!--當spring和struts整合後class就是name的名字(區別主要在這裏,class再也不是類的全路徑,
        你也能夠測試究竟是類名的首字母小寫仍是和
        name屬性相同,我沒有進行測試,可是這裏的前提是你一
        定要將插件jar添加進來才能被識別到)-->
        <action name="userAction" class="userAction" method="execute">
            <result name="success">/test.jsp</result>
        </action>
    </package>

</struts>

那麼若是到這裏基本就算是完成啦,開啓tomcat進行測試環境搭建是否成功,上面的TestService使用到的註解上面已經講過再也不解釋,測試須要將TestService類中的異常代碼註釋關閉和打開分別測試,主要是測試事務。

看個人兩次測試結果:

這是我數據庫中最新的記錄,接下來咱們進行兩側測試(我把以前測試的結果都刪除啦)

將TestService異常代碼註釋測試

TestService中的 int i= 1/0;註釋

訪問UserAction

測試結果

打開TestService異常代碼註釋測試

TestService中的 int i= 1/0;註釋解開

訪問UserAction,發現報錯

刷新數據庫,發現數據庫中結果沒變,到這裏說明咱們的事務是沒有什麼問題的。

最後上一張個人目錄結構

到這裏呢基本上是完啦,三大框架的整合並且仍是最新版的哦,接下來能夠好好的更加深刻的研究學習框架吧。。。。

但願對你有所幫助,後邊可能還會去寫關於使用maven搭建的方式,企業使用自動構建的比較多,可是對於學習仍是手動搭建學的知識要多寫,而且這裏使用的是註解的方式,不表明xml配置的方式不能使用,做爲一個合格的框架使用者務必兩種方式都要掌握,註解、xml都有好又很差。

加油吧騷年!!!!

記錄學習的每一步,記錄每一次的成長!!!!

相關文章
相關標籤/搜索