准备
首先介绍一下,我的工具使用的是STS, 需要的童鞋可以到官网下载:http://spring.io/tools/sts/all
使用STS是因为她集成了Maven进行 “包“ 管理以及自带 Web server 方便部署(不用配置啦~),个人感觉还是挺方便的。如果大家想要自己配置Tomcat,也未尝不可 :)
我下载的是压缩包的STS,下载完成后解压缩 -> 启动STS.exe ->指定 workspace ->创建Maven项目 -> 选择建立 webapp 项目。 等待片刻以后,我们就可以看到STS为我们创建的项目架构如下:
引用和管理 jar 包
在这里,我们使用Maven来做 jar 包的管理(修改 Maven 的 POM 文件即可)。
这里推荐一下 Maven 仓库的网址:http://mvnrepository.com 或者 http://search.maven.org
我们只需要在上面搜索需要的jar包,将<dependency />的内容复制到POM文件中的
<dependencies>
...
</dependencies>
即可完成Jar包的引用。
我这里参照的是Spring3.x版本,比较老,希望有更新版本的童鞋给我指点一下,THX~~
POM 内容如下,这里直接贴出所有依赖包:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example.tuo</groupId> <artifactId>SpringMVC_Mybatis</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMVC_Mybatis Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.1.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>0.2.9</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.1</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.11</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.26</version> </dependency> </dependencies> <build> <finalName>SpringMVC_Mybatis</finalName> </build> </project>
Spring & Mybatis 集成
1. 首先介绍引入的几个配置文件
- config.properties -com.alibaba.druid 的数据源描述文件
jdbc_url=jdbc:mysql://localhost:3306/db_SSM?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull jdbc_username=root jdbc_password=12345
- spring-mybatis.xml - spring + mybatis 的配置文件(我将他们放到了一个文件中)
<?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:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx-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 "> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!-- 自动扫描(自动注入) --> <context:component-scan base-package="cgt.service" /> <!-- JNDI方式配置数据源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> --> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="0" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <!-- <property name="filters" value="stat" /> --> <property name="filters" value="mergeStat" /> </bean> <!-- myBatis文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 --> <property name="mapperLocations" value="classpath:cgt/mapping/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cgt.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 注解方式配置事物 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* sy.service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> <!-- 配置druid监控spring jdbc --> <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"> </bean> <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype"> <property name="patterns"> <list> <value>cgt.service.*</value> </list> </property> </bean> <aop:config> <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" /> </aop:config> </beans>
建立数据库与表
这部分很简单,我在这里放出SQL与截图,供大家参考。
我们可以看到我们建立了一个数据库 db_SSM, 一张表t_user, 里面有两个user,具体的SQL如下:
/* SQLyog 企业版 - MySQL GUI v8.14 MySQL - 5.1.49-community : Database - db_ssm ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`db_ssm` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `db_ssm`; /*Table structure for table `t_user` */ DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NAME` varchar(50) DEFAULT NULL, `PWD` varchar(50) DEFAULT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; /*Data for the table `t_user` */ insert into `t_user`(`ID`,`NAME`,`PWD`) values (1,'tony','tony'),(2,'sasha','sasha'); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
业务处理类
总的项目结构如下:
Service层
IUserService
package cgt.service; import cgt.model.User; public interface IUserService { public User getUserById(int id); }
UserService
package cgt.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cgt.dao.UserMapper; import cgt.model.User; @Service("userService") public class UserService implements IUserService{ private UserMapper userMapper; public UserMapper getUserMapper() { return userMapper; } @Autowired public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } public User getUserById(int id) { // TODO Auto-generated method stub User u=userMapper.selectById(id); return u; } }
由于我们以 Spring 自动扫描包的方式加载service,所以,在这里我们只要使用@service以及@autowired注解即可。
Dao层
UserMapper - 根据Mybatis的特点,Dao层为均为Interface,具体的实现通过类相对应的Mapper里面的SQL来体现。
package cgt.dao; import cgt.model.User; public interface UserMapper { User selectById(int id); }
Mapper层
UserMapper - 注意前缀必须与Dao的前缀相同(我这里的前缀为 user )
<?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="cgt.dao.UserMapper"> <resultMap id="BaseResultMap" type="cgt.model.User"> <id column="ID" property="id" jdbcType="INTEGER" /> <result column="NAME" property="name" jdbcType="VARCHAR" /> <result column="PWD" property="pwd" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List"> ID, NAME, PWD </sql> <select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from t_user where ID = #{id,jdbcType=VARCHAR} </select> </mapper>
Model层
User类 - POJO 类
package cgt.model; public class User { private int id; private String name; private String pwd; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public User() { super(); // TODO Auto-generated constructor stub } public User(String name, String pwd) { super(); this.name = name; this.pwd = pwd; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + "]"; } }
到这里,我们关于Spring & Mybatis 相关的业务逻辑部分就完成了。
使用 junit 编写测试代码
关于Junit test,这里介绍两种方式 :
方法一:使用 ApplicationContext 对象
package cgt.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cgt.model.User; import cgt.service.IUserService; public class SpinrgMybatisTest { @Test public void test1(){ ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml"); IUserService userService=(IUserService)ac.getBean("userService"); User u = userService.getUserById(2); System.out.println(u); } }
测试结果:
方法二: Junit 集成 Spring 的 test 方式
首先需要在POM.xml引入jar包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.0.RELEASE</version> </dependency>
Test类的写法如下:
package cgt.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cgt.model.User; import cgt.service.IUserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:spring-mybatis.xml"}) public class SpinrgMybatisTest2 { private IUserService userService; public IUserService getUserService() { return userService; } @Autowired public void setUserService(IUserService userService) { this.userService = userService; } @Test public void test2(){ User u = userService.getUserById(1); System.out.println(u); } }
测试结果:
通过 Junit 测试,我们可以看到Spring & Mybatis 的集成成功啦, nice! :)
集成SpringMVC
我们需要以SpringMVC的方式接受HTTP Request,request的URL格式我们使用的是类似于REST的格式。例如:http://localhost:8080/SpringMVC_Mybatis/userController/getUserName.do?id=1
Web.xml
她是整个程序的入口,我们需要在这里特别注意两点:
1. 以SpringMVC的方式接受request(servlet)
2. 项目需要读取哪些配置文件。
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>SpringMVC_Mybatis</display-name> <!-- 需要加载的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- 字符集过滤器 --> <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> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- spring mvc servlet --> <servlet> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 配置session超时时间,单位分钟 --> <session-config> <session-timeout>15</session-timeout> </session-config> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
Sping-mvc.xml
这里主要是 “指明” 扫描 Controller 的包下的类(与 @controller 配合)。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 --> <context:component-scan base-package="cgt.controller" /> <!-- 避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 --> </list> </property> </bean> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 --> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean> </beans>
UserController
这个类需要接受Request请求,并且转到对应的 JSP 页面
package cgt.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import cgt.service.IUserService; @Controller @RequestMapping("/userController") public class UserController { private IUserService userService; public IUserService getUserService() { return userService; } @Autowired public void setUserService(IUserService userService) { this.userService = userService; } @RequestMapping("/getUserName/{id}") public String getUserNameById(@PathVariable String id, HttpServletRequest request) { request.setAttribute("user", userService.getUserById(Integer.parseInt(id))); return "showUser"; } }
请注意这里的几个细节:
首先注解部分:
@Controller - 指明这是一个Controller类,需要被Spring管理。
@RequestMapping - 指明URL的请求路径。
@PathVariable - 与方法上面的@RequestMapping注解 中的 {id} 相结合,表示接受id作为请求的参数
方法的返回值:
返回值为 “showUser”。它与SpringMVC中的 “InternalResourceViewResolver”
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />
一同指定了返回的jsp页面为: 根目录下的showUser.jsp,如图所示:
部署程序+测试
1. Maven install
2. 使用STS内置的Server,运行起来后输入URL=http://localhost:8080/SpringMVC_Mybatis/userController/getUserName/2.do
结果如下:
Well done! 我们的集成之路顺利完成!!
结束语
lz入Java坑时间不长,所以我这里主要是参考网上的一些示例来做的集成。 因此,使用的Spring版本比较老,如果大家较新版本(Sping 4 or later)的集成,请务必推荐给我,感谢 :)