最新版ssh hibernate spring struts2環境搭建
最新版spring Framework下載地址:spring4.0.0RELEASE環境搭建
http://repo.spring.io/release/org/springframework/spring/4.0.0.RELEASE/
最新版hibernate下載地址:hibernate4.2.21
https://sourceforge.net/projects/hibernate/postdownload?source=dlp
最新版struts2下載地址:struts2 2.5.2
https://struts.apache.org/
上面的版本就是本次搭建環境所用到的版本,如果為了學習使用的可以通過鏈接下載。因為現在ssh框架跟新,然而網絡上最新版的ssh環境搭建的教程還沒有,雖然版本變換都差不多,但是還是簡單的介紹下,記錄自己學習的過程,也作為一種分享。
簡單介紹本次教程(適合簡單入門):
使用的開發環境是intelliJ Idea
先介紹單個的搭建案例,並且給出小型的Demo
然后再整合框架,例子的話就是簡單的測試Demo
在看教程之前,我想您需要了解hibernate
Spring
struts2
都是干什么的,有什么作用,至少要知道定義吧,現在這篇教程只是講解手動的去搭建環境,沒有使用maven等等項目構建工具,之后會寫試用項目構架工具構建項目。
1、hibernate
簡單說說hibernate,hibernate是一個基於JDBC的封裝框架,解決的問題自然就是數據的增刪改查所謂的持久化操作,讓JDBC操作變得更加面向對象,一切的操作都可以面向對象化。
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那簡直就更好了
這里我就不去過多的簡紹,每一個jar有什么作用,但是會在spring的時候回去講,因為這里的jar都比較簡單,沒有很多,相信只要知道一點單詞就能知道jar是什么意思了吧。
好了,如果你是用的是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了。
2、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的單獨搭建基本就完成了。
3、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作為測試頁面,然后啟動,沒有報錯就說明你成功啦。其實很簡單,只是因為是新版本,改動還是有的。如果看到測試頁面就說明你成功啦
我的經過無數次的折騰成功啦,我相信你也許也會遇到一些或多或少的問題,但是也要面對去解決。
那么接下來就是框架整合啦,首先你必須能夠讓上面的這些都能單獨的跑起來,自己一定要一步一步的測試過來,為了讓后面你能安安靜靜的做一個美男子
4、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
,這個是第三方的,所以還要去下載,很多人也會忽略這一步。
關於這個錯誤的一些說法:
現在,開始測試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配置就基本完成。
5、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都有好又不好。
加油吧騷年!!!!
記錄學習的每一步,記錄每一次的成長!!!!