【ssm整合教程】spring4.0.2+springMVC4.0.2+mybatis3.2.6集成

原文地址为: 【ssm整合教程】spring4.0.2+springMVC4.0.2+mybatis3.2.6集成

spring、springMVC和mybatis的集成




1、  关于三大框架的介绍我在这就不多说了,既然要学三大框架的集成,那说明已经掌握了他们各自的用法了并能够单独使用了,下面我来讲一下三大框架的集成

     1.1   其实ssm的集成比ssh的集成简单很多,spring和springMVC的无缝结合给我们省了很多配置,首先我们创一个web项目,我这里用的是myeclipes没有用maven搭建,然后导入项目所需jar包,关于jar的话,spring和springMVC并不需要额外的jar包,只需要额外加入mybatis-spring.jar包,该包由mybatis提供,关于jar包在此不做跟多的说明。

下面给出本项目所用的spring4.0.2的jar包下载连接:http://download.csdn.net/detail/hing2008/6940551

mybatis3.2.6+mybatis-spring1.2.2 的链接 :http://download.csdn.net/detail/aaa5438438/9586717


     1.2  首先我们在项目中配置如下目录结构,为了之后配置文件中配置和最后的测试, 再在项目中创建一个与src同级的包,在这个包下的文件在发布时也是在classes文件夹下和放在src目录下没有区别,这样做是为了方便配置,得到的结构如下图:


图 1.1

2、  接下来我们要在在config包下书写配置文件

    2.1  首先我们先配置一下我们连接数据库所需文件,在config包下创建jdbc.properties文件如下图:



图1.2

    2.2  然后我们创建一个springmvc.xml文件(三个框架整合没有它什么事,先配了再说),这个配置文件只负责生成各种handler,映射路径什么的,为了管理起来更加轻松我把spring和springmvc的配置文件都放在config/spring目录下


<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!--自动扫描,里面填你的controller所在的包 -->
<context:component-scan base-package="com.ssm.controller"/>

<!-- 处理静态资源 和解放MVC的原有功能-->
<mvc:default-servlet-handler/>
<mvc:annotation-driven> </mvc:annotation-driven>

<!--文件上传配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>

<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/"/>
<property name="suffix" value=".jsp" />
</bean>


</beans>

    2.2  然后我们来配一下spring和mybatis整合文件applicationContext-dao.xml

<?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"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">


<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />

<!-- 连接池最大数量 -->
<property name="maxActive" value="30"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="5"></property>

</bean>

<!--spring与mybatis整合-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<!--
<property name="mapperLocations" value="classpath:com/ssm/mapping/*.xml"></property>
-->
<!-- 全局配置 -->
<!-- 若不保留mybatis配置文件用上面那条替换这一条 -->
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"/>
</bean>

<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描包路径,需要扫描多个包中间用逗号隔开 -->
<property name="basePackage" value="com.ssm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

</beans>

  2.3  然后我们在配一下事务的文件applicationContext-transaction.xml,这个文件其实可以和上面一个文件写在一起,为了跟简单的管理配置,我把他写开了

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--
数据源dataSource在applicationContext-dao.xml中配置了
-->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 启用事务 -->
<tx:annotation-driven transaction-manager="transactionmanager" />
</beans>

  2.4 下一步是配置业务层的文件applicationContext-services.xml,这个文件也可以直接写在applicationContext-dao.xml中,为了。。。。。同上

<?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"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.ssm.service.impl"/>
</beans>

   2.5  最后我们再配置mybatis的配置文件sqlMapConfig.xml如果你在applicationContext-dao.xml中没有采用全局配置,这个文件就可以不用写,当然在这里我们还是要写的

<?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>


<mappers>
<!-- 注册userMapper.xml文件 -->
<mapper resource="com/ssm/mapping/UserMapper.xml"/>

</mappers>
</configuration>

             自此我们三大框架集成所要配的容器文件配置完了,我们应该有如下目录结构



 2.6   最后一步,在web.xml文件中配置spring和springmvc的容器,就是上面的那些配置文件

<?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"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
    version="3.0">  
    <display-name>Archetype Created Web Application</display-name>  
    
    <!-- Spring容器和mybatis的配置文件 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>  
    </context-param>    
    <!-- Spring监听器 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <!-- 防止Spring内存溢出监听器 -->  
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  
 
    <!-- 加载springMVC容器 -->  
    <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/springmvc.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
        <async-supported>true</async-supported>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVC</servlet-name>  
        <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>
    
    <!-- 编码过滤器 -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <async-supported>true</async-supported>  
        <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>
      
    <welcome-file-list>  
        <welcome-file>/index.jsp</welcome-file>  
    </welcome-file-list>  
 
</web-app>  



好了,到这里我们是真的真的配完了。。。。

3、  测试集成是否成功

 3.1、 在数据库中创建表user_t

/*
Navicat MySQL Data Transfer

Source Server : localhost_3306
Source Server Version : 50536
Source Host : localhost:3306
Source Database : ssm

Target Server Type : MYSQL
Target Server Version : 50536
File Encoding : 65001

Date: 2016-07-26 10:30:37
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user_t
-- ----------------------------
DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(40) NOT NULL,
`password` varchar(255) NOT NULL,
`age` int(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=202 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user_t
-- ----------------------------
INSERT INTO `user_t` VALUES ('2', '测试1', '123456', '18');
INSERT INTO `user_t` VALUES ('3', '测试1', '123456', '18');
INSERT INTO `user_t` VALUES ('4', '测试1', '123456', '18');
INSERT INTO `user_t` VALUES ('5', '测试1', '123456', '18');
INSERT INTO `user_t` VALUES ('6', '测试1', '123456', '18');
INSERT INTO `user_t` VALUES ('7', '测试1', '123456', '18');
INSERT INTO `user_t` VALUES ('8', '测试1', '123456', '18');
INSERT INTO `user_t` VALUES ('9', '测试1', '123456', '18');
INSERT INTO `user_t` VALUES ('10', '测试1', '123456', '18');


   3.2在com.ssm.pojo创建User类

package com.ssm.pojo;

public class User {
private Integer userid;
private String username;
private String password;
private Integer age;

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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User [userid=" + userid + ", username=" + username
+ ", password=" + password + ", age=" + age + "]";
}

}

    3.3 创建Usermapper.xml和UserDao接口

           UserMapper.xml

<?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.ssm.dao.UserDao" >

<resultMap id="userMap" type="com.ssm.pojo.User">
<id column="id" property="userid" jdbcType="INTEGER"/>
<result column="user_name" property="username" jdbcType="VARCHAR"/>
<result column="password" property="password" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
</resultMap>
<!-- 查询所有 -->
<select id="getAll" resultMap="userMap">
select * from user_t
</select>
</mapper>
          UserDao.java
package com.ssm.dao;import java.util.List;import com.ssm.pojo.User;public interface UserDao {	public List<User> getAll();}

         3.3创建UserService 和UserServiceImp

           UserService.java

package com.ssm.service;

import java.util.List;


import com.ssm.pojo.User;

public interface UserService {
public List<User> getAll();
}

        UserServiceImp.java

package com.ssm.service.impl;

import java.util.List;

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

import com.ssm.dao.UserDao;
import com.ssm.pojo.User;
import com.ssm.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
public List<User> getAll() {
// TODO Auto-generated method stub
return userDao.getAll();
}

}

     3.4 创建控制层UserController.java

package com.ssm.controller;

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

import com.ssm.service.UserService;



@Controller
public class UserController {
<span><span class="annotation">@Autowired</span></span>
  private UserService userService;
@RequestMapping("/getAll")
public ModelAndView getAll(ModelAndView mv){
mv.addObject("userList", userService.getAll());
mv.setViewName("list");
return mv;
}
}

 3.4在WEB-INF/jsps/下创建list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>userList</title>

</head>

<body>
<table border="2" align="center">
      <tr>
          <th>ID</th>
          <th>用户名</th>
          <th>密码</th>
          <th>年龄</th>
      </tr>
    <c:forEach items="${requestScope.userList}" var="user">
        <tr>
            <td>${user.userid}</td>
            <td>${user.username}</td>
            <td>${user.password}</td>
            <td>${user.age}</td>
        <tr>
    </c:forEach>   
  </table>
</body>
</html>

4、 测试,测试之前记得改下数据库密码,在地址栏输入:http://localhost:8080/ssmtest/getAll

若出现下图,恭喜




若没有,继续努力吧,累死了。。。。。。


                                                                                        转载请注明出处:http://blog.csdn.net/aaa5438438



          



转载请注明本文地址: 【ssm整合教程】spring4.0.2+springMVC4.0.2+mybatis3.2.6集成
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值