Spring学习笔记----三大框架(Spring+SpringMVC+MyBatis)整合详细教程

下面的过程中我还没有使用Maven,在后面的学习过程中我会补上,此外,下面在整合的过程中我总会碰到路径的问题,所以将有的配置文件直接放在了src目录下,有的在放在了WEB-INF的目录下,下面列举一下所有的配置文件。

spring.xml(applicationContext.xml)--------------------spring配置文件
spring-mybatis.xml------------------------------------MyBatis配置文件
generatorConfig.xml-----------------------------------MyBatis Generator自动创建代码配置文件

spring-MVC.xml(springMVC.xml)-------------------------SpringMVC配置文件
web.xml-----------------------------------------------SpringMVC配置文件

log4j.properties--------------------------------------Log4j配置文件
jdbc.properties---------------------------------------数据源配置文件

上述的配置文件存放的位置很容易发生找不到文件的错误,所以一定要注意,后面我会继续整理配置文件的存放位置。
下面是我整合完成后文件的目录,感觉有点乱



1、Spring

Spring是一个开源框架,Spring是一个轻量级的Java开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来,它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只有可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。简单的来说,Spring是一个轻量级的
控制反转(IoC)和面向切面(AOP)的容器框架。

2、SpringMVC

SpringMVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面,Spring MVC分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

3、MyBatis

MyBatis本来是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code ,并且改名为MyBatis。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Object(DAO)MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis使用简单XML或注解用于配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射数据库
中的记录。

4、SSM整合 

4.1  Spring与Mybatis的整合

所有的jar包都引入后,先将spring和MyBatris整合,然后写了个单元测试。

4.1.1、建立JDBC属性文件(设置属性为utf-8)

jdbc.properties

<span style="font-family:Comic Sans MS;">driverClassName=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=scott
password=123</span>

起初我设置了包括下面的属性,但是发现出现了问题,我直接选择了将下面的属性去掉。这个问题我在后面会进一步的解决掉

#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

4.1.2、建立spring-mybatis.xml配置文件

<span style="font-family:Comic Sans MS;"><?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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	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-2.5.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 自动扫描 -->
	
	<context:component-scan base-package="com.ssm.www"></context:component-scan>

	<!-- 引入配置文件 --><!-- 一般的Properties都是放在class的path下面,发布项目后,WEB-INF的目录很深的,不能直接的找到的, -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties"></property>
	</bean>

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
		<!-- <property name="driverClassName" value="${driverClassName}"></property>
		<property name="url" value="${url}"></property>
		<property name="username" value="${username}"></property>
		<property name="password" value="${password}"></property>
		 -->
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
		<property name="username" value="scott" />
		<property name="password" value="123" />
		<!-- 初始化连接大小 -->
		<!-- <property name="initialSize" value="${initialSize}"></property> -->
		<!-- 连接池最大数量 -->
		<!-- <property name="maxActive" value="${maxActive}"></property>
		连接池最大空闲
		<property name="maxIdle" value="${maxIdle}"></property>
		连接池最小空闲
		<property name="minIdle" value="${minIdle}"></property>
		连接池最大等待时间
		<property name="maxWait" value="${maxWait}"></property> -->
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<!-- 自动扫描mapping.xml文件 省略configuration。xml里手工配置 -->
		<!-- 手工配置如下 -->
		<!-- <property name="configLocation" value="classpath:sqlmap-config.xml" 
			/> -->

		<!-- 比如说Student类的sql语句文件StudentMapper.xml 即为sql映射语句文件 -->
		<property name="mapperLocations" value="classpath:com/ssm/www/mapping/*.xml"></property>
	</bean>

	<!-- DAO接口即Mapper接口所在的包,Spring会自动查找其其下的Mapper 即DAO -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.ssm.www.dao"></property>
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
	<!-- 事物管理 transaction manager,use JtaTransactionManager for global ts -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- <bean id="userService" class="com.ssm.www.service.impl.IUserServiceImpl">
	<property name="sqlSessionFactory" ref="sqlSessionFactory"></property> 
	</bean>-->
</beans></span>

在这个配置文件里面,我碰到的最大的问题就是路径的问题。比如说value="classpath:jdbc.properties",最开始我是放在WEB-INF目录下面,但是后来运行时一直说找不到文件,在网上找了很久,发现有人说一般的Properties都是放在class的path下面,发布项目后,WEB-INF的目录很深的,不能直接的找到的所以我选择了直接将所有的配置文件放在src目录下面,这里也是我需要改进的地方。


