1. 程式人生 > >SSM框架(一)之SSM框架整合(Spring,SpringMVC,MyBatis)

SSM框架(一)之SSM框架整合(Spring,SpringMVC,MyBatis)

一、基本概念

最近做一個Web網站,選擇了使用SSM框架,SSM框架下的Web程式主要用到了三個技術:

1. Spring:用到了註解和自動裝配,就是Spring的兩個精髓IOC(反向控制)和 AOP(面向切面程式設計)。
2. SpringMVC:用到了MVC模型,將邏輯程式碼放到Controller層處理。
3. MyBatis:用到了與資料庫打交道的層面,放在所有的邏輯之後,處理與資料庫的CRUD相關的操作。

二、SSM框架下程式碼完成步驟

  1. 先寫實體類Entity,定義物件的屬性(可以參照資料庫中表的欄位來設定,資料庫的設計應該在所有編碼開始之前)。
  2. 寫Mapper.xml(Mybatis),其中定義你的功能,對應要對資料庫進行的那些操作,比如 insert、selectAll、selectByKey、delete、update等。
  3. 寫Dao.java,將Mapper.xml中的操作按照id對映成Java函式。
  4. 寫Service.java,為控制層提供服務,接受控制層的引數,完成相應的功能,並返回給控制層。
  5. 寫Controller.java,連線頁面請求和服務層,獲取頁面請求的引數,通過自動裝配,對映不同的URL到相應的處理函式,並獲取引數,對引數進行處理,之後傳給服務層。
  6. 寫JSP頁面呼叫,請求哪些引數,需要獲取什麼資料。

    歸納起來就是:
    DataBase ===> Entity ===> Mapper.xml ===> Dao.java ===> Service.java ===> Controller.java ===> Jsp

    三、SSM整合

    整合後完整的目錄結構如下:
    SSM整合後的目錄結構

    3.1、引入相關jar包

    將所需的jar包複製貼上到WebContent\WEB-INF\lib資料夾下面

    3.2、Spring與MyBatis的整合

    所有需要的JAR包都引入以後,首先進行Spring與MyBatis的整合,然後再進行JUnit測試

3.2.1、建立spring-mybatis.xml配置檔案

這個檔案就是用來完成spring和mybatis的整合的。這裡面也沒多少行配置,主要的就是自動掃描,自動注入,配置資料庫。註釋也很詳細,大家看看就明白了。
spring-mybatis.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 自動掃描 --> <context:component-scan base-package="com.cn.cust"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan> <!-- 配置資料來源, 整合其他框架, 事務等. --> <!-- 1. 資料來源 : DriverManagerDataSource --> <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/db_test" /> <property name="username" value="root" /> <property name="password" value="mysql" /> </bean> <!-- 2. mybatis的SqlSession的工廠: SqlSessionFactoryBean dataSource / typeAliasesPackage --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource" /> <property name="typeAliasesPackage" value="com.cn.cust.entities" /> <!-- 自動掃描 mapping.xml 檔案 --> <property name="mapperLocations" value="classpath:com/cn/cust/mapping/*.xml" /> </bean> <!-- 3. mybatis自動掃描載入Sql對映檔案 : MapperScannerConfigurer sqlSessionFactory(已過時,目前使用sqlSessionFactoryBeanName) / basePackage(介面對映檔案所在的包) --> <bean id="config" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- DAO介面所在包名,Spring會自動查詢其下的類 --> <property name="basePackage" value="com.cn.cust.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 4. 事務管理 : DataSourceTransactionManager --> <bean id="manager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="datasource" /> </bean> <!-- 5. 使用宣告式事務 --> <tx:annotation-driven transaction-manager="manager" /> <!-- 使用 import 節點匯入配置檔案 --> <!-- <import resource="blog/musicboy90/mudual/*/applicationContext-*.xml" /> --> </beans>

3.2.2、Log4j的配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug" />
    </logger>
    <logger name="org.apache.ibatis">
        <level value="debug" />
    </logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    </root>
</log4j:configuration>

3.2.3、JUnit測試

經過以上步驟(到3.2.2,log4j不配也沒影響),我們已經完成了Spring和mybatis的整合,這樣我們就可以編寫一段測試程式碼來試試是否成功了。

3.2.3.1、建立測試用表

既然我們需要測試,那麼我們就需要建立在資料庫中建立一個測試表,這個表建的很簡單,SQL語句為:

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=2 DEFAULT CHARSET=utf8;  

/*Data for the table `user_t` */  

insert  into `user_t`(`id`,`user_name`,`password`,`age`) values (1,'測試','sfasgfaf',24);  

3.2.3.2、根據資料表user_t建立實體類User

package com.cn.cust.entities;

public class User {

    private Integer id;

    private String userName;

    private String password;

    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    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 [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age + "]";
    }
}

3.2.3.3、Mapping層

