本教程源碼請訪問:tutorial_demo SSM整合可以使用多種方式,我們採用XML+註解的方式 SSM的整體思路:整合Spring和SpringMVC,整合Spring和MyBatis,兩兩整合。 一、環境準備 1.1、建庫建表 DROP DATABASE IF EXISTS ssm; CRE ...
本教程源碼請訪問:tutorial_demo
SSM整合可以使用多種方式,我們採用XML+註解的方式
SSM的整體思路:整合Spring和SpringMVC,整合Spring和MyBatis,兩兩整合。
一、環境準備
1.1、建庫建表
DROP DATABASE IF EXISTS ssm;
CREATE DATABASE ssm;
USE ssm;
DROP TABLE IF EXISTS account;
CREATE TABLE account (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(40) DEFAULT NULL,
money float DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4;
INSERT INTO account VALUES ('1', 'Tom', '1999');
INSERT INTO account VALUES ('2', 'Bob', '2000');
INSERT INTO account VALUES ('3', 'Peter', '10000');
INSERT INTO account VALUES ('5', 'John', '9700');
INSERT INTO account VALUES ('6', 'Smith', '421315');
INSERT INTO account VALUES ('7', 'Rose', '8800000');
1.2、創建Maven工程
在idea中從原型創建Maven工程,選擇org.apache.maven.archetypes:maven-archetype-webapp
,在pom.xml中添加如下的坐標:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<!-- Spring和MyBatis整合的jar包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- JSP -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
1.3、創建實體類
package org.codeaction.bean;
/**
* 表示賬戶的實體類
*/
public class Account {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
1.4、創建持久層介面
package org.codeaction.dao;
import org.codeaction.bean.Account;
import java.util.List;
public interface IAccountDao {
List<Account> findAll();
}
1.5、創建業務層介面
package org.codeaction.service;
import org.codeaction.bean.Account;
import java.util.List;
public interface IAccountService {
List<Account> findAll();
}
二、SSM整合
2.1、保證Spring框架在Web工程中獨立運行
2.1.1、編寫Spring配置文件並導入約束
文件名:applicationContext.xml。
位置:resources目錄下。
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring創建容器時要掃描的包 -->
<context:component-scan base-package="org.codeaction">
<!-- 掃描包的規則,不掃描@Controller註解的Java類,其他的需要掃描 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
2.1.2、創建持久層介面的實現類
package org.codeaction.dao.impl;
import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 這個類僅僅用來測試Spring框架是否搭建成功,測試通過後就可以刪掉
*/
@Repository
public class AccountDaoImpl implements IAccountDao {
@Override
public List<Account> findAll() {
System.out.println("AccountDaoImpl----findAll");
return null;
}
}
這個類是一個“臨時的類”,用來後面測試Spring框架是否搭建成功,後續可以刪掉。
2.1.3、創建業務層介面的實現類
package org.codeaction.service.impl;
import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.codeaction.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
}
2.1.4、測試Spring是否能夠獨立運行
package org.codeaction.test;
import org.codeaction.bean.Account;
import org.codeaction.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
@Autowired
private IAccountService accountService;
@Test
public void testSpring() {
List<Account> list = accountService.findAll();
}
}
運行測試方法,控制台輸出如下,Spring配置成功
AccountDaoImpl----findAll
2.2、保證SpringMVC在Web工程中獨立運行
2.2.1、在web.xml中配置核心控制器
<!-- SpringMVC的核心控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置Servlet的初始化參數,讀取springmvc的配置文件,創建spring容器 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 配置servlet啟動時載入對象 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 解決POST請求亂碼 -->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.2.2、編寫SpringMVC的配置文件
文件名:springmvc.xml。
位置:resource目錄下。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring創建容器時要掃描的包 -->
<context:component-scan base-package="org.codeaction">
<!-- 掃描包的規則,掃描@Controller註解的Java類,其他的不掃描 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置視圖解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--
配置靜態資源不過濾
location:表示路徑
mapping:表示文件
**表示該目錄下的文件以及子目錄文件
-->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<!-- 配置spring開啟註解mvc的支持-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
2.2.3、編寫Controller
package org.codeaction.controller;
import org.codeaction.bean.Account;
import org.codeaction.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
public class AccountController {
@RequestMapping("/accounts")
public String findAll(Model m) {
System.out.println("findAll...");
return "success";
}
}
2.2.4、編寫JSP頁面
index.jsp,在webapp目錄下
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Index</title>
</head>
<body>
<p>
<a href="${pageContext.request.contextPath}/accounts">查詢所有</a>
</p>
</body>
</html>
success.jsp,在webapp\WEB-INF\pages目錄下
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>success</title>
</head>
<body>
<p>success...</p>
</body>
</html>
運行tomcat伺服器,訪問index.jsp上的超鏈接,能夠跳轉到success.jsp,說明SpringMVC配置成功。
2.3、保證MyBatis在Web工程中獨立運行
2.3.1、修改持久層介面
這裡可以把先前創建的持久層介面的實現類刪除了。
package org.codeaction.dao;
import org.apache.ibatis.annotations.Select;
import org.codeaction.bean.Account;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface IAccountDao {
@Select("select * from account")
List<Account> findAll();
}
2.3.2、編寫jdbc配置文件
文件名:jdbcConfig.properties;
位置:resources目錄下。
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
2.3.3、編寫MyBatis配置文件
<?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">
<!-- mybatis的主配置文件 -->
<configuration>
<properties resource="jdbcConfig.properties"></properties>
<!-- 配置環境 -->
<environments default="mysql">
<!-- 配置mysql的環境 -->
<environment id="mysql">
<!-- 配置事務的類型 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置數據源連接池-->
<dataSource type="POOLED">
<!--
配置連接資料庫的4個基本信息
通過${屬性名}的方式獲取屬性值
-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置 -->
<mappers>
<package name="org.codeaction.dao"/>
</mappers>
</configuration>
2.3.4、測試MyBatis是否能夠獨立運行
package org.codeaction.test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
@Test
public void testMyBatis() throws IOException {
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = factory.openSession();
IAccountDao accountDao = session.getMapper(IAccountDao.class);
List<Account> accounts = accountDao.findAll();
accounts.forEach(System.out::println);
}
}
運行測試方法,控制台輸出如下:
Account{id=1, name='Tom', money=1999.0}
Account{id=2, name='Bob', money=2000.0}
Account{id=3, name='Peter', money=10000.0}
Account{id=5, name='John', money=9700.0}
Account{id=6, name='Smith', money=421315.0}
Account{id=7, name='Rose', money=8800000.0}
2.4、整合Spring和SpringMVC
配置監聽器實現啟動服務創建容器,在web.xml中添加如下內容:
<!-- 配置Spring的監聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定Spring配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
2.5、整合Spring和MyBatis
在Spring配置文件applicationContext.xml中添加如下的內容:
<!-- 載入配置文件 -->
<context:property-placeholder location="classpath:jdbcConfig.properties" />
<!-- 配置MyBatis的Session工廠 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 註入資料庫連接處 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置Mapper掃描器 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.codeaction.dao" />
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事務的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false" />
<tx:method name="find" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 配置aop -->
<aop:config>
<!-- 配置切入點表達式 -->
<aop:pointcut id="pt" expression="execution(* org.codeaction.service.impl.*.*(..))" />
<!-- 建立通知和切入點表達式的關係 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt" />
</aop:config>
通過上面的配置,Spring容器負責MyBatis Session工廠的創建,接下來就可以把MyBatis的主配置文件SqlMapConfig.xml刪除了。
2.6、整體測試
2.6.1、修改Controller
package org.codeaction.controller;
import org.codeaction.bean.Account;
import org.codeaction.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
public class AccountController {
@Autowired
private IAccountService accountService;
@RequestMapping("/accounts")
public String findAll(Model m) {
List<Account> accounts = accountService.findAll();
m.addAttribute("accounts", accounts);
return "success";
}
}
2.6.2、修改success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>success</title>
</head>
<body>
<p>success...</p>
<table>
<tr>
<th>id</th>
<th>姓名</th>
<th>餘額</th>
</tr>
<c:forEach items="${accounts}" var="item">
<tr>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.money}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
2.6.3、測試
運行tomcat伺服器,點擊index.jsp上的超鏈接,最終頁面顯示表格,表格中顯示資料庫account表的數據,測試通過。