注:此文檔只說明簡單的框架集成,各個框架的高級特性未涉及,剛剛接觸框架的新人可能需要參考其他資料。
PS:本次練習所用jar包都能在此下載到:http://pan.baidu.com/s/1sjmgdYX
- 准備工作
開發環境:JDK 7u80、Eclipse 4.4 、Tomcat 7.0.63、MySQL 5.6
開發使用組件:Spring 3.2.14、Hibernate 3.6.10、common-logging 1.2、aopalliance.jar、aspectjweaver.jar、mysql-connector-java-5.1.35-bin.jar
在Eclipse下創建動態web項目Test,創建過程中注意勾選web.xml的選項,如果不勾選,項目創建之后需要手動創建web.xml,創建完成后將其部署到Tomcat中,項目結構應該如下(Package Explorer下,看個人習慣):
- 配置Spring
將以下JAR包復制到lib文件夾下,不要問為什么是這些,想知道為什么可以把其他任意一個刪掉看看啟動項目報什么錯。
在web.xml中配置Spring監聽器,代碼如下:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
創建applicationContext.xml,當前版本的Spring默認其位於WEB-INF下,不過大多數開發人員習慣還是將其放到src下,這里我們將其放在src下。之后向applicationContext.xml中添加bean相關聲明,具體如下
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> </beans>
web.xml中添加如下內容,用於自定義Spring配置文件的位置:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
新建測試實體類User,路徑暫定為com.test.entity,添加如下代碼:
package com.test.entity; public class User { private String id; private String username; private String password; public String getId() { return id; } public void setId(String id) { this.id = id; } 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; } }
applicationContext.xml中添加如下定義(此處測試完成之后可以刪除):
<bean id="user" class="com.test.entity.User">
<property name="username" value="test" />
</bean>
新建Test類,暫定路徑com.test.test,添加如下代碼:
package com.test.test; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.test.entity.User; public class Test{ @SuppressWarnings("resource") public static void main(String[] args) { FileSystemXmlApplicationContext ac = new FileSystemXmlApplicationContext("src\\applicationContext.xml"); User user = (User) ac.getBean("user"); System.out.println(user.getUsername()); } }
運行Test類查看結果,如果輸出test則表示spring框架運行正常。
- 配置SpringMVC
添加SpringMVC所需JAR包:spring-webmvc-3.2.14.RELEASE.jar,在web.xml中添加SpringMVC前端控制器相關配置,SpringMVC的配置文件默認servlet配置名-servlet.xml(例如此處應該為springmvc-servlet.xml),位於WEB-INF下,這里我們將spring的配置文件與springmvc配置文件合並,所以我們需要在配置DispatcherServlet時說明配置文件的位置,配置如下:
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
配置springmvc掃描器,用於掃描springmvc注解,此處需要用到context標簽, 所以需要添加context的文檔聲明,所有代碼如下:
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <context:component-scan base-package="com.test" /> <bean id="user" class="com.test.entity.User"> <property name="username" value="test" /> </bean> </beans>
配置視圖解析器,Controller層處理完請求之后會返回數據或者視圖,所以我們需要先添加視圖解析器,否則無法跳轉回前台頁面,代碼如下:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="suffix" value=".jsp"/> </bean>
- 測試SpringMVC
創建index.jsp,代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>test</title> </head> <body> <form action="${pageContext.request.contextPath }/user/test.do" method="post"> <label>用戶名:</label><input type="text" name="username" /><br> <label>密碼:</label><input type="password" name="password" /> <input type="submit" value="登錄"> </form> </body> </html>
創建return.jsp,代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>test</title> </head> <body> ${user.username }:${user.password } </body> </html>
創建UserController,暫定位於com.test.controller,用於接收前台請求,代碼如下:
package com.test.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.test.entity.User; import com.test.service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/test") public String test(User user,ModelMap model){ System.out.println(user.getUsername()); System.out.println(user.getPassword()); model.addAttribute(user); return "/return"; } }
啟動Tomcat后測試即可,正常情況下結果如下,說明框架已成功相應請求:
- 配置Hibernate集成
添加以下JAR包:
applicationContest.xml中添加Hibernate相關配置,hibernate的實體聲明可以選擇配置文件和注解兩種方式,我個人比較傾向於配置文件方式,如下圖所示:
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource"> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mappingLocations"> <value>classpath*:/com/test/entity/*.cfg.xml</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean>
由於Hibernate3必須在事務中處理數據訪問,所以需要添加事務控制,個人傾向於使用aop方式,所以需要先添加tx和aop的文檔配置,配置后文檔聲明部分代碼如下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
配置事務控制器,並通過aop將其織入到service切面進行事務控制,如下所示:
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes > <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.test.service.*.*(..))" id="aopPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="aopPointcut"/> </aop:config>
- 測試整體框架
Mysql中創建test_user表用於測試框架能否正常進行數據庫的操作,此處我們測試在事務管理中進行保存操作,建表語句如下:
create table test_user ( id varchar(36) primary key, username varchar(20) not null, password varchar(50) not null );
創建Hibernate實體映射文件,內容如下:
<?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.test.entity.User" table="test_user"> <id name="id" type="java.lang.String" length="36"> <column name="id" /> <generator class="uuid" /> </id> <property name="username" type="java.lang.String" length="10" > <column name="username" not-null="true" unique="true"/> </property> <property name="password" type="java.lang.String" length="32" > <column name="password" not-null="true" unique="true"/> </property> </class> </hibernate-mapping>
創建UserDAO,暫定位於com.test.dao下,用於處理數據庫操作,代碼如下:
package com.test.dao; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.test.entity.User; @Repository public class UserDAO { @Autowired private SessionFactory sessionFactory; public String save(User user){ return (String) sessionFactory.getCurrentSession().save(user); } }
創建UserService,暫定位於com.test.service下,用於提供請求服務,代碼如下:
package com.test.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.test.dao.UserDAO; import com.test.entity.User; @Service public class UserService { @Autowired private UserDAO userDAO; public String save(User user){ return userDAO.save(user); } }
修改UserController如下:
package com.test.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.test.entity.User; import com.test.service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/test") public String test(User user,ModelMap model){ userService.save(user); model.addAttribute(user); return "/return"; } }
至此項目內容應該如下圖所示:
重啟Tomcat后輸入用戶名和密碼,點擊按鈕后查看數據庫,正常結果為后台未報錯且數據庫有數據存入,如下圖所示:
接下來我們測試下在出現異常的情況下能否正常回滾事務,修改Service代碼如下:
package com.test.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.test.dao.UserDAO; import com.test.entity.User; @Service public class UserService { @Autowired private UserDAO userDAO; public String save(User user){ userDAO.save(user); throw new RuntimeException("測試事務能否正常回滾!"); } }
重啟Tomcat后測試框架能否正常回滾,正常情況下,后台會將自定義的異常拋出,而數據庫中未出現第二條數據,框架集成到此結束,之后便可進行基於框架的開發工作了。
PS:各位有什么問題或者不同看法可以留言