<?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.cn.cust.dao.IUserDao">

    <resultMap type="User" id="userResult">
        <result column="id" property="id"></result>
        <result column="user_name" property="userName"></result>
        <result column="password" property="password"></result>
        <result column="age" property="age"></result>        
    </resultMap>

    <insert id="save" keyColumn="id" keyProperty="id" useGeneratedKeys="true">
        insert into user_t (user_name, password, age) values (#{user_name}, #{password}, #{age})
    </insert>

    <update id="update" parameterType="user">
        update user_t set user_name = #{user_name}, password = #{password}, age = #{age}
        where id = #{id}
    </update>

    <delete id="delete" parameterType="int">
        delete from user_t where id = #{id}
    </delete>

    <select id="findById" parameterType="int" resultMap="userResult">
        select * from user_t where id = #{id}
    </select>

    <select id="getAll" resultType="User">
        SELECT * FROM user_t
    </select>

</mapper>

3.2.3.4、持久層

package com.cn.cust.dao;

import java.util.ArrayList;

import com.cn.cust.entities.User;

/**
 * 
 * @author HuangMinghao 持久層,資料訪問物件
 */
public interface IUserDao { 

    void save(User user);

    void update(User user);

    void delete(int id);

    User findById(int id);

    ArrayList<User> getAll();

}

3.2.3.5、建立Service介面和實現類

IUserService.jave

package com.cn.cust.service;

import com.cn.cust.entities.User;

public interface IUserService { 
    public User getUserById(int userId);
}

UserServiceImpl.java

package com.cn.cust.serviceImpl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cn.cust.dao.IUserDao;
import com.cn.cust.entities.User;
import com.cn.cust.service.IUserService;



@Service("userService")
public class UserServiceImpl implements IUserService {

    @Resource
    private IUserDao userDao;

    @Override
    public User getUserById(int userId) {       
        return this.userDao.findById(userId);
    }

}

3.2.3.6、建立測試類

測試類在src/test/java中建立, 如果測試成功,表示 Spring 和 Mybatis 已經整合成功了 。輸出資訊使用的是 Log4j 列印到控制檯。

package com.cn.cust.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.cn.cust.entities.User;
import com.cn.cust.service.IUserService;

@RunWith(SpringJUnit4ClassRunner.class)     // 表示繼承了 SpringJUnit4ClassRunner 類
@ContextConfiguration("classpath:spring-mybatis.xml")
public class TestUser {

    @Resource   
    private IUserService userService;

    @Test
    public void testGetUserName() {
        User user = userService.getUserById(1);
        System.out.println("成功!!" + user.getUserName());
    }

}

測試結果:
這裡寫圖片描述
這裡寫圖片描述

至此, 完成Spring和mybatis這兩大框架的整合 ,下面在繼續進行SpringMVC的整合。

3.3、整合SpringMVC

上面已經完成了2大框架的整合,SpringMVC的配置檔案單獨放,然後在web.xml中配置整合

3.3.1、配置spring-mvc.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: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.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自動掃描該包,使SpringMVC認為包下用了@controller註解的類是控制器 -->
    <context:component-scan base-package="com.cn.hnust.controller" />

    <!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的對映 -->
    <context:component-scan base-package="com.cn.cust"
        use-default-filters="false">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:include-filter type="annotation"
            expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </context:component-scan>

    <!-- 定義跳轉的檔案的前後綴 ,檢視模式配置 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 這裡的配置我的理解是自動給後面action的方法return的字串加上字首和字尾,變成一個 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:default-servlet-handler />

    <mvc:annotation-driven />

</beans>

3.3.2、配置web.xml檔案

這裡面對spring-mybatis.xml的引入以及配置的spring-mvc的Servlet就是為了完成SSM整合,之前2框架整合不需要在此處進行任何配置。配置一樣有詳細註釋,不多解釋了。
web.xml

<?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_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Text</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 和  mybatis 的配置檔案 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mybatis.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>

    <!-- Spring MVC servlet -->
    <servlet>
        <servlet-name>springDispatcherServlet</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>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 編碼過濾器 -->
    <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>

    <!-- 配置 HiddenHttpMethodFilter : 把 Post 請求轉化為 DELETE,PUT請求 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

3.3.3、測試
至此已經完成了SSM三大框架的整合了,接下來測試一下,如果成功了,那麼恭喜你,如果失敗了,繼續除錯吧, 作為程式設計師就是不停的與BUG做鬥爭 !
3.3.3.1、新建jsp頁面
showUser.jsp 此頁面僅輸出一下使用者名稱,完成一個 完整的簡單流程 。

<%@ 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>測試</title>
</head>
<body>
    ${user.userName}
</body>
</html>

3.3.3.2、建立UserController類

UserController.java 控制器

package com.cn.cust.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cn.cust.entities.User;
import com.cn.cust.service.IUserService;

/**
 * 引數傳遞,最簡單的DEMO
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @RequestMapping("/showUser")
    public String toIndex(HttpServletRequest request,Model model) {
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = this.userService.getUserById(userId);
        model.addAttribute("user",user);
        return "showUser";
    }

}

3.3.3.3、部署專案

輸入地址: localhost:8080/ 專案名稱 /user/showUser?id=1
這裡寫圖片描述
至此,SSM三大框架的整合就完成了,在此基礎上可再新增其他功能。

4、原始碼下載地址: