本教程源碼請訪問:tutorial_demo SSM整合可以使用多種方式,我們純註解的方式,拋棄所有的xml配置文件(包括web.xml),使用Java配置類和註解進行配置。 SSM的整體思路:整合Spring和SpringMVC,整合Spring和MyBatis,兩兩整合。 一、環境準備 1.1、 ...
本教程源碼請訪問:tutorial_demo
SSM整合可以使用多種方式,我們純註解的方式,拋棄所有的xml配置文件(包括web.xml),使用Java配置類和註解進行配置。
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>javax.servlet-api</artifactId>
<version>3.1.0</version>
</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>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>
這裡註意,由於我們要拋棄web.xml配置文件,需要將servlet版本升級到3.0及以上版本。
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配置類
這個配置類用來對Spring進行配置,代替之前的Spring配置文件applicationContext.xml。
//Spring的配置類
@Configuration
@ComponentScan(value = "org.codeaction",
excludeFilters = {
@ComponentScan.Filter(
type = FilterType.ANNOTATION,
classes = {org.springframework.stereotype.Controller.class})
})
public class RootConfig {
}
@Configuration聲明這是一個配置類。
@ComponentScan指定要掃描的包,excludeFilters指定要忽略的註解,因為@Controller配置的類由SpringMVC管理,Spring要忽略它。
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、編寫SpringMVC的配置類
之前我們在springmvc.xml中配置SpringMVC,這裡我們拋棄springmvc.xml,使用Java類配置SpringMVC。
package org.codeaction.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
//SpringMVC的配置類
@Configuration
@ComponentScan(value = "org.codeaction", includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {org.springframework.stereotype.Controller.class})
})
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
//配置視圖解析器
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
registry.viewResolver(resolver);
}
//配置靜態資源不過濾
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
}
2.2.2、配置核心控制器
之前我們在web.xml中配置核心控制器,這裡我們拋棄web.xml,使用Java類配置核心控制器。
package org.codeaction.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
//這裡暫時先這樣寫,後面還要修改
return new Class[]{};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
我們只需要知道繼承AbstractAnnotationConfigDispatcherServletInitializer
的類都會自動地配置DispatcherServlet
和Spring應用上下文,Spring的應用上下文會位於應用程式的Servlet上下文之中。
在Servlet3.0環境中,容器會在類路徑中查找實現javax.servlet.ServletContainerInitializer
介面的類,如果能發現的話,就會用它來配置Servlet容器。
Spring提供了這個介面的實現,名為SpringServletContainerInitializer
,SpringServletContainerInitializer
這個類反過來又會查找實現WebApplicationInitializer
的類並將配置的任務交給它們來完成。Spring3.2引入了WebApplicationInitializer
的基礎實現AbstractAnnotationConfigDispatcherServletInitializer
。
因此,我們繼承AbstractAnnotationConfigDispatcherServletInitializer
(同時也實現了WebApplicationInitializer
),當項目部署到Servlet3.0容器中的時候,容器會自動發現它,並用它來配置Servlet上下文。
getServletMappings()
會將一個或多個路徑映射到DispatcherServlet
上。
getServletConfigClasses()
在DispatcherServlet
載入應用上下文時,使用定義在WebConfig
配置類中的bean。WebConfig
作用就是代替springmvc.xml配置文件,getServletConfigClasses()
說白了就是讓DispatcherServlet
讀取springmvc.xml的配置用的。
我們在之前Spring整合SpringMVC中需要配置監聽器ContextLoaderListener
,並且要將Spring的配置文件當成初始化參數進行配置供ContextLoaderListener
讀取,getRootConfigClasses()
作用和這個相同,就是指定Spring的配置類,供監聽器ContextLoaderListener
讀取,後面我們會用到,這個數組我們暫時不寫內容。
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配置文件
文件名:jdbc.properties;
位置:resources目錄下。
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8
jdbc.user=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="jdbc.properties"></properties>
<!-- 配置環境 -->
<environments default="mysql">
<!-- 配置mysql的環境 -->
<environment id="mysql">
<!-- 配置事務的類型 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置數據源連接池-->
<dataSource type="POOLED">
<!--
配置連接資料庫的4個基本信息
通過${屬性名}的方式獲取屬性值
-->
<property name="driver" value="${jdbc.driverClass}"/>
<property name="url" value="${jdbc.jdbcUrl}"/>
<property name="username" value="${jdbc.user}"/>
<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
修改WebAppInitializer,代碼如下:
package org.codeaction.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
//讓監聽器載入Spring的配置
return new Class[]{RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
//配置POST請求編碼的Filter
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter());
characterEncodingFilter.setInitParameter("encoding", "UTF-8");
characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*");
}
}
通過onStartup可以在SpringMVC中配置Servlet、Filter、Listener。
2.5、整合Spring和MyBatis
2.5.1、編寫數據源配置類
package org.codeaction.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* 配置類
*/
@Configuration
public class JdbcConfig {
@Value("${jdbc.driverClass}")
private String driverClass;
@Value("${jdbc.jdbcUrl}")
private String jdbcUrl;
@Value("${jdbc.user}")
private String user;
@Value("${jdbc.password}")
private String password;
//創建和配置數據源
@Bean("dataSource")
public DataSource dataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(driverClass);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(user);
dataSource.setPassword(password);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
}
2.5.2、編寫事務配置類
package org.codeaction.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
@Configuration
public class TransactionConfig {
//創建事務管理器
@Bean("transactionManager")
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
2.5.3、修改Spring配置類
package org.codeaction.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
//Spring的配置類
@Configuration
@ComponentScan(value = "org.codeaction", excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {org.springframework.stereotype.Controller.class})
})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, TransactionConfig.class})
@EnableTransactionManagement
@MapperScan(basePackages = "org.codeaction.dao")
public class RootConfig {
//配置MyBatis的Bean工廠
@Bean("sqlSessionFactory")
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
}
@MapperScan指定Spring要掃描的Mapper的位置。
通過上面的配置,Spring容器負責MyBatis Session工廠的創建,接下來就可以把MyBatis的主配置文件SqlMapConfig.xml刪除了。
2.5.4、修改持久層介面
package org.codeaction.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.codeaction.bean.Account;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
public interface IAccountDao {
@Select("select * from account")
List<Account> findAll();
}
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表的數據,測試通過。