4.1.3、Log4j的配置

之前我也简单的学习了一下Log4j,Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件、甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
下面是我的基本配置,我之前写过一点关于Log4j的应用,下面是我的网址
http://blog.csdn.net/cwzhsi/article/details/41926467
还有转载的一篇Log4j使用的文章
http://blog.csdn.net/zhshulin/article/details/37937365


<span style="font-family:Comic Sans MS;">log4j.properties
#定义LOG输出级别
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=%-4r %-5p [%t] %37c %3x -%m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File=org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File=E:WorkSpace/logs/errors.log
#定义文件最大大小
log4j.appender.File.MaxFileSize=10MB
#输出所有日志,如果换成DEBUG表示输出DEBUG以上级别日志
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</span>

4.1.4、Junit测试

上面基本完成了Spring和MyBatis的配置,下面来进行一个具体的测试。

4.1.4.1、创建测试用表

我之前就在oracle中创建了TD表,表的创建步骤之前也已经介绍过,这里就不再详述了。

4.1.4.2、利用MyBatis Generator

这个可根据表自动创建实体类,MyBatis映射文件及DAO接口,一般都习惯性的将接口改名为IUserDao,而不是直接用它生成的UserMapper,注意,这一步改了之后,千万要记得MyBatis映射文件也要改,我就是之前忘了改然后一直不知道哪里报错了。关于MyBatis Generator的具体实现可以看看我的另一篇博文
 http://blog.csdn.net/cwzhsi/article/details/42041087

下面是生成目录图如下:



4.1.4.3、建立service接口和实现类

下面是我的具体的内容:

IUserService.java

<span style="font-family:Comic Sans MS;">public interface IUserService {
    public User getUserById(BigDecimal userId);
    public String addUser(User user);
}</span>
IUserSerivceImpl.java

<span style="font-family:Comic Sans MS;">@Service("userService")
public class IUserServiceImpl implements IUserService{
	private IUserDao userDao;
	@Autowired
	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}
	@Override
	public User getUserById(BigDecimal userId) {
		return this.userDao.selectByPrimaryKey(userId);
	}
	@Override
	public String addUser(User user) {
		System.out.println("zhsi");
		userDao.insert(user);
		return "success";
	}
}</span>
这里我使用了自动注解的功能,这样在注入时就不用在配置文件中进行设置了,不过也要注意这里的实现,这一步我也调试了很久主要是对注解的使用还不是很熟练。

4.1.4.4 建立测试类

<span style="font-family:Comic Sans MS;">@ContextConfiguration(locations={"spring-mybatis.xml","applicationContext.xml"})
public class SpringTest {
	private static Logger logger=Logger.getLogger(SpringTest.class);
	@Resource
	private IUserService userService;
	@Before
	public void before(){
		ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"classpath:spring-mybatis.xml","classpath:applicationContext.xml"});
		userService =(IUserService) context.getBean("userService");
		PropertyConfigurator
		.configure(".//WebContent/WEB-INF/cfg/log4j.properties");
	}
	@Test
	public void test() {
		User user=new User();
		user.setUserName("mama");
		user.setPassword("789");
		user.setAge(new BigDecimal(21));
		logger.info(userService.addUser(user));
	}
}</span>
测试结果如下:


上面的方式实现了Spring和MyBatis的整合,输出的信息使用的是Log4j打印到控制台。

这里我碰到了一个问题,就是使用注解的方式来引入配置文件和类,然后将service接口对象注入,但是这里我一直出现了空指针错误,找不到userService类。

哇塞,我终于解决问题了!

下面的测试类如下:

<span style="font-family:Comic Sans MS;">@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mybatis.xml","classpath:applicationContext.xml"})
public class SpringTest {
	private static Logger logger=Logger.getLogger(SpringTest.class);
	/**
	 * @Resource按名称注入(不需要setter方法了),@Autowired按类型注入
	 */
	@Resource
	private IUserService userService;
	@Autowired
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	/*@Before
	public void before(){
		ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"classpath:spring-mybatis.xml","classpath:applicationContext.xml"});
		userService =(IUserService) context.getBean("userService");
		PropertyConfigurator
		.configure(".//WebContent/WEB-INF/cfg/log4j.properties");
	}*/
	
