基於Maven的Spring + Spring MVC + Mybatis的環境搭建
基於Maven的Spring + Spring MVC + Mybatis的環境搭建專案開發,先將環境先搭建起來。上次做了一個Spring + Spring MVC + Mybatis + Log4J + JUnit Test的環境搭建,這次也差不多,不過就是基於了Maven,同時也添加了事務管理。
首先,可以去了解一下maven,個人覺得這個東西就是JAR包管理方便,不用自己一個個去寫,直接新增dependence就行了,不過有時候要注意喲,有可能重複的包含了某個JAR包,會報衝突的喲,親!因為只有一個POM檔案裡指定JAR包,所以整個專案都很小的,一般就幾MB,只有你在將該專案打成WAR包的時候,maven會自動的把三方JAR包放進專案,然後你就可以去部署到Tomcat的webapp下面了,放進去,重啟Tomcat就OK。
1.開始搭建我的環境吧。首先,IDE我用的是eclipse的JEE版本。要保證裝上了Maven喲,可以使用eclipse的Install New Software,
URL地址是http://m2eclipse.sonatype.org/sites/m2e/,
然後一步步走下去,安裝好了過了會重啟一次。給一個忠告喲,安裝好了maven後,不要使用IDE裡面的了,而是去官方下載一個,解壓,然後讓IDE的Maven指向你下載安裝的,如圖:
2.maven安裝成功了,我們用Maven建立一個新的WEB專案。File—> New—> Other—>Maven Project.
選預設,下一步。在Select an Archetype裡面種找到如下圖所示
3.然後next,輸入groupId:net.yuanmomo;artifactId:Test,然後finish,稍微等待一下,就建立好了。下面的是建立好了的一個初始的專案:
4.但是這個並不是預設的maven專案的標準結構.我們需要進行一些改動.
(1).在專案下建立一個Source Folder.
Folder Name:src/main/java
如下圖所示:
(當然,還可以新增用於junit測試的src/test/java和src/test/resources
不過在此就不添加了.)
(2).在src/main/java中建立3個包(maven標準推薦是3層包結構)
(3).如果裝的JDK是1.6的,更改JRE System Libary為1.6版本的.
(4).就src/main/webapp資料夾看做一個的WebRoot,然後建立js,css,jsp等資料夾。
這樣.一個標準的maven web專案建立成功.
5.大家一看上面的專案結構,很熟悉吧。maven的專案結構路徑有點討厭,有點讓人很煩。maven打WAR包的時候提取的東西是src/main/webapp下面的檔案,然後打成一個WAR的WEB專案就可以部署了,但是,但是,我們在開發的時候,在使用eclipse裡面的Tomcat除錯的時候,tomcat卻不是把src/main/webapp下面的檔案部署到伺服器。此時,如果你開啟Server,然後add and remove,你在左邊是找不到Test專案的,如下:
原因是因為Tomcat預設回去Test專案的路徑下面去找WebRoot—>WEB-INF–>web.xml(WebRoot資料夾的名字可以不一樣,可以使其它的,但是WEB-INF–>web.xml這兩個名字不能變),但是當前就找不到這幾個目錄。這個時候有兩個解決辦法:
(5.1). 在Test專案的路徑下面,按照路徑規則建立WebRoot,WEB-INF等資料夾,然後把上面的web.xml拷貝到新建的WEB-INF中去。放心吧,我上一個專案就是這樣做的,不過這種方式打死都不可取的。你修改JSP的時候改的是下面的,maven打包的時候用的上面的。你還得拷貝過來,拷過去,麻煩,如果再有svn管理,累死你,暈死你,我們經常是除錯編寫的時候再下面做,最後提交的時候還得一個個拷貝上去,還出很多問題。所以建議採用第二種方式。
(5.2).轉換該專案:
(1)在Test工程名上右鍵–>Properties–>Project Facets–>Convet to faceted form,
(2)勾上Dynamic Web Module,選擇2.4版本。同時點選下方的further configuration available
(3)將預設的WebContent改成src/main/webapp
(4)一路點OK..此時在server檢視中的tomcat server上點右鍵–>Add and Remove,就能看到該專案於,然後部署啦。
至此,我們已經建立好了一個合格的基於Maven的專案,也可以在Tomcat中部署。
接下來,我們開始整合我們的J2EE框架。
6.先給出資料庫的建立指令碼,方便測試搭建是否成功。
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
—
— 資料庫: `timesheet`
—
CREATE DATABASE `timesheet` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
USE `timesheet`;
— ——————————————————–
—
— 表的結構 `testtable`
—
CREATE TABLE IF NOT EXISTS `testtable` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`date` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;
7.在pom檔案中新增必要的jar包的dependence,可以從兩個地方查詢:
http://mvnrepository.com/
http://search.maven.org/
新增後的pom檔案如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.yuanmomo</groupId> <artifactId>Test</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Test Maven Webapp</name> <url>http://maven.apache.org</url> <!– 設定 Spring 的版本 –> <properties> <org.springframework.version>3.0.0.RELEASE</org.springframework.version> </properties> <dependencies> <!– 此處開始就是Spring 所有的jar了,spring3.0的jar包拆分了,所以很多 –> <!– Core utilities used by other modules. Define this if you use Spring Utility APIs (org.springframework.core.*/org.springframework.util.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Expression Language (depends on spring-core) Define this if you use Spring Expression APIs (org.springframework.expression.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Bean Factory and JavaBeans utilities (depends on spring-core) Define this if you use Spring Bean APIs (org.springframework.beans.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Aspect Oriented Programming (AOP) Framework (depends on spring-core, spring-beans) Define this if you use Spring AOP APIs (org.springframework.aop.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Application Context (depends on spring-core, spring-expression, spring-aop, spring-beans) This is the central artifact for Spring’s Dependency Injection Container and is generally always defined –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Various Application Context utilities, including EhCache, JavaMail, Quartz, and Freemarker integration Define this if you need any of these integrations –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Transaction Management Abstraction (depends on spring-core, spring-beans, spring-aop, spring-context) Define this if you use Spring Transactions or DAO Exception Hierarchy (org.springframework.transaction.*/org.springframework.dao.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework.version}</version> </dependency> <!– JDBC Data Access Library (depends on spring-core, spring-beans, spring-context, spring-tx) Define this if you use Spring’s JdbcTemplate API (org.springframework.jdbc.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA, and iBatis. (depends on spring-core, spring-beans, spring-context, spring-tx) Define this if you need ORM (org.springframework.orm.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Object-to-XML Mapping (OXM) abstraction and integration with JAXB, JiBX, Castor, XStream, and XML Beans. (depends on spring-core, spring-beans, spring-context) Define this if you need OXM (org.springframework.oxm.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Web application development utilities applicable to both Servlet and Portlet Environments (depends on spring-core, spring-beans, spring-context) Define this if you use Spring MVC, or wish to use Struts, JSF, or another web framework with Spring (org.springframework.web.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Spring MVC for Servlet Environments (depends on spring-core, spring-beans, spring-context, spring-web) Define this if you use Spring MVC with a Servlet Container such as Apache Tomcat (org.springframework.web.servlet.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Spring MVC for Portlet Environments (depends on spring-core, spring-beans, spring-context, spring-web) Define this if you use Spring MVC with a Portlet Container (org.springframework.web.portlet.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Support for testing Spring applications with tools such as JUnit and TestNG This artifact is generally always defined with a ‘test’ scope for the integration testing framework and unit testing stubs –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> <scope>test</scope> </dependency> <!– 上面的都是Spring的jar包,可以選擇性的新增 –> <!– Mybatis 開發包 –> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.1.1</version> </dependency> <!– Mybatis 和Spring的 整合包,是mybatis出的–> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.1.1</version> </dependency> <!– tomcat servlet開發包 –> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!– JSTL標籤庫 –> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <!– mysql的資料庫驅動包 –> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <!– 日誌列印 log4j包 –> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> <scope>runtime</scope> </dependency> <!– 下面兩個包 commons-dbcp,commons-pool 是配置資料來源的包–> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.4</version> </dependency> <!– 日誌記錄依賴包,很多都依賴此包,像log4j,json-lib等等 –> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> <version>1.1</version> </dependency> <!– Spring 檔案上傳的包 –> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <!– Spring 檔案上傳的依賴包 –> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <!– dom4j 解析 XML檔案的包 –> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!– 下面的三個包是在配置事務的時候用到的 spring的依賴包 –> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.0</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2.2</version> </dependency> <!– JSON lib 開發包 以及它的依賴包 –> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <classifier>jdk15</classifier> <version>2.4</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.3</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.5</version> </dependency> <!– junit 測試包 –> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>Test</finalName> </build> </project>
修改pom檔案後,儲存,maven會自動的去download這些jar包到本地。等待的時間可能會很長。上面我把所有我這次專案用到的包都羅列出來了,如果你用不到的,可以自行刪除。
下載完成過後,點開專案左側的Maven Dependencies,你就能看到很多的下載的JAR包了。
8. 修改web.xml,配置Spring,spring MVC,log4j,亂碼處理等。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <!– Spring context startup Spring的初始化–> <context-param> <param-name>contextConfigLocation</param-name> <param-value><!– Spring的配置檔案 –> classpath:/com/comverse/timesheet/config/ApplicationContext.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!– Spring character filter 處理亂碼–> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!– Configuration of Log4j log4j的配置 –> <context-param> <param-name>log4jConfigLocation</param-name> <param-value><!– log4j.properties檔案路徑 –> classpath:/com/comverse/timesheet/config/log4j.properties </param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener> <!– Spring MVC Configuration Spring MVC的配置–> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value><!– dispatcher-servlet.xml檔案路徑 –> classpath:/com/comverse/timesheet/config/dispatcher-servlet.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
修改後儲存該檔案。
9.新增 log4j.properties,jdbc.properties等配置檔案:
路徑位置:
各個配置檔案的內容如下:
(1). log4j.properties: log4j的配置
#配置了控制檯和文字記錄兩種方式 log4j.rootLogger=DEBUG,CONSOLE,FILEOUT log4j.addivity.org.apache=true# CONSOLE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.Threshold=DEBUG log4j.appender.CONSOLE.Target=System.out log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout #log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d – %c -%-4r [%t] %-5p %c %x – %m%n log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} \:%m%n# # FILEOUT log4j.appender.FILEOUT=org.apache.log4j.RollingFileAppender log4j.appender.FILEOUT.File=${catalina.home}\\file.log log4j.appender.fileout.MaxFileSize=100000KB # default is true,append to the file; if false, the replace the log file whenever restart system log4j.appender.FILEOUT.Append=true #RollingFileAppender沒有DatePattern這個屬性 log4j.appender.FILEOUT.layout=org.apache.log4j.PatternLayout #log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d – %c -%-4r [%t] %-5p %c %x – %m%n log4j.appender.FILEOUT.layout.ConversionPattern=[%-5p]_%d{yyyy-MM-dd HH:mm:ss} :%m%n
(2). jdbc.properties: 資料庫連線資訊的配置
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/timesheet user=root password=root
(3). ApplicationContext.xml: Spring的配置檔案
<?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" 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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!– jdbc.properties檔案路徑 –> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:/com/comverse/timesheet/config/jdbc.properties" /> </bean> <!– 資料來源的配置 –> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${user}" /> <property name="password" value="${password}" /> <!– data source configuration –> <property name="initialSize" value="60" /><!– initial connections –> <property name="maxActive" value="100" /><!– MAX connections –> <property name="maxIdle" value="50" /><!– MAX idle connections –> <property name="minIdle" value="10" /><!– MIN idle connections –> <!– 處理mysql 8小時自動斷開連線的問題 –> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="validationQuery" value="select 1" /> <property name="timeBetweenEvictionRunsMillis" value="20000" /> <property name="numTestsPerEvictionRun" value="100" /> </bean> <!–====事務相關控制==–> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="userTxAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="pc" expression="execution(* com.comverse.timesheet.web.business.*.*(..))" /> <!– 把事務控制在Business層 –> <aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" /> </aop:config> <!– MyBatis sqlSessionFactory 配置 mybatis–> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:/com/comverse/timesheet/mybatis/SqlMapConfig.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <!– business AND implementation beans 包含ImplAndBusinessBeans.xml檔案 –> <import resource="ImplAndBusinessBeans.xml" /> </beans>
(4). dispatcher-servlet: Spring MVC的配置檔案
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:annotation-config /> <!– 把標記了@Controller註解的類轉換為bean –> <context:component-scan base-package="com.comverse.timesheet.web.controller" /> <!– 啟動Spring MVC的註解功能,完成請求和註解POJO的對映 –> <bean class="org.springframework.web.servlet.mvc. annotation.AnnotationMethodHandlerAdapter" /> <!– 檢視 beans –> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> <!– Controller 跳轉的JSP頁面路徑 和 檔案的字尾 –> <!– 檔案上傳 –> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!– set the max upload size100MB –> <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize"> <value>1024000</value> </property> </bean> </beans>
(5). ImplAndBusinessBeans.xml: 這個檔案主要放置implementation 和 Business的 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" 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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!– 這兩個類的具體實現會在後面給出來–> <bean id="ITestTableDAOImpl" class="com.comverse.timesheet.web.impl.ITestTableDAOImpl"> <property name="session" ref="sqlSession" /> </bean> <bean id="TestBusiness" class="com.comverse.timesheet.web.business.TestBusiness"> <property name="testDAO" ref="ITestTableDAOImpl" /> </bean> </beans>
此時,幾個主要的配置檔案我們已經加進來了,只有mybatis還有幾個配置檔案沒有加進來。
10. 建立包,用於開發系統:
bean : 放pojo, java bean
business : 放業務層
conroller : 放控制層,主要負責接受請求和呼叫business,返回檢視結果
dao : 放每個bean對應的介面
impl : dal 介面的具體實現
interceptor: 過濾器
resource : 資源包,比如檔案路徑,配置檔案呀
test : 測試包
util : 工具包
web : 是裝樣子的喲,不是我這次要用的,是個空包。
10. 建立本次測試的java檔案
(1). bean : TestTable.java:
package com.comverse.timesheet.web.bean;import java.util.Date;public class TestTable { private int id; private String name; private Date birthday; //setter and getter …………….}
(2). dao : ITestTableDAO.java
package com.comverse.timesheet.web.dao;import com.comverse.timesheet.web.bean.TestTable;public interface ITestTableDAO { public boolean add(TestTable test) throws Exception; }
(3). impl : ITestTableDAOImpl:
package com.comverse.timesheet.web.impl;import com.comverse.timesheet.web.bean.TestTable; import com.comverse.timesheet.web.dao.ITestTableDAO; import com.comverse.timesheet.web.util.BasicSqlSupport;public class ITestTableDAOImpl extends BasicSqlSupport implements ITestTableDAO { @Override public boolean add(TestTable test) throws Exception { boolean flag=false; int count=this.session.insert("com.comverse.timesheet.web.mapper.Test.add",test); if(count>0){ flag=true; } return flag; } }
(4). business: TestBusiness.java
package com.comverse.timesheet.web.business;import java.util.Date;import javax.annotation.Resource;import org.springframework.transaction.annotation.Transactional;import com.comverse.timesheet.web.bean.TestTable; import com.comverse.timesheet.web.dao.ITestTableDAO;public class TestBusiness { private ITestTableDAO testDAO=null; public ITestTableDAO getTestDAO() { return testDAO; } public void setTestDAO(ITestTableDAO testDAO) { this.testDAO = testDAO; } public void add() throws Exception{ TestTable test=new TestTable(); test.setName("yuanmomo6"); test.setBirthday(new Date()); try { testDAO.add(test); } catch (Exception e) { // TODO Auto-generated catch block throw e; } } }
(5). Controller : ResultController
package com.comverse.timesheet.web.controller;import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping;import com.comverse.timesheet.web.business.TestBusiness;@Controller @RequestMapping("/result.do") public class ResultController { //將spring 配置檔案中的bean 通過setter注入進來 @Resource(name="TestBusiness") private TestBusiness testBusiness=null; public void setTestBusiness(TestBusiness testBusiness) { this.testBusiness = testBusiness; } @RequestMapping public String viewUser(HttpServletRequest request, ModelMap modelMap) throws Exception { System.out.println("$$$$$$$$$$$$$$$$$$$$$you want to check the result.jsp+++++++++++++"); System.out.println("$$$$$$$$$$$$$$$$$$$$$ ready to insert +++++++++++++"); testBusiness.add(); System.out.println("$$$$$$$$$$$$$$$$$$$$$ insert completed +++++++++++++"); return "result"; } }
(6). util : BasicSqlSupport.java所有的implementation類都會繼承這個類,在ImplAndBusinessBeans.xml檔案中註冊的bean,都會注入一個sqlsession。例如上面的implementation就是繼承了這個類。
package com.comverse.timesheet.web.util;import org.apache.ibatis.session.SqlSession;public class BasicSqlSupport{ protected SqlSession session; public SqlSession getSession() { return session; } public void setSession(SqlSession session) { this.session = session; } }
加入mybatis的配置檔案:
(1). 為 TestTable bean 建立mapper檔案,路徑為com/comverse/timesheet/mybatis/mapper/Test.xml:
Test.xml<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
(1). 加入Mybatis的配置檔案:在上面的ApplicationContext.xml檔案中我們已經包含了SqlMapConfig.xml檔案。在/com/comverse/timesheet/mybatis/下建立
SqlMapConfig.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <configuration> <typeAliases> <!– Entities 引數實體 –> <!– com.comverse.timesheet.web.bean 包中的 所有Bean, 取個別名 –> <!– 比如TestTable類就用Test來表示–> <typeAlias type="com.comverse.timesheet.web.bean.TestTable" alias="Test" /> </typeAliases> <mappers> <!– 對應Bean類的xml配置檔案的路徑資訊 –> <mapper resource="com/comverse/timesheet/mybatis/mapper/Test.xml" /> </mappers> </configuration>
- 框架的整合完成,專案的目錄結構如下:
- 編寫一個測試頁面,這個頁面的路徑在dispatcher-servlet.xml中已經確定—/WEB-INF/jsp/:
檔名在controller中已經定義–result, 字尾是 .jsp, 所以就是 result.jsp。
(1). result.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=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1> 你插入資料成功了!!!</h1> </body> </html>
14.至此,我們的專案完成了,部署。
部署之前檢查一下problem框,看有沒有問題。這次我突然遇到一個問題,我上個星期五的時候都沒有遇到,今天就奇了怪了。不過沒事,問題來就想辦法解決它。
(1).在problem處發現這個問題
Description:
Classpath entry org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER will not be exported or published. Runtime ClassNotFoundExceptions may result. 如果部署了專案,啟動,會報找不到類異常。
(2).問題的原因參考 Loose classpath web libraries support
在專案上右鍵–>properties—>deployment Assembly–>add,選擇 java build path entries,然後選中Maven dependencies–>finish–>OK,就能解決問題啦。
- 一點小插曲過後,我們再次的部署專案,重新啟動,看日誌,專案成功的啟動起來啦。
開啟瀏覽器:訪問 http://localhost:8080/Test/,看到HelloWord
先檢視資料的資訊,沒有資料,返回0行。
接著訪問,http://localhost:8080/Test/result.do 看到結果了,高興哇!!再看資料庫
資料插入成功,至此,我們的專案搭建完整的完成了!!!如有錯別字,請原諒,因為打字太痛苦啦!!謝謝大家!!
檢查一下我們的日誌資訊:
[DEBUG] 2012-08-13 18:10:34 :DispatcherServlet with name ‘dispatcher’ determining Last-Modified value for [/Test/result.do] [DEBUG] 2012-08-13 18:10:34 :Mapping [/result.do] to handler ‘[email protected]’ [DEBUG] 2012-08-13 18:10:34 :Last-Modified value for [/Test/result.do] is: -1 [DEBUG] 2012-08-13 18:10:34 :DispatcherServlet with name ‘dispatcher’ processing GET request for [/Test/result.do] [DEBUG] 2012-08-13 18:10:34 :Invoking request handler method: public java.lang.String com.comverse.timesheet.web.controller.ResultController.viewUser(javax.servlet.http.HttpServletRequest,org.springframework.ui.ModelMap) throws java.lang.Exception $$$$$$$$$$$$$$$$$$$$$you want to check the result.jsp+++++++++++++ $$$$$$$$$$$$$$$$$$$$$ ready to insert +++++++++++++ [DEBUG] 2012-08-13 18:10:34 :Creating new transaction with name [com.comverse.timesheet.web.business.TestBusiness.add]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-java.lang.Exception [DEBUG] 2012-08-13 18:10:34 :Acquired Connection [jdbc:mysql://localhost:3306/timesheet, [email protected], MySQL-AB JDBC Driver] for JDBC transaction [DEBUG] 2012-08-13 18:10:34 :Switching JDBC Connection [jdbc:mysql://localhost:3306/timesheet, [email protected], MySQL-AB JDBC Driver] to manual commit [DEBUG] 2012-08-13 18:10:34 :Creating a new SqlSession [DEBUG] 2012-08-13 18:10:34 :Registering transaction synchronization for SqlSession [[email protected]] [DEBUG] 2012-08-13 18:10:34 :JDBC Connection [jdbc:mysql://localhost:3306/timesheet, [email protected], MySQL-AB JDBC Driver] will be managed by Spring [DEBUG] 2012-08-13 18:10:34 :ooo Using Connection [jdbc:mysql://localhost:3306/timesheet, [email protected], MySQL-AB JDBC Driver] [DEBUG] 2012-08-13 18:10:34 :==> Preparing: INSERT INTO testtable (NAME,DATE) VALUES(?,?) [DEBUG] 2012-08-13 18:10:34 :==> Parameters: yuanmomo6(String), 2012-08-13 18:10:34.122(Timestamp) [DEBUG] 2012-08-13 18:10:34 :Releasing transactional SqlSession [[email protected]] [DEBUG] 2012-08-13 18:10:34 :Initiating transaction commit [DEBUG] 2012-08-13 18:10:34 :Committing JDBC transaction on Connection [jdbc:mysql://localhost:3306/timesheet, [email protected], MySQL-AB JDBC Driver] [DEBUG] 2012-08-13 18:10:34 :Transaction synchronization committing SqlSession [[email protected]] [DEBUG] 2012-08-13 18:10:34 :Transaction synchronization closing SqlSession [[email protected]] [DEBUG] 2012-08-13 18:10:34 :Releasing JDBC Connection [jdbc:mysql://localhost:3306/timesheet, [email protected], MySQL-AB JDBC Driver] after transaction [DEBUG] 2012-08-13 18:10:34 :Returning JDBC Connection to DataSource $$$$$$$$$$$$$$$$$$$$$ insert completed +++++++++++++ [DEBUG] 2012-08-13 18:10:34 :Invoking afterPropertiesSet() on bean with name ‘result’ [DEBUG] 2012-08-13 18:10:34 :Rendering view [org.springframework.web.servlet.view.JstlView: name ‘result’; URL [/WEB-INF/jsp/result.jsp]] in DispatcherServlet with name ‘dispatcher’ [DEBUG] 2012-08-13 18:10:34 :Forwarding to resource [/WEB-INF/jsp/result.jsp] in InternalResourceView ‘result’ [DEBUG] 2012-08-13 18:10:34 :Successfully completed request [DEBUG] 2012-08-13 18:10:34 :Returning cached instance of singleton bean ‘sqlSessionFactory’
可以看出我們的事務也新增成功。
Spring MVC的流程:
request–>controller–>business–>implementation–>mysql
GitHub專案地址:暫無