【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



          


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章