	@Test
	public void test() {
		PropertyConfigurator
		.configure(".//WebContent/WEB-INF/cfg/log4j.properties");
		User user=new User();
		user.setUserName("baba");
		user.setPassword("222");
		user.setAge(new BigDecimal(21));
		logger.info(userService.addUser(user));
	}
}</span>

现在不需要执行@Before里面的内容了,因为我加上了@RunWith(SpringJUnit4ClassRunner.class),现在就不会报service空指针错了,在网上看了一下,原因是说在使用所有注解前必须使用@RunWith(SpringJUnit4ClassRunner.class),让测试运行与Spring测试环境Spring框架在org.springframework.test.annotation包中提供了常用的Spring特定注解集。

这个问题整了我一天了,多谢师姐过来给我指点一下,太高兴了!

4.2、整合SpringMVC

SpringMVC的配置文件包括web.xml 和 springMVC.xml  这两个配置文件存放在WEB-INF目录下面

4.2.1、配置springMVC.xml文件(一般是spring-mvc.xml,我将其的名字改为了springMVC.xml)

该配置文件主要是自动扫描控制器、视图模式、注解的启动这三个。配置文件如下:

<span style="font-family:Comic Sans MS;"><?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	default-lazy-init="true"
	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  ">
	<!-- <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="ssm.do">ssm</prop>
			</props>
		</property>
	</bean> -->

	<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->

    <context:component-scan base-package="com.ssm.www.controller"></context:component-scan>
    <!-- 支持spring mvc新的注解类型 详细spring3.0手册 15.12.1 mvc:annotation-driven -->
	<mvc:annotation-driven />
	<context:annotation-config />
	
	<!-- 避免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>

	<!-- 啟動SpringMVC的注解功能,完成請求和注解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">
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<!-- 配置文件上传,如果没有使用文件上传可以不用配置,但不配的时候配置文件中也不必引入上传组件包 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 默认编码 -->
		<property name="defaultEncoding" value="utf-8"></property>
		<!-- 文件大小最大值 -->
		<property name="maxUploadSize" value="10485760000"></property>
		<property name="maxInMemorySize" value="40960"></property>
	</bean>

</beans></span>

配置文件中都有注释,我就不再详细介绍了。

4.2.2、配置web.xml文件

在这里对spring-mybatis.xml和配置文件springMVC.xml进行的引入就是完成了对SSM框架的整合。

web.xml

<span style="font-family:Comic Sans MS;"><?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>SSM_1</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<!-- spring(这里我是application.xml)和mybatis配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mybatis.xml,classpath:applicationContext.xml</param-value>
	</context-param>

	<!-- 加载log4j配置文件 -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</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></span>

4.2.3、创建一个简单的JSP显示文件

showUser.jsp  此页面仅输出一下用户名

<span style="font-family:Comic Sans MS;"><%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ssm Test</title>
</head>
   <body>
    ${user.userName}
   </body>
</html></span>


4.2.4、建立UserController类

UserController.java

<span style="font-family:Comic Sans MS;">@Controller
@RequestMapping("/user")
public class UserController {
	private static Logger logger=Logger.getLogger(SpringTest.class);
	@Resource
	private IUserService userService;
	@RequestMapping("/addUser")
	public String addUser(HttpServletRequest request,Model model){
		//PropertyConfigurator.configure(".//WebContent/WEB-INF/cfg/log4j.properties");
		User user=new User();
		user.setUserName("weiwei");
		user.setPassword("333");
		user.setAge(new BigDecimal(21));
		userService.addUser(user);
		model.addAttribute("user", user);
		return "showUser";
	}
	@RequestMapping("/getUser")
	public String getUser(HttpServletRequest request,Model model){
		int userId=Integer.parseInt(request.getParameter("id"));
		User user=this.userService.getUserById(new BigDecimal(userId));
		model.addAttribute("user", user);
		return "showUser";
	}
}	</span>

4.2.5、部署项目

addUser方法被调用时,输入地址:http://localhost:8080/SSM_1/user/addUser
getUser方法被调用时,输入地址:http://localhost:8080/SSM_1/user/getUser?id=107

至此,SSM三大框架简单的整合就基本完成了,虽然是我是模仿的别人的例子,但是在整合的过程中通过碰到问题、解决问题这样反复折腾的
过程,我学习了很多,对框架整合的流程也基本上算是了解了,后面再进一步的学习吧。



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值