基於Maven的Spring + Spring MVC + Mybatis的環境搭建

基於Maven的Spring + Spring MVC + Mybatis的環境搭建項目開發,先將環境先搭建起來。上次作了一個Spring + Spring MVC + Mybatis + Log4J + JUnit Test的環境搭建,此次也差很少,不過就是基於了Maven,同時也添加了事務管理。css

首先,能夠去了解一下maven,我的以爲這個東西就是JAR包管理方便,不用本身一個個去寫,直接添加dependence就好了,不過有時候要注意喲,有可能重複的包含了某個JAR包,會報衝突的喲,親!由於只有一個POM文件裏指定JAR包,因此整個項目都很小的,通常就幾MB,只有你在將該項目打成WAR包的時候,maven會自動的把三方JAR包放進項目,而後你就能夠去部署到Tomcat的webapp下面了,放進去,重啓Tomcat就OK。html

1.開始搭建個人環境吧。首先,IDE我用的是eclipse的JEE版本。要保證裝上了Maven喲,可使用eclipse的Install New Software, URL地址是http://m2eclipse.sonatype.org/sites/m2e/, 而後一步步走下去,安裝好了過了會重啓一次。給一個忠告喲,安裝好了maven後,不要使用IDE裏面的了,而是去官方下載一個,解壓,而後讓IDE的Maven指向你下載安裝的,如圖: java

在這裏插入圖片描述
2.maven安裝成功了,咱們用Maven建立一個新的WEB項目。File—> New—> Other—>Maven Project. 選默認,下一步。在Select an Archetype裏面種找到以下圖所示
在這裏插入圖片描述

3.而後next,輸入groupId:net.yuanmomo;artifactId:Test,而後finish,稍微等待一下,就建立好了。下面的是建立好了的一個初始的項目: node

在這裏插入圖片描述

4.可是這個並非默認的maven項目的標準結構.咱們須要進行一些改動. (1).在項目下建立一個Source Folder. Folder Name:src/main/java 以下圖所示: mysql

在這裏插入圖片描述
(固然,還能夠添加用於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項目的,以下: git

在這裏插入圖片描述
緣由是由於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, github

在這裏插入圖片描述
(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,能夠從兩個地方查詢:

mvnrepository.com/ search.maven.org/ 添加後的pom文件以下:web

<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包了。 spring

在這裏插入圖片描述

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>
複製代碼

修改後保存該文件。sql

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;     } }
複製代碼
  1. 加入mybatis的配置文件: (1). 爲 TestTable bean 建立mapper文件,路徑爲com/comverse/timesheet/mybatis/mapper/Test.xml: Test.xml

    INSERT INTO testtable (NAME,DATE) VALUES(#{name},#{birthday})

(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>
複製代碼
  1. 框架的整合完成,項目的目錄結構以下:
    在這裏插入圖片描述
  2. 編寫一個測試頁面,這個頁面的路徑在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,就能解決問題啦。

在這裏插入圖片描述

在這裏插入圖片描述
在這裏插入圖片描述
14. 一點小插曲事後,咱們再次的部署項目,從新啓動,看日誌,項目成功的啓動起來啦。
在這裏插入圖片描述
打開瀏覽器:訪問 http://localhost:8080/Test/,看到HelloWord
在這裏插入圖片描述
先查看數據的信息,沒有數據,返回0行。
在這裏插入圖片描述

接着訪問,http://localhost:8080/Test/result.do 看到結果了,高興哇!!再看數據庫

在這裏插入圖片描述

數據插入成功,至此,咱們的項目搭建完整的完成了!!!若有錯別字,請原諒,由於打字太痛苦啦!!謝謝你們!!

  1. 檢查一下咱們的日誌信息:

    [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 ‘com.comverse.timesheet.web.controller.ResultController@7056d5’ [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, UserName=root@localhost, MySQL-AB JDBC Driver] for JDBC transaction [DEBUG] 2012-08-13 18:10:34 :Switching JDBC Connection [jdbc:mysql://localhost:3306/timesheet, UserName=root@localhost, 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 [org.apache.ibatis.session.defaults.DefaultSqlSession@177e6b4] [DEBUG] 2012-08-13 18:10:34 :JDBC Connection [jdbc:mysql://localhost:3306/timesheet, UserName=root@localhost, MySQL-AB JDBC Driver] will be managed by Spring [DEBUG] 2012-08-13 18:10:34 :ooo Using Connection [jdbc:mysql://localhost:3306/timesheet, UserName=root@localhost, 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 [org.apache.ibatis.session.defaults.DefaultSqlSession@177e6b4] [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, UserName=root@localhost, MySQL-AB JDBC Driver] [DEBUG] 2012-08-13 18:10:34 :Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@177e6b4] [DEBUG] 2012-08-13 18:10:34 :Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@177e6b4] [DEBUG] 2012-08-13 18:10:34 :Releasing JDBC Connection [jdbc:mysql://localhost:3306/timesheet, UserName=root@localhost, 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項目地址:github.com/BothEyes199…

相關文章
相關標籤/搜索