Maven based on Spring + Spring MVC + Mybatis environment construction project development, the first environment to build up. Last time we did a Spring + Spring MVC + Mybatis + Log4J + JUnit Test environment setup, this time is similar, but is based on Maven, but also added transaction management.

First of all, you can learn about Maven. Personally, I think it is very convenient to manage JAR packages. I don’t need to write it one by one, I can just add it directly. Since there is only one POM file to specify the JAR package, the entire project is very small, usually a few MB, only when you make the project into a WAR package, Maven will automatically put the third-party JAR package into the project, then you can deploy to the Tomcat webApp, put in, restart Tomcat OK.

1. How to Play guitar First, I use the JEE version of Eclipse for the IDE. To ensure that installed the Maven yo, you can use the eclipse Install New Software, the URL is http://m2eclipse.sonatype.org/sites/m2e/, and then go step by step, and installed after will restart again. A word of advice: after installing Maven, don’t use it in your IDE. Instead, download it from your IDE, unzip it, and have maven point to the one you downloaded and installed.

3. Next, type groupId:net.yuanmomo; ArtifactId :Test, finish, wait a little bit, and you’re done. Here is an initial project created:

4. But this is not the default Standard structure for Maven projects. Create a Source Folder under your project. Folder Name: SRC /main/ Java as shown below:

5. If you look at the above project structure, you are familiar with it. Maven’s project structure path is a bit annoying, a bit annoying. Maven WAR package extract things are SRC /main/webapp files, and then into a WAR WEB project can be deployed, but, but, when we develop, in eclipse Tomcat debugging, Tomcat does not deploy files under SRC /main/webapp to the server. At this point, if you open the Server and then add and remove, you will not find the Test project on the left side, as follows:

(5.1). Create the WebRoot, WEB-INF, etc folder under the path of the Test project according to the path rules, and copy the above web. XML to the new web-INF folder. Don’t worry, that’s what I did on my last project, but it won’t work that way. You change the JSP to the following one and maven to the upper one for packaging. You still have to copy it and copy it. Trouble, if SVN management is used again, you will be exhausted and dizzy. We often do it below when debugging and writing, and then have to copy it one by one when submitting, and there are many problems. Therefore, the second method is recommended. (1) Right-click on Test Facets — >Properties — >Project Facets — >Convet to Representations of representations form

6. The database creation script is provided to facilitate the test.

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; -- DATABASE: 'timesheet' -- CREATE DATABASE 'timesheet' DEFAULT CHARACTER SET UTF8 COLLATE UTf8_bin; USE `timesheet`; — —————————————————— - - TABLE structure '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 ;Copy the code

7. How to add the necessary JAR packages to the POM file can be found in two different places:

Mvnrepository.com/ search.maven.org/ Adds the following POM file:

<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>
Copy the code

After modifying the POM file and saving it, Maven will automatically download the JAR packages locally. The wait could be long. Above I have listed all the packages I used in this project, if you can not use them, you can delete them. Once the download is complete, click on Maven Dependencies on the left of the project to see several jars.

8. Modify web. XML, configure Spring, Spring MVC, log4j, garble handling, etc.

<? The 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 - >< context-param> <param-name>contextConfigLocation</param-name> <param-value><! - the Spring configuration file - > classpath: / com/comverse timesheet/config/ApplicationContext. XML value > < param - < / context - param > <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <! - Spring character filter handle garbled characters - > <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 Configuration - >< context-param> <param-name>log4jConfigLocation</param-name> <param-value><! - log4j. The properties file path - > 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 -- > <servlet> <servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value><! - the dispatcher - servlet. XML file path - > classpath: / com/comverse timesheet/config/dispatcher - servlet. XML value > < param - </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>Copy the code

Save the file after modification.

9. Add log4j properties, JDBC. The properties such as the configuration file:

Path location:

# configuration for the CONSOLE and text record two ways 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 - - 4 r - 5 p [t] % % % % 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 appenders. Fileout. MaxFileSize = 100000 KB # default is true, append to the file; if false, the replace the log file whenever restart system log4j.appender.FILEOUT.Append=true # RollingFileAppender no DatePattern this attribute log4j. Appender. FILEOUT. Layout = org.. Apache log4j. PatternLayout # log4j. Appender. CONSOLE. Layout. ConversionPattern = [framework] % % % d - c - - 4 r - 5 p [t] % % % % c x - % m % n log4j.appender.FILEOUT.layout.ConversionPattern=[%-5p]_%d{yyyy-MM-dd HH:mm:ss} :%m%nCopy the code

(2).jdbc.properties: configuration of database connection information

driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/timesheet user=root password=root
Copy the code

(3).applicationContext. XML: Spring configuration file

<? The 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. The properties file path - > < bean class = "org. Springframework. Beans. Factory. Config. Accomplished" > < property  name="locations" value="classpath:/com/comverse/timesheet/config/jdbc.properties" /> </bean> <! - data source configuration - > < bean id = "dataSource" class = "HTTP: / / org.apache.com mons. 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 -- > <! <property name="testOnBorrow" value="false" /> <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> <! - control the = = = = = = affairs related -- > < 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.*.*(..) ) "/ > <! < AOP :advisor pointcut-ref=" PC "advice-ref="userTxAdvice" /> </aop:config> <! - MyBatis sqlSessionFactory MyBatis configuration - > < 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> <! XML file -- > <import resource=" implandBusinessBeans.xml "/> </beans>Copy the code

(4). Dispatcher-servlet: Configuration file for Spring MVC

<? The 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: the annotation - config / > <! - put the mark @ Controller annotation class into a bean - > < context: component - scan base - package = "com.com verse. The timesheet. Web. Controller" / > <! -- Enable Spring MVC annotations, To complete the request and annotated POJO mapping - > < bean class = "org. Springframework. Web. Servlet. MVC. The annotation. AnnotationMethodHandlerAdapter" / > <! - view beans - > < bean id = "viewResolver" class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> <! - Controller jump JSP page path and file suffix - > <! - file upload - > < bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.Com monsMultipartResolver" > <! - Set the Max upload size100MB - > <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize"> <value>1024000</value> </property> </bean> </beans>Copy the code

(5). ImplAndBusinessBeans. XML: this file is the main place the Business object of bean and implementation.

<? The 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 "> <! - these two classes of concrete implementation will give out in the back - > < bean id = "ITestTableDAOImpl" class = "com.com verse. The 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>Copy the code

At this point, several main configuration files have been added, only mybatis has several configuration files not added.

10. Create packages for developing systems:

10. Create a Java file for this test

(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........................ .}Copy the code

(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; }Copy the code

(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; }}Copy the code

(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; }}}Copy the code

(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 {// Inject bean from spring configuration file via 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"; }}Copy the code

(6).util: Basicsqlsupport. Java all implementation classes inherit from this class, and beans registered in implandBusinessBeans. XML will inject a SQLSession. The implementation above, for example, inherits this class.

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; }}Copy the code
  1. Join mybatis configuration file: (1) for TestTable beans to create mapper file, the path to the com/comverse timesheet/mybatis mapper/Test. The XML: Test. The XML

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

Add Mybatis config file to applicationContext. XML file (applicationContext. XML). In/com/comverse timesheet/mybatis/create SqlMapConfig. XML:

<? The 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.com verse. The timesheet. Web. All the bean in the bean bag, take individual name - > <! - such as TestTable class can use the Test to say - > < typeAlias type = "com.com verse. The timesheet. Web. Beans. TestTable" alias = "Test" / > < / typeAliases > <mappers> <! - corresponding XML configuration file path information of the Bean class - > < mapper resource = "com/comverse timesheet/mybatis mapper/Test. The XML" / > < / mappers > </configuration>Copy the code
  1. The integration of the framework is complete, and the directory structure of the project is as follows:
  2. Write a test page whose path is specified in dispatcher-servlet.xml — / web-INF/JSP / : the file name is defined in controller — result, the suffix is.jsp, so result.jsp.

(1). result.jsp:

<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <! PUBLIC DOCTYPE HTML "- / / / / 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> </h1> </body> </html>Copy the code

14. At this point, our project is complete and deployed.

Check the Problem box for problems before deploying. This time I suddenly encountered a problem, I did not meet last Friday, today is strange. But that’s okay. We’re gonna solve the problem. (1). This problem is found at the problem

See Loose CLASspath Web Libraries Support. Right-click on the project – > Properties – > Deployment Assembly – > Add and select Java Build Path “Entries, then check Maven Dependencies – > Finish – >OK to solve the problem.

http://localhost:8080/Test/, see HelloWord

Then visit http://localhost:8080/Test/result.do and see the results, happy!! Let’s look at the database

Data insertion successfully, so far, our project setup is complete!! If there is a typo, please forgive me, because typing too painful!! Thank you!!

  1. Check our log message:

    [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.com verse. The timesheet. Web. Controller. ResultController @ 7056 d5’ [the 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.springframewor k.ui.ModelMap) throws java.lang.Exception ???????????????????????? 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: The 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’

You can see that our transaction also added successfully.

Spring MVC flow: Request – > Controller – > Business – > Implementation – >mysql

GitHub project address: github.com/BothEyes199…