Example of Spring+Mybatis+Spring MVC+Maven+MySql

Keywords: Attribute Spring Mybatis log4j

Example of Spring+Mybatis+Spring MVC+Maven+MySql

Label: SpringMybatisspring mvcMaven
2015-09-30 07:50 3,055 people reading comment(37) Collection Report
This article has been included in:
Classification:
Mybatis(12) SpringMVC(8) Spring(24)

Copyright Statement: This article is the original article of Evankaka, blogger Lin Bingwen, reproduced at http://blog.csdn.net/evankaka

Catalog (?)[+]

  1. Preparations
  2. Second Project Establishment
  3. Three spingmybatis configuration
  4. Four Unit Testing
  5. Five Conversion web Engineering
  6. Six configurations Spring MVC

        Evankaka Lin Bingwen Original works. Reprinted please indicate the source http://blog.csdn.net/evankaka

Summary: This article mainly talks about how to use Maven to build. spring+Mybatis+SpringMVC+MySQL The article is very detailed, with code and pictures, and finally with the effect of running.

Free download of this project

I. Preparations

1. First create a table:

  1. CREATE TABLE `t_user` (  
  2.   `USER_ID` int(11) NOT NULL AUTO_INCREMENT,  
  3.   `USER_NAME` char(30) NOT NULL,  
  4.   `USER_PASSWORD` char(10) NOT NULL,  
  5.   `USER_EMAIL` char(30) NOT NULL,  
  6.   PRIMARY KEY (`USER_ID`),  
  7.   KEY `IDX_NAME` (`USER_NAME`)  
  8. ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8  
CREATE TABLE `t_user` (
  `USER_ID` int(11) NOT NULL AUTO_INCREMENT,
  `USER_NAME` char(30) NOT NULL,
  `USER_PASSWORD` char(10) NOT NULL,
  `USER_EMAIL` char(30) NOT NULL,
  PRIMARY KEY (`USER_ID`),
  KEY `IDX_NAME` (`USER_NAME`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8

Insert some data randomly:

  1. INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (1,'Lin Bingwen','1234567','ling20081005@126.com');
  2. INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (2, 'evan', '123', 'fff@126.com');  
  3. INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (3, 'kaka', 'cadg', 'fwsfg@126.com');  
  4. INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (4, 'simle', 'cscs', 'fsaf@126.com');  
  5. INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (5, 'arthur', 'csas', 'fsaff@126.com');  
  6. INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (6,'Xiaode','yuh78','fdfas@126.com');
  7. INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (7,'Small','cvff','fsaf@126.com');
  8. INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (8,'Forest House','gvv','lin@126.com');
  9. INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (9,'Lin Bingwen Evankaka','dfsc','ling2008@126.com');
  10. INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (10, 'apple', 'uih6', 'ff@qq.com');  
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (1, 'Pin-Wen Lin', '1234567@', 'ling20081005@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (2, 'evan', '123', 'fff@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (3, 'kaka', 'cadg', 'fwsfg@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (4, 'simle', 'cscs', 'fsaf@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (5, 'arthur', 'csas', 'fsaff@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (6, 'Xiao De', 'yuh78', 'fdfas@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (7, 'Little', 'cvff', 'fsaf@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (8, 'Lin Lin's home', 'gvv', 'lin@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (9, 'Pin-Wen Lin Evankaka', 'dfsc', 'ling2008@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (10, 'apple', 'uih6', 'ff@qq.com');

II. Engineering Creation

1. Maven Project Creation

(1) New construction


(2) Choosing a Fast Framework

(3) Output project name, package, remember to select war (for web project, spingMVC can be used later)


(4) After creation.

The catalogue is as follows:


(5) Check

The JDK versions in these three places must be the same!!!




3. sping+mybatis configuration

1. The whole project catalogue is as follows:


2. POM files

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>com.lin</groupId>  
  5.     <artifactId>ssm_project</artifactId>  
  6.     <version>0.0.1-SNAPSHOT</version>  
  7.     <packaging>war</packaging>  
  8.     <properties>  
  9.         <!-- spring version number -->  
  10.         <spring.version>3.2.8.RELEASE</spring.version>  
  11.         <!-- log4j Log File Management Package Version -->  
  12.         <slf4j.version>1.6.6</slf4j.version>  
  13.         <log4j.version>1.2.12</log4j.version>  
  14.         <!-- junit version number -->  
  15.         <junit.version>4.10</junit.version>  
  16.         <!-- mybatis version number -->  
  17.         <mybatis.version>3.2.1</mybatis.version>  
  18.     </properties>  
  19.   
  20.     <dependencies>  
  21.         <!-- Add to Spring rely on -->  
  22.         <dependency>  
  23.             <groupId>org.springframework</groupId>  
  24.             <artifactId>spring-core</artifactId>  
  25.             <version>${spring.version}</version>  
  26.         </dependency>  
  27.         <dependency>  
  28.             <groupId>org.springframework</groupId>  
  29.             <artifactId>spring-webmvc</artifactId>  
  30.             <version>${spring.version}</version>  
  31.         </dependency>  
  32.         <dependency>  
  33.             <groupId>org.springframework</groupId>  
  34.             <artifactId>spring-context</artifactId>  
  35.             <version>${spring.version}</version>  
  36.         </dependency>  
  37.         <dependency>  
  38.             <groupId>org.springframework</groupId>  
  39.             <artifactId>spring-context-support</artifactId>  
  40.             <version>${spring.version}</version>  
  41.         </dependency>  
  42.         <dependency>  
  43.             <groupId>org.springframework</groupId>  
  44.             <artifactId>spring-aop</artifactId>  
  45.             <version>${spring.version}</version>  
  46.         </dependency>  
  47.         <dependency>  
  48.             <groupId>org.springframework</groupId>  
  49.             <artifactId>spring-aspects</artifactId>  
  50.             <version>${spring.version}</version>  
  51.         </dependency>  
  52.         <dependency>  
  53.             <groupId>org.springframework</groupId>  
  54.             <artifactId>spring-tx</artifactId>  
  55.             <version>${spring.version}</version>  
  56.         </dependency>  
  57.         <dependency>  
  58.             <groupId>org.springframework</groupId>  
  59.             <artifactId>spring-jdbc</artifactId>  
  60.             <version>${spring.version}</version>  
  61.         </dependency>  
  62.         <dependency>  
  63.             <groupId>org.springframework</groupId>  
  64.             <artifactId>spring-web</artifactId>  
  65.             <version>${spring.version}</version>  
  66.         </dependency>  
  67.   
  68.         <!--Unit test dependencies -->  
  69.         <dependency>  
  70.             <groupId>junit</groupId>  
  71.             <artifactId>junit</artifactId>  
  72.             <version>${junit.version}</version>  
  73.             <scope>test</scope>  
  74.         </dependency>  
  75.   
  76.         <!-- Log File Management Package -->  
  77.         <!-- log start -->  
  78.         <dependency>  
  79.             <groupId>log4j</groupId>  
  80.             <artifactId>log4j</artifactId>  
  81.             <version>${log4j.version}</version>  
  82.         </dependency>  
  83.         <dependency>  
  84.             <groupId>org.slf4j</groupId>  
  85.             <artifactId>slf4j-api</artifactId>  
  86.             <version>${slf4j.version}</version>  
  87.         </dependency>  
  88.         <dependency>  
  89.             <groupId>org.slf4j</groupId>  
  90.             <artifactId>slf4j-log4j12</artifactId>  
  91.             <version>${slf4j.version}</version>  
  92.         </dependency>  
  93.         <!-- log end -->  
  94.   
  95.         <!--spring Unit test dependencies -->  
  96.         <dependency>  
  97.             <groupId>org.springframework</groupId>  
  98.             <artifactId>spring-test</artifactId>  
  99.             <version>${spring.version}</version>  
  100.             <scope>test</scope>  
  101.         </dependency>  
  102.   
  103.         <!--mybatis rely on -->  
  104.         <dependency>  
  105.             <groupId>org.mybatis</groupId>  
  106.             <artifactId>mybatis</artifactId>  
  107.             <version>${mybatis.version}</version>  
  108.         </dependency>  
  109.   
  110.         <!-- mybatis/spring package -->  
  111.         <dependency>  
  112.             <groupId>org.mybatis</groupId>  
  113.             <artifactId>mybatis-spring</artifactId>  
  114.             <version>1.2.0</version>  
  115.         </dependency>  
  116.   
  117.         <!-- mysql Driving package -->  
  118.         <dependency>  
  119.             <groupId>mysql</groupId>  
  120.             <artifactId>mysql-connector-java</artifactId>  
  121.             <version>5.1.29</version>  
  122.         </dependency>  
  123.     </dependencies>  
  124.   
  125. </project>  
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.lin</groupId>
	<artifactId>ssm_project</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<properties>
		<!-- spring version number -->
		<spring.version>3.2.8.RELEASE</spring.version>
		<!-- log4j Log File Management Package Version -->
		<slf4j.version>1.6.6</slf4j.version>
		<log4j.version>1.2.12</log4j.version>
		<!-- junit version number -->
		<junit.version>4.10</junit.version>
		<!-- mybatis version number -->
		<mybatis.version>3.2.1</mybatis.version>
	</properties>

	<dependencies>
		<!-- Add to Spring rely on -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!--Unit test dependencies -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- Log File Management Package -->
		<!-- log start -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<!-- log end -->

		<!--spring Unit test dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>

		<!--mybatis rely on -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>

		<!-- mybatis/spring package -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.0</version>
		</dependency>

		<!-- mysql Driving package -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.29</version>
		</dependency>
	</dependencies>

</project>
3. Java Code - --- src/main/java

The catalogue is as follows:


(1)User.Java

Corresponding data base The fields of the middle table, the package com.lin.domain under src/main/java

  1. package com.lin.domain;  
  2.   
  3. /** 
  4.  * User Mapping class 
  5.  *  
  6.  * @author linbingwen 
  7.  * @time 2015.5.15 
  8.  */  
  9. public class User {  
  10.     private Integer userId;  
  11.     private String userName;  
  12.     private String userPassword;  
  13.     private String userEmail;  
  14.   
  15.     public Integer getUserId() {  
  16.         return userId;  
  17.     }  
  18.   
  19.     public void setUserId(Integer userId) {  
  20.         this.userId = userId;  
  21.     }  
  22.   
  23.     public String getUserName() {  
  24.         return userName;  
  25.     }  
  26.   
  27.     public void setUserName(String userName) {  
  28.         this.userName = userName;  
  29.     }  
  30.   
  31.     public String getUserPassword() {  
  32.         return userPassword;  
  33.     }  
  34.   
  35.     public void setUserPassword(String userPassword) {  
  36.         this.userPassword = userPassword;  
  37.     }  
  38.   
  39.     public String getUserEmail() {  
  40.         return userEmail;  
  41.     }  
  42.   
  43.     public void setUserEmail(String userEmail) {  
  44.         this.userEmail = userEmail;  
  45.     }  
  46.   
  47.     @Override  
  48.     public String toString() {  
  49.         return "User [userId=" + userId + ", userName=" + userName  
  50.                 + ", userPassword=" + userPassword + ", userEmail=" + userEmail  
  51.                 + "]";  
  52.     }  
  53.       
  54. }  
package com.lin.domain;

/**
 * User Mapping class
 * 
 * @author linbingwen
 * @time 2015.5.15
 */
public class User {
	private Integer userId;
	private String userName;
	private String userPassword;
	private String userEmail;

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserPassword() {
		return userPassword;
	}

	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	public String getUserEmail() {
		return userEmail;
	}

	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}

	@Override
	public String toString() {
		return "User [userId=" + userId + ", userName=" + userName
				+ ", userPassword=" + userPassword + ", userEmail=" + userEmail
				+ "]";
	}
	
}

(2)UserDao.java

Dao interface class, which corresponds to mapper files. The package com.lin.dao placed under src/main/java is as follows:

  1. package com.lin.dao;  
  2.   
  3.   
  4. import com.lin.domain.User;  
  5.   
  6. /** 
  7.  * Functional summary: User's DAO class 
  8.  *  
  9.  * @author linbingwen 
  10.  * @since 2015 September 28th 2013 
  11.  */  
  12. public interface UserDao {  
  13.     /** 
  14.      *  
  15.      * @author linbingwen 
  16.      * @since 2015 September 28th 2013 
  17.      * @param userId 
  18.      * @return 
  19.      */  
  20.     public User selectUserById(Integer userId);  
  21.   
  22. }  
package com.lin.dao;


import com.lin.domain.User;

/**
 * Functional summary: User's DAO class
 * 
 * @author linbingwen
 * @since 2015 September 28th 2013
 */
public interface UserDao {
	/**
	 * 
	 * @author linbingwen
	 * @since 2015 September 28th 2013
	 * @param userId
	 * @return
	 */
	public User selectUserById(Integer userId);

}

(2) UserService.java and UserService Impl. Java

Service interface class and implementation class, the package com.lin.service under src/main/java, are as follows:

UserService.java

  1. package com.lin.service;  
  2.   
  3. import org.springframework.stereotype.Service;  
  4.   
  5. import com.lin.domain.User;  
  6.   
  7. /** 
  8.  * Functional summary: UserService interface class 
  9.  *  
  10.  * @author linbingwen 
  11.  * @since  2015 28 September 
  12.  */  
  13. public interface UserService {  
  14.     User selectUserById(Integer userId);  
  15.   
  16. }  
package com.lin.service;

import org.springframework.stereotype.Service;

import com.lin.domain.User;

/**
 * Functional summary: UserService interface class
 * 
 * @author linbingwen
 * @since  2015 September 28th 2013 
 */
public interface UserService {
	User selectUserById(Integer userId);

}

UserServiceImpl.java

  1. package com.lin.service;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Service;  
  5.   
  6. import com.lin.dao.UserDao;  
  7. import com.lin.domain.User;  
  8.   
  9. /** 
  10.  * Functional summary: UserService implementation class 
  11.  *  
  12.  * @author linbingwen 
  13.  * @since  2015 28 September 
  14.  */  
  15. @Service  
  16. public class UserServiceImpl implements UserService{  
  17.     @Autowired  
  18.     private UserDao userDao;  
  19.   
  20.     public User selectUserById(Integer userId) {  
  21.         return userDao.selectUserById(userId);  
  22.           
  23.     }  
  24.   
  25. }  
package com.lin.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lin.dao.UserDao;
import com.lin.domain.User;

/**
 * Functional summary: UserService implementation class
 * 
 * @author linbingwen
 * @since  2015 September 28th 2013 
 */
@Service
public class UserServiceImpl implements UserService{
	@Autowired
	private UserDao userDao;

	public User selectUserById(Integer userId) {
		return userDao.selectUserById(userId);
		
	}

}

(4) mapper file

Used to correspond to dao files, under the com.lin.mapper package under src/main/java

  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"    
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4. <mapper namespace="com.lin.dao.UserDao">  
  5. <!--Set up domain Class corresponds to the fields of the tables in the database one by one. Pay attention to the fields in the database and the fields in the database. domain The field names in the classes are different, so be sure to do it here! uuuuuuuuuu-->  
  6.     <resultMap id="BaseResultMap" type="com.lin.domain.User">  
  7.         <id column="USER_ID" property="userId" jdbcType="INTEGER" />  
  8.         <result column="USER_NAME" property="userName" jdbcType="CHAR" />  
  9.         <result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />  
  10.         <result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />  
  11.     </resultMap>  
  12.     <!-- Query single record -->  
  13.     <select id="selectUserById" parameterType="int" resultMap="BaseResultMap">  
  14.         SELECT * FROM t_user WHERE USER_ID = #{userId}  
  15.     </select>  
  16. </mapper>  
<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lin.dao.UserDao">
<!--Set up domain Class corresponds to the fields of the tables in the database one by one. Pay attention to the fields in the database and the fields in the database. domain The field names in the classes are different, so be sure to do it here! uuuuuuuuuu-->
	<resultMap id="BaseResultMap" type="com.lin.domain.User">
		<id column="USER_ID" property="userId" jdbcType="INTEGER" />
		<result column="USER_NAME" property="userName" jdbcType="CHAR" />
		<result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />
		<result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />
	</resultMap>
	<!-- Query single record -->
	<select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
		SELECT * FROM t_user WHERE USER_ID = #{userId}
	</select>
</mapper>

4. Resource Allocation--src/main/resources

The catalogue is as follows:


(1)mybatis configuration file

There's nothing here, because it's all in application.xml, under the mybatis folder under src/main/resources

mybatis-config.xml reads as follows:

  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"    
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">    
  4. <configuration>      
  5. </configuration>  
<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
"http://mybatis.org/dtd/mybatis-3-config.dtd">  
<configuration>    
</configuration>

(2) Data source configuration jdbc.properties

Put it in the properties folder under src/main/resources

  1. jdbc_driverClassName=com.mysql.jdbc.Driver  
  2. jdbc_url=jdbc:mysql://localhost:3306/learning  
  3. jdbc_username=root  
  4. jdbc_password=christmas258@  
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/learning
jdbc_username=root
jdbc_password=christmas258@
(3) Spring configuration

This is the most important: application.xml is as follows

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="    
  6.            http://www.springframework.org/schema/beans    
  7.            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  8.            http://www.springframework.org/schema/aop    
  9.            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  10.            http://www.springframework.org/schema/context    
  11.            http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  12.        
  13.      <!-- Introduce jdbc configuration file -->    
  14.      <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  15.         <property name="locations">  
  16.             <list>  
  17.                <value>classpath:properties/*.properties</value>  
  18.                 <!--If you have more than one configuration file, you just need to add it here - >  
  19.             </list>  
  20.         </property>  
  21.     </bean>  
  22.       
  23.       
  24.   
  25.     <!-- Configure Data Source - > Configure Data Source -> Configure Data Source -> Configure Data Source -> Configure Data Source -> Configure Data Source  
  26.     <bean id="dataSource"  
  27.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  28.         <!-- Do not use properties to configure --> uuuuuuuuuuuu  
  29.         <!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" />   
  30.             <property name="url" value="jdbc:mysql://localhost:3306/learning" />   
  31.             <property name="username" value="root" />   
  32.             <property name="password" value="christmas258@" /> -->  
  33.        <!-- Use properties to configure --> uuuuuuuuuuuu  
  34.         <property name="driverClassName">  
  35.             <value>${jdbc_driverClassName}</value>  
  36.         </property>  
  37.         <property name="url">  
  38.             <value>${jdbc_url}</value>  
  39.         </property>  
  40.         <property name="username">  
  41.             <value>${jdbc_username}</value>  
  42.         </property>  
  43.         <property name="password">  
  44.             <value>${jdbc_password}</value>  
  45.         </property>  
  46.     </bean>  
  47.   
  48.     <!-- All mapper interface files corresponding to XxxxMapper.xml are scanned automatically, so there is no need to configure the mapping of Mpper manually one by one, as long as the Mapper interface class corresponds to the Mapper mapping file. >  
  49.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  50.         <property name="basePackage"  
  51.             value="com.lin.dao" />  
  52.     </bean>  
  53.   
  54.     <!-- Configure Mybatis files, mapperLocations ** Mapper.xml file locations, configLocation s mybatis-config file locations - >.  
  55.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  56.         <property name="dataSource" ref="dataSource" />  
  57.         <property name="mapperLocations" value="classpath*:com/lin/mapper/**/*.xml"/>    
  58.         <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />  
  59.         <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"   
  60.             /> -->  
  61.     </bean>  
  62.   
  63.     <!-- Automatic Scanning Annotation bean -->  
  64.     <context:component-scan base-package="com.lin.service" />  
  65.   
  66. </beans>  
<?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"
	xsi:schemaLocation="  
           http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-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/context  
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
     
     <!-- Introduce jdbc configuration file -->  
     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
               <value>classpath:properties/*.properties</value>
                <!--If you have more than one configuration file, you just need to add it here - >
            </list>
        </property>
    </bean>
    
    

	<!-- Configuring data sources - >
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!-- Configuration without using properties - > uuuuuuuuuuuu
		<!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
			<property name="url" value="jdbc:mysql://localhost:3306/learning" /> 
			<property name="username" value="root" /> 
			<property name="password" value="christmas258@" /> -->
	   <!-- Use properties to configure - >
		<property name="driverClassName">
			<value>${jdbc_driverClassName}</value>
		</property>
		<property name="url">
			<value>${jdbc_url}</value>
		</property>
		<property name="username">
			<value>${jdbc_username}</value>
		</property>
		<property name="password">
			<value>${jdbc_password}</value>
		</property>
	</bean>

	<!-- All mapper interface files corresponding to XxxxMapper.xml are scanned automatically, so there is no need to configure the mapping of Mpper manually one by one, as long as the Mapper interface class corresponds to the Mapper mapping file. >
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage"
			value="com.lin.dao" />
	</bean>

    <!-- Configure Mybatis file, mapperLocations ** Mapper.xml file location, configLocation configuration mybatis-config file location - >
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath*:com/lin/mapper/**/*.xml"/>  
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
		<!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model" 
			/> -->
	</bean>

	<!-- Automatic Scanning Annotation bean -->
	<context:component-scan base-package="com.lin.service" />

</beans>

(4) Log printing log4j.properties

Just put it in src/main/resources

  1. log4j.rootLogger=DEBUG,Console,Stdout  
  2.   
  3. #Console  
  4. log4j.appender.Console=org.apache.log4j.ConsoleAppender  
  5. log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
  6. log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  
  7.   
  8. log4j.logger.java.sql.ResultSet=INFO  
  9. log4j.logger.org.apache=INFO  
  10. log4j.logger.java.sql.Connection=DEBUG  
  11. log4j.logger.java.sql.Statement=DEBUG  
  12. log4j.logger.java.sql.PreparedStatement=DEBUG   
  13.   
  14. log4j.appender.Stdout = org.apache.log4j.DailyRollingFileAppender    
  15. log4j.appender.Stdout.File = E://logs/log.log    
  16. log4j.appender.Stdout.Append = true    
  17. log4j.appender.Stdout.Threshold = DEBUG     
  18. log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout    
  19. log4j.appender.Stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n    
log4j.rootLogger=DEBUG,Console,Stdout

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG 

log4j.appender.Stdout = org.apache.log4j.DailyRollingFileAppender  
log4j.appender.Stdout.File = E://logs/log.log  
log4j.appender.Stdout.Append = true  
log4j.appender.Stdout.Threshold = DEBUG   
log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout  
log4j.appender.Stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n  

Unit Testing

The above configuration is in good condition, and the next step is the success of the test.

The entire catalogue is as follows:


(1)test base class

  1. package com.lin.baseTest;  
  2.   
  3. import org.junit.runner.RunWith;  
  4. import org.slf4j.Logger;  
  5. import org.slf4j.LoggerFactory;  
  6. import org.springframework.test.context.ContextConfiguration;  
  7. import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;  
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  9.   
  10. /** 
  11.  * Functional summary: 
  12.  *  
  13.  * @author linbingwen 
  14.  * @since  2015 28 September 
  15.  */  
  16. //Specify the configuration file for bean injection  
  17. @ContextConfiguration(locations = { "classpath:application.xml" })  
  18. //Use the standard JUnit@RunWith annotation to tell JUnit to use Spring TestRunner  
  19. @RunWith(SpringJUnit4ClassRunner.class)  
  20. public abstract class SpringTestCase extends AbstractJUnit4SpringContextTests{  
  21.     protected Logger logger = LoggerFactory.getLogger(getClass());  
  22. }  
package com.lin.baseTest;

import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Functional summary:
 * 
 * @author linbingwen
 * @since  2015 September 28th 2013 
 */
//Specify the configuration file for bean injection
@ContextConfiguration(locations = { "classpath:application.xml" })
//Use the standard JUnit@RunWith annotation to tell JUnit to use Spring TestRunner
@RunWith(SpringJUnit4ClassRunner.class)
public abstract class SpringTestCase extends AbstractJUnit4SpringContextTests{
	protected Logger logger = LoggerFactory.getLogger(getClass());
}

(2) Test class

  1. package com.lin.service;  
  2.   
  3. import org.apache.log4j.Logger;  
  4. import org.junit.Test;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6.   
  7. import com.lin.baseTest.SpringTestCase;  
  8. import com.lin.domain.User;  
  9.   
  10. /** 
  11.  * Functional summary: UserService unit testing 
  12.  *  
  13.  * @author linbingwen 
  14.  * @since  2015 28 September 
  15.  */  
  16. public class UserServiceTest extends SpringTestCase {  
  17.     @Autowired  
  18.     private UserService userService;  
  19.     Logger logger = Logger.getLogger(UserServiceTest.class);  
  20.       
  21.     @Test  
  22.     public void selectUserByIdTest(){  
  23.         User user = userService.selectUserById(10);  
  24.         logger.debug("Finding results" + user);  
  25.     }  
  26.       
  27.   
  28. }  
package com.lin.service;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.lin.baseTest.SpringTestCase;
import com.lin.domain.User;

/**
 * Functional summary: UserService unit testing
 * 
 * @author linbingwen
 * @since  2015 September 28th 2013 
 */
public class UserServiceTest extends SpringTestCase	{
	@Autowired
	private UserService userService;
	Logger logger = Logger.getLogger(UserServiceTest.class);
	
	@Test
	public void selectUserByIdTest(){
		User user = userService.selectUserById(10);
        logger.debug("Finding results" + user);
	}
	

}
Select UserByIdTest, and then right-click to run as follows


Output results:


Results of Important Printing


Here

  1. 2015-09-28 15:20:15,129 [main] DEBUG [com.lin.dao.UserDao.selectUserById] - ==>  Preparing: SELECT * FROM t_user WHERE USER_ID = ?   
  2. 2015-09-28 15:20:15,160 [main] DEBUG [com.lin.dao.UserDao.selectUserById] - ==> Parameters: 10(Integer)  
  3. 2015-09-28 15:20:15,160 [main] DEBUG [org.mybatis.spring.SqlSessionUtils] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6b64bff9]  
  4. 2015-09-28 15:20:15,160 [main] DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Returning JDBC Connection to DataSource  
  5. 2015-09-28 15:20:15,160 [main] DEBUG [com.lin.service.UserServiceTest] - Finding results User [userId=10, userName=apple, userPassword=uih6, userEmail=ff@qq.com]  
2015-09-28 15:20:15,129 [main] DEBUG [com.lin.dao.UserDao.selectUserById] - ==>  Preparing: SELECT * FROM t_user WHERE USER_ID = ? 
2015-09-28 15:20:15,160 [main] DEBUG [com.lin.dao.UserDao.selectUserById] - ==> Parameters: 10(Integer)
2015-09-28 15:20:15,160 [main] DEBUG [org.mybatis.spring.SqlSessionUtils] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6b64bff9]
2015-09-28 15:20:15,160 [main] DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Returning JDBC Connection to DataSource
2015-09-28 15:20:15,160 [main] DEBUG [com.lin.service.UserServiceTest] - Finding results User [userId=10, userName=apple, userPassword=uih6, userEmail=ff@qq.com]

Database:


The program runs successfully and the results are correct!

Configure spring+mybatis+mysql!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
=====================================================
Here we start adding Spirng MVC and converting maven project to web project

5. Conversion of web Engineering

Then the project goes on to say that before spingMVC is added at this point, the project has to be converted slightly.
At this point, the results under webapp have not been displayed, because we have not yet configured this project as a web project.

Enter the Properties configuration again, as shown in the following figure: If it is not shown below, remove the of the dynamic web module first, and then reopen this
Enter, and then enter the following

Once OK is determined, some files are automatically generated under webapp, as follows





Configuration of Spring MVC

(1) Modify the POM file and add this content. The new POM file is as follows:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>com.lin</groupId>  
  5.     <artifactId>ssm_project</artifactId>  
  6.     <version>0.0.1-SNAPSHOT</version>  
  7.     <packaging>war</packaging>  
  8.     <properties>  
  9.         <!-- spring version number -->  
  10.         <spring.version>3.2.8.RELEASE</spring.version>  
  11.         <!-- log4j Log File Management Package Version -->  
  12.         <slf4j.version>1.6.6</slf4j.version>  
  13.         <log4j.version>1.2.12</log4j.version>  
  14.         <!-- junit version number -->  
  15.         <junit.version>4.10</junit.version>  
  16.         <!-- mybatis version number -->  
  17.         <mybatis.version>3.2.1</mybatis.version>  
  18.     </properties>  
  19.   
  20.     <dependencies>  
  21.         <!-- Add to Spring rely on -->  
  22.         <dependency>  
  23.             <groupId>org.springframework</groupId>  
  24.             <artifactId>spring-core</artifactId>  
  25.             <version>${spring.version}</version>  
  26.         </dependency>  
  27.         <dependency>  
  28.             <groupId>org.springframework</groupId>  
  29.             <artifactId>spring-webmvc</artifactId>  
  30.             <version>${spring.version}</version>  
  31.         </dependency>  
  32.         <dependency>  
  33.             <groupId>org.springframework</groupId>  
  34.             <artifactId>spring-context</artifactId>  
  35.             <version>${spring.version}</version>  
  36.         </dependency>  
  37.         <dependency>  
  38.             <groupId>org.springframework</groupId>  
  39.             <artifactId>spring-context-support</artifactId>  
  40.             <version>${spring.version}</version>  
  41.         </dependency>  
  42.         <dependency>  
  43.             <groupId>org.springframework</groupId>  
  44.             <artifactId>spring-aop</artifactId>  
  45.             <version>${spring.version}</version>  
  46.         </dependency>  
  47.         <dependency>  
  48.             <groupId>org.springframework</groupId>  
  49.             <artifactId>spring-aspects</artifactId>  
  50.             <version>${spring.version}</version>  
  51.         </dependency>  
  52.         <dependency>  
  53.             <groupId>org.springframework</groupId>  
  54.             <artifactId>spring-tx</artifactId>  
  55.             <version>${spring.version}</version>  
  56.         </dependency>  
  57.         <dependency>  
  58.             <groupId>org.springframework</groupId>  
  59.             <artifactId>spring-jdbc</artifactId>  
  60.             <version>${spring.version}</version>  
  61.         </dependency>  
  62.         <dependency>  
  63.             <groupId>org.springframework</groupId>  
  64.             <artifactId>spring-web</artifactId>  
  65.             <version>${spring.version}</version>  
  66.         </dependency>  
  67.   
  68.         <!--Unit test dependencies -->  
  69.         <dependency>  
  70.             <groupId>junit</groupId>  
  71.             <artifactId>junit</artifactId>  
  72.             <version>${junit.version}</version>  
  73.             <scope>test</scope>  
  74.         </dependency>  
  75.   
  76.         <!-- Log File Management Package -->  
  77.         <!-- log start -->  
  78.         <dependency>  
  79.             <groupId>log4j</groupId>  
  80.             <artifactId>log4j</artifactId>  
  81.             <version>${log4j.version}</version>  
  82.         </dependency>  
  83.         <dependency>  
  84.             <groupId>org.slf4j</groupId>  
  85.             <artifactId>slf4j-api</artifactId>  
  86.             <version>${slf4j.version}</version>  
  87.         </dependency>  
  88.         <dependency>  
  89.             <groupId>org.slf4j</groupId>  
  90.             <artifactId>slf4j-log4j12</artifactId>  
  91.             <version>${slf4j.version}</version>  
  92.         </dependency>  
  93.         <!-- log end -->  
  94.   
  95.         <!--spring Unit test dependencies -->  
  96.         <dependency>  
  97.             <groupId>org.springframework</groupId>  
  98.             <artifactId>spring-test</artifactId>  
  99.             <version>${spring.version}</version>  
  100.             <scope>test</scope>  
  101.         </dependency>  
  102.   
  103.         <!--mybatis rely on -->  
  104.         <dependency>  
  105.             <groupId>org.mybatis</groupId>  
  106.             <artifactId>mybatis</artifactId>  
  107.             <version>${mybatis.version}</version>  
  108.         </dependency>  
  109.   
  110.         <!-- mybatis/spring package -->  
  111.         <dependency>  
  112.             <groupId>org.mybatis</groupId>  
  113.             <artifactId>mybatis-spring</artifactId>  
  114.             <version>1.2.0</version>  
  115.         </dependency>  
  116.   
  117.         <!-- mysql Driving package -->  
  118.         <dependency>  
  119.             <groupId>mysql</groupId>  
  120.             <artifactId>mysql-connector-java</artifactId>  
  121.             <version>5.1.29</version>  
  122.         </dependency>  
  123.           
  124.             <!-- javaee-api package Attention and project usage JDK Version correspondence -->  
  125.         <dependency>  
  126.             <groupId>javax</groupId>  
  127.             <artifactId>javaee-api</artifactId>  
  128.             <version>6.0</version>  
  129.             <scope>provided</scope>  
  130.         </dependency>  
  131.   
  132.         <!-- javaee-web-api package Attention and project usage JDK Version correspondence -->  
  133.         <dependency>  
  134.             <groupId>javax</groupId>  
  135.             <artifactId>javaee-web-api</artifactId>  
  136.             <version>6.0</version>  
  137.             <scope>provided</scope>  
  138.         </dependency>  
  139.     </dependencies>  
  140.   
  141. </project>  
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.lin</groupId>
	<artifactId>ssm_project</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<properties>
		<!-- spring version number -->
		<spring.version>3.2.8.RELEASE</spring.version>
		<!-- log4j Log File Management Package Version -->
		<slf4j.version>1.6.6</slf4j.version>
		<log4j.version>1.2.12</log4j.version>
		<!-- junit version number -->
		<junit.version>4.10</junit.version>
		<!-- mybatis version number -->
		<mybatis.version>3.2.1</mybatis.version>
	</properties>

	<dependencies>
		<!-- Add to Spring rely on -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!--Unit test dependencies -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- Log File Management Package -->
		<!-- log start -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<!-- log end -->

		<!--spring Unit test dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>

		<!--mybatis rely on -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>

		<!-- mybatis/spring package -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.0</version>
		</dependency>

		<!-- mysql Driving package -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.29</version>
		</dependency>
		
            <!-- javaee-api Pack attention and project usage JDK Version correspondence -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>6.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- javaee-web-api Pack attention and project usage JDK Version correspondence -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-web-api</artifactId>
			<version>6.0</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>

</project>
In fact, it adds the following two
  1.         <!-- javaee-api package Attention and project usage JDK Version correspondence -->  
  2. <dependency>  
  3.     <groupId>javax</groupId>  
  4.     <artifactId>javaee-api</artifactId>  
  5.     <version>6.0</version>  
  6.     <scope>provided</scope>  
  7. </dependency>  
  8.   
  9. <!-- javaee-web-api package Attention and project usage JDK Version correspondence -->  
  10. <dependency>  
  11.     <groupId>javax</groupId>  
  12.     <artifactId>javaee-web-api</artifactId>  
  13.     <version>6.0</version>  
  14.     <scope>provided</scope>  
  15. </dependency>  
          <!-- javaee-api Pack attention and project usage JDK Version correspondence -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>6.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- javaee-web-api Pack attention and project usage JDK Version correspondence -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-web-api</artifactId>
			<version>6.0</version>
			<scope>provided</scope>
		</dependency>

(2) Add spring MVC folder in src/main/resource, and then add the file spring-mvc.xml as follows:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.   xmlns:p="http://www.springframework.org/schema/p"  
  4.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.   xmlns:context="http://www.springframework.org/schema/context"  
  6.   xmlns:mvc="http://www.springframework.org/schema/mvc"  
  7.   xsi:schemaLocation="  
  8.     http://www.springframework.org/schema/beans  
  9.     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  10.     http://www.springframework.org/schema/context  
  11.     http://www.springframework.org/schema/context/spring-context-3.2.xsd  
  12.     http://www.springframework.org/schema/mvc  
  13.     http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">  
  14.        
  15.     <!-- scanning controller(controller Layer injection) -->  
  16.    <context:component-scan base-package="com.lin.controller"/>    
  17.        
  18.    <!-- Adding prefixes and suffixes to model views -->  
  19.      <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
  20.       p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>  
  21. </beans>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
     
    <!-- scanning controller(controller Layer injection) -->
   <context:component-scan base-package="com.lin.controller"/>  
     
   <!-- Adding prefixes and suffixes to model views -->
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>
</beans>
(3) configure web,xml
The catalogue is as follows:

Here's the key. web.xml is used to start sping, spingMVC
Place it under src/main/webapp/WEB-INF. The contents are as follows:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  5.     id="WebApp_ID" version="2.5">  
  6.     <display-name>Archetype Created Web Application</display-name>  
  7.    <!-- Initial Welcome Interface -->  
  8.     <welcome-file-list>  
  9.         <welcome-file>index.jsp</welcome-file>  
  10.     </welcome-file-list>  
  11.    
  12.     <!-- read spring configuration file -->  
  13.     <context-param>  
  14.         <param-name>contextConfigLocation</param-name>  
  15.         <param-value>classpath:application.xml</param-value>  
  16.     </context-param>  
  17.     <!-- Design Path Variable Value -->  
  18.     <context-param>  
  19.         <param-name>webAppRootKey</param-name>  
  20.         <param-value>springmvc.root</param-value>  
  21.     </context-param>  
  22.    
  23.    
  24.     <!-- Spring Character Set Filter -->  
  25.     <filter>  
  26.         <filter-name>SpringEncodingFilter</filter-name>  
  27.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  28.         <init-param>  
  29.             <param-name>encoding</param-name>  
  30.             <param-value>UTF-8</param-value>  
  31.         </init-param>  
  32.         <init-param>  
  33.             <param-name>forceEncoding</param-name>  
  34.             <param-value>true</param-value>  
  35.         </init-param>  
  36.     </filter>  
  37.     <filter-mapping>  
  38.         <filter-name>SpringEncodingFilter</filter-name>  
  39.         <url-pattern>/*</url-pattern>  
  40.     </filter-mapping>  
  41.    
  42.     <!-- Log record -->  
  43.     <context-param>  
  44.         <!-- Log Profile Path -->  
  45.         <param-name>log4jConfigLocation</param-name>  
  46.         <param-value>classpath:log4j.properties</param-value>  
  47.     </context-param>  
  48.     <context-param>  
  49.         <!-- Refresh intervals for log pages -->  
  50.         <param-name>log4jRefreshInterval</param-name>  
  51.         <param-value>6000</param-value>  
  52.     </context-param>  
  53.     <listener>  
  54.         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  55.     </listener>  
  56.    
  57.     <listener>  
  58.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  59.     </listener>  
  60.    
  61.     <!-- springMVC Core configuration -->  
  62.     <servlet>  
  63.         <servlet-name>dispatcherServlet</servlet-name>  
  64.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  65.         <init-param>  
  66.             <param-name>contextConfigLocation</param-name>  
  67.             <!--spingMVC Configuration path  -->  
  68.             <param-value>classpath:springmvc/spring-mvc.xml</param-value>  
  69.         </init-param>  
  70.         <load-on-startup>1</load-on-startup>  
  71.     </servlet>  
  72.     <!-- Interception settings -->  
  73.     <servlet-mapping>  
  74.         <servlet-name>dispatcherServlet</servlet-name>  
  75.         <url-pattern>/</url-pattern>  
  76.     </servlet-mapping>  
  77.    
  78.     <!-- Error jump page -->  
  79.     <error-page>  
  80.         <!-- Path incorrect -->  
  81.         <error-code>404</error-code>  
  82.         <location>/WEB-INF/errorpage/404.jsp</location>  
  83.     </error-page>  
  84.     <error-page>  
  85.         <!-- Access is prohibited without access rights -->  
  86.         <error-code>405</error-code>  
  87.         <location>/WEB-INF/errorpage/405.jsp</location>  
  88.     </error-page>  
  89.     <error-page>  
  90.         <!-- internal error -->  
  91.         <error-code>500</error-code>  
  92.         <location>/WEB-INF/errorpage/500.jsp</location>  
  93.     </error-page>  
  94. </web-app>  
<?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">
    <display-name>Archetype Created Web Application</display-name>
   <!-- Initial Welcome Interface -->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
 
    <!-- read spring configuration file -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>
    <!-- Design Path Variable Value -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>springmvc.root</param-value>
    </context-param>
 
 
    <!-- Spring Character Set Filter -->
    <filter>
        <filter-name>SpringEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>SpringEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
    <!-- Log record -->
    <context-param>
        <!-- Log Profile Path -->
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>
    <context-param>
        <!-- Refresh intervals for log pages -->
        <param-name>log4jRefreshInterval</param-name>
        <param-value>6000</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- springMVC Core configuration -->
	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<!--spingMVC Configuration path  -->
			<param-value>classpath:springmvc/spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- Interception settings -->
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
 
    <!-- Error jump page -->
    <error-page>
        <!-- Path incorrect -->
        <error-code>404</error-code>
        <location>/WEB-INF/errorpage/404.jsp</location>
    </error-page>
    <error-page>
        <!-- Access is prohibited without access rights -->
        <error-code>405</error-code>
        <location>/WEB-INF/errorpage/405.jsp</location>
    </error-page>
    <error-page>
        <!-- internal error -->
        <error-code>500</error-code>
        <location>/WEB-INF/errorpage/500.jsp</location>
    </error-page>
</web-app>

(4) Add index.jsp
Under src/main/webapp/WEB-INF, create a new folder view and add an index.jsp, which reads as follows:
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2. <html>  
  3. <body>  
  4. <h2>Hello World!</h2>  
  5.  ${user.userId}<br>  
  6.  ${user.userName}<br>  
  7.  ${user.userPassword}<br>  
  8.  ${user.userEmail}<br>  
  9. </body>  
  10. </html>  
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<h2>Hello World!</h2>
 ${user.userId}<br>
 ${user.userName}<br>
 ${user.userPassword}<br>
 ${user.userEmail}<br>
</body>
</html>

(5) Finally, controller wrote it.

Create a new package com.lin.controller under src/main/java. Then create a new class UserController.java, which reads as follows:

  1. package com.lin.controller;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.servlet.ModelAndView;  
  8.   
  9. import com.lin.domain.User;  
  10. import com.lin.service.UserService;  
  11.   
  12. /** 
  13.  * Functional summary: User Controller 
  14.  *  
  15.  * @author linbingwen 
  16.  * @since  2015 28 September 
  17.  */  
  18. @Controller  
  19. public class UserController {  
  20.     @Resource  
  21.     private UserService userService;  
  22.       
  23.     @RequestMapping("/")    
  24.     public ModelAndView getIndex(){      
  25.         ModelAndView mav = new ModelAndView("index");   
  26.         User user = userService.selectUserById(1);  
  27.         mav.addObject("user", user);   
  28.         return mav;    
  29.     }    
  30. }  
package com.lin.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.lin.domain.User;
import com.lin.service.UserService;

/**
 * Functional summary: User Controller
 * 
 * @author linbingwen
 * @since  2015 September 28th 2013 
 */
@Controller
public class UserController {
	@Resource
	private UserService userService;
	
	@RequestMapping("/")  
    public ModelAndView getIndex(){    
		ModelAndView mav = new ModelAndView("index"); 
		User user = userService.selectUserById(1);
	    mav.addObject("user", user); 
        return mav;  
    }  
}

(6) Final operation!
Finally, it's the result. It's all configured. We can start running as a web project!

And then all the way next


Next the console prints out the log! as follows

Print the browser and enter the address: http://localhost:8088/ssm_project/

Free download of this project

top 36 step on 1
 
 

My Similar Articles

Mybatis(12) SpringMVC(8) Spring(24)
http://blog.csdn.net More articles
Reproduced from http://blog.csdn.net/evankaka

Posted by TheDefender on Sat, 22 Dec 2018 19:36:16 -0800