参考文档:http://blog.csdn.net/zhshulin/article/details/37956105
1.搭建maven工程,具体参见我另一篇博客:http://www.cnblogs.com/kangyun/p/5455108.html
进行到配置web.xml之前那一步就可以了
2.maven导入依赖,我的pom.xml文件的依赖如下所示:
1 <dependencies> 2 <dependency> 3 <groupId>junit</groupId> 4 <artifactId>junit</artifactId> 5 <version>3.8.1</version> 6 <scope>test</scope> 7 </dependency> 8 <dependency> 9 <groupId>org.springframework</groupId> 10 <artifactId>spring-aop</artifactId> 11 <version>4.2.4.RELEASE</version> 12 </dependency> 13 <dependency> 14 <groupId>org.springframework</groupId> 15 <artifactId>spring-context-support</artifactId> 16 <version>4.2.4.RELEASE</version> 17 </dependency> 18 <dependency> 19 <groupId>org.springframework</groupId> 20 <artifactId>spring-core</artifactId> 21 <version>4.2.4.RELEASE</version> 22 </dependency> 23 <dependency> 24 <groupId>org.springframework</groupId> 25 <artifactId>spring-oxm</artifactId> 26 <version>3.0.4.RELEASE</version> 27 </dependency> 28 <dependency> 29 <groupId>org.springframework</groupId> 30 <artifactId>spring-jdbc</artifactId> 31 <version>4.2.4.RELEASE</version> 32 </dependency> 33 <dependency> 34 <groupId>org.springframework</groupId> 35 <artifactId>spring-test</artifactId> 36 <version>4.2.4.RELEASE</version> 37 </dependency> 38 <dependency> 39 <groupId>org.springframework</groupId> 40 <artifactId>spring-web</artifactId> 41 <version>4.2.4.RELEASE</version> 42 </dependency> 43 <dependency> 44 <groupId>org.springframework</groupId> 45 <artifactId>spring-webmvc</artifactId> 46 <version>4.2.4.RELEASE</version> 47 </dependency> 48 <dependency> 49 <groupId>org.springframework</groupId> 50 <artifactId>spring-tx</artifactId> 51 <version>4.2.4.RELEASE</version> 52 </dependency> 53 <dependency> 54 <groupId>org.mybatis</groupId> 55 <artifactId>mybatis</artifactId> 56 <version>3.3.0</version> 57 </dependency> 58 <dependency> 59 <groupId>org.mybatis</groupId> 60 <artifactId>mybatis-spring</artifactId> 61 <version>1.2.3</version> 62 </dependency> 63 <dependency> 64 <groupId>javax</groupId> 65 <artifactId>javaee-api</artifactId> 66 <version>7.0</version> 67 </dependency> 68 <dependency> 69 <groupId>mysql</groupId> 70 <artifactId>mysql-connector-java</artifactId> 71 <version>5.1.38</version> 72 </dependency> 73 <dependency> 74 <groupId>commons-dbcp</groupId> 75 <artifactId>commons-dbcp</artifactId> 76 <version>1.4</version> 77 </dependency> 78 <dependency> 79 <groupId>jstl</groupId> 80 <artifactId>jstl</artifactId> 81 <version>1.2</version> 82 </dependency> 83 <dependency> 84 <groupId>log4j</groupId> 85 <artifactId>log4j</artifactId> 86 <version>1.2.14</version> 87 </dependency> 88 <dependency> 89 <groupId>com.alibaba</groupId> 90 <artifactId>fastjson</artifactId> 91 <version>1.2.7</version> 92 </dependency> 93 <dependency> 94 <groupId>org.slf4j</groupId> 95 <artifactId>slf4j-api</artifactId> 96 <version>1.7.5</version> 97 </dependency> 98 <dependency> 99 <groupId>org.slf4j</groupId> 100 <artifactId>slf4j-log4j12</artifactId> 101 <version>1.7.5</version> 102 </dependency> 103 <dependency> 104 <groupId>org.codehaus.jackson</groupId> 105 <artifactId>jackson-mapper-asl</artifactId> 106 <version>1.9.13</version> 107 </dependency> 108 </dependencies>
pom.xml 依赖部分
2.整合mybatis
首先配置数据库连接配置文件,在src/main/resources下创建文件:jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_test
username=root
password=
initialSize=0
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000
依然是在该目录下,创建spring-mybatis.xml文件
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:p="http://www.springframework.org/schema/p" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-3.1.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 12 <!-- 自动扫描 --> 13 <context:component-scan base-package="com.practice.prac" /> 14 <!-- 引入配置文件 --> 15 <bean id="propertyConfigurer" 16 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 17 <property name="location" value="classpath:jdbc.properties" /> 18 </bean> 19 20 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 21 destroy-method="close"> 22 <property name="driverClassName" value="${driver}" /> 23 <property name="url" value="${url}" /> 24 <property name="username" value="${username}" /> 25 <property name="password" value="${password}" /> 26 <!-- 初始化连接大小 --> 27 <property name="initialSize" value="${initialSize}"></property> 28 <!-- 连接池最大数量 --> 29 <property name="maxActive" value="${maxActive}"></property> 30 <!-- 连接池最大空闲 --> 31 <property name="maxIdle" value="${maxIdle}"></property> 32 <!-- 连接池最小空闲 --> 33 <property name="minIdle" value="${minIdle}"></property> 34 <!-- 获取连接最大等待时间 --> 35 <property name="maxWait" value="${maxWait}"></property> 36 </bean> 37 38 <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> 39 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 40 <property name="dataSource" ref="dataSource" /> 41 <!-- 自动扫描mapping.xml文件 --> 42 <property name="mapperLocations" value="classpath:com/practice/prac/mapping/*.xml"></property> 43 </bean> 44 45 <!-- DAO接口所在包名,Spring会自动查找其下的类 --> 46 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 47 <property name="basePackage" value="com.practice.prac.dao" /> 48 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> 49 </bean> 50 51 <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> 52 <bean id="transactionManager" 53 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 54 <property name="dataSource" ref="dataSource" /> 55 </bean> 56 57 </beans>
spring-mybatis.xml
配置log4j,依然在该目录下,创建log4j.properties
log4j.rootLogger=INFO,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
log4j.appender.File = org.apache.log4j.RollingFileAppender
log4j.appender.File.File = logs/ssm.log
log4j.appender.File.MaxFileSize = 10MB
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
以上就是mybatis的全部配置,为了验证,我们现在使用junit测试后台部分。
首先创建数据表:
1 CREATE TABLE `user_t` ( 2 `id` int(11) NOT NULL AUTO_INCREMENT, 3 `user_name` varchar(40) NOT NULL, 4 `password` varchar(255) NOT NULL, 5 `age` int(4) NOT NULL, 6 PRIMARY KEY (`id`) 7 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; 8 9 /*Data for the table `user_t` */ 10 11 insert into `user_t`(`id`,`user_name`,`password`,`age`) values (1,‘测试‘,‘sfasgfaf‘,24);
sql
然后配置mybatis-generator自动创建代码,参考这篇博客:
自动创建dao、mapper和model之后,自己写service接口和serviceImpl:
1 package com.practice.prac.service; 2 3 import com.practice.prac.model.User; 4 5 public interface IUserService { 6 public User getUserById(int userId); 7 }
IUserService
1 package com.practice.prac.service.Impl; 2 3 import javax.annotation.Resource; 4 5 import org.springframework.stereotype.Service; 6 7 import com.practice.prac.dao.UserMapper; 8 import com.practice.prac.model.User; 9 import com.practice.prac.service.IUserService; 10 11 @Service("userService") 12 public class UserServiceImpl implements IUserService{ 13 14 @Resource 15 private UserMapper userMapper; 16 17 @Override 18 public User getUserById(int userId) { 19 20 return userMapper.selectByPrimaryKey(userId); 21 } 22 23 }
UserServiceImpl
然后在src/test/java目录下创建包:com.practice/prac/service/Impl
在该目录下创建测试文件:
1 package com.practice.prac.service.Impl; 2 3 import javax.annotation.Resource; 4 5 import org.apache.log4j.Logger; 6 import org.junit.Test; 7 import org.junit.runner.RunWith; 8 import org.springframework.test.context.ContextConfiguration; 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 10 11 import com.alibaba.fastjson.JSON; 12 import com.practice.prac.model.User; 13 import com.practice.prac.service.IUserService; 14 15 @RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类 16 @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"}) 17 18 public class TestMyBatis { 19 private static Logger logger = Logger.getLogger(TestMyBatis.class); 20 @Resource 21 private IUserService userService = null; 22 @Test 23 public void test1() { 24 User user = userService.getUserById(1); 25 logger.info(JSON.toJSONString(user)); 26 } 27 }
TestMyBatis
右键测试文件,run as junit 测试成功
至此,mybatis整合成功。
3.整合springMVC
在src/main/resources目录下创建文件spring-servlet.xml
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:p="http://www.springframework.org/schema/p" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-3.1.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 12 13 <mvc:annotation-driven /> 14 15 <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> 16 <context:component-scan base-package="com.practice.prac.controller" /> 17 18 <!-- 定义跳转的文件的前后缀 ,视图模式配置--> 19 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 20 <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> 21 <property name="prefix" value="/WEB-INF/view/" /> 22 <property name="suffix" value=".jsp" /> 23 </bean> 24 </beans>
spring-servlet.xml
ps:原博客这里有问题,启动后访问不了controller,加了<mvc:annotation-driven />这句后才能使用,其他地方也做了一些修改,主要是去掉了jackson的配置,因为原博是3.x的springmvc框架,我这里是4.x的,因此jackson报错,只好删掉
然后配置web.xml
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" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 5 version="3.0"> 6 <display-name>Archetype Created Web Application</display-name> 7 <!-- Spring和mybatis的配置文件 --> 8 <context-param> 9 <param-name>contextConfigLocation</param-name> 10 <param-value>classpath:spring-mybatis.xml</param-value> 11 </context-param> 12 <!-- 编码过滤器 --> 13 <filter> 14 <filter-name>encodingFilter</filter-name> 15 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 16 <async-supported>true</async-supported> 17 <init-param> 18 <param-name>encoding</param-name> 19 <param-value>UTF-8</param-value> 20 </init-param> 21 </filter> 22 <filter-mapping> 23 <filter-name>encodingFilter</filter-name> 24 <url-pattern>/*</url-pattern> 25 </filter-mapping> 26 <!-- Spring监听器 --> 27 <listener> 28 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 29 </listener> 30 <!-- 防止Spring内存溢出监听器 --> 31 <listener> 32 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> 33 </listener> 34 35 <!-- Spring MVC servlet --> 36 <servlet> 37 <servlet-name>SpringMVC</servlet-name> 38 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 39 <init-param> 40 <param-name>contextConfigLocation</param-name> 41 <param-value>classpath:spring-servlet.xml</param-value> 42 </init-param> 43 <load-on-startup>1</load-on-startup> 44 <async-supported>true</async-supported> 45 </servlet> 46 <servlet-mapping> 47 <servlet-name>SpringMVC</servlet-name> 48 <url-pattern>/</url-pattern> 49 </servlet-mapping> 50 51 </web-app>
web.xml
这样就整合完成了,下面创建一个jsp页面和一个controller来验证:
1 package com.practice.prac.controller; 2 3 import javax.annotation.Resource; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 7 import org.springframework.ui.ModelMap; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.RequestMethod; 10 import org.springframework.web.bind.annotation.RestController; 11 import org.springframework.web.servlet.ModelAndView; 12 13 import com.practice.prac.model.User; 14 import com.practice.prac.service.IUserService; 15 16 @RestController 17 @RequestMapping(value = "show/") 18 public class TestController { 19 @Resource 20 private IUserService userService; 21 22 @RequestMapping(value = "/index", method = RequestMethod.GET) 23 public ModelAndView showIndex(HttpServletRequest request,HttpServletResponse response){ 24 ModelMap modelMap = new ModelMap(); 25 User user = userService.getUserById(1); 26 modelMap.put("user", user); 27 return new ModelAndView("/index",modelMap); 28 } 29 }
TestController
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <title>测试</title> 7 </head> 8 9 <body> 10 ${user.userName} 11 </body> 12 </html>
index.jsp
把项目放到tomcat下运行,在浏览器中输入:http://localhost:8080/prac/show/index
整合成功!
最后贴出项目目录: