文章目录
零、源代码
源代码已上传至 GitHub:callmePicacho
建议搭配源代码使用
参考视频:
Mybatis教程IDEA版-4天-2018黑马SSM-01
Spring教程IDEA版-4天-2018黑马SSM-02
SpringMVC教程IDEA版-3天-2018黑马SSM-03
一、说明
1. 需求分析
- 从数据库读数据到前台
- 从前台插入数据到数据库
2. 效果图
3. 整合思路
- 先搭建整合环境
- 搭建 Spring 配置
- 使用 Spring 整合 SpringMVC
- 使用 Spring 整合 MyBatis
4. 环境
- IDE:IntelliJ IDEA 2018.1.3
- JDK:9.0.4
- Maven:3.6.1
- Tomcat:9.0.8
- Mysql:5.1.6
- Spring:5.0.2.RELEASE
- spring-web:5.0.2.RELEASE
- MyBatis:3.4.5
5. 架构
- Spring 作为业务层,整合 SpringMVC 和 MyBatis,处理数据
- SpringMVC 作为表现层,显示数据
- MyBatis 作为持久层,与数据库交互
二、搭建整合环境
0. 目标
- 数据库和表创建完成
- Maven 项目创建完成,并导入坐标
- MVC 架构创建完成
- xml 配置文件创建完成
- tomcat 服务器配置完成,并成功运行
0.1 目录结构
1. 创建数据库和表
CREATE DATABASE ssm;
USE ssm;
CREATE TABLE user(
id int primary key auto_increment,
name varchar(20),
age int
);
INSERT INTO user(name,age) VALUES('aaa',12);
INSERT INTO user(name,age) VALUES('bbb',34);
INSERT INTO user(name,age) VALUES('ccc',56);
2. 搭建 Maven 项目
- 创建 maven 项目
IDEA搭建Maven Web - 在 pom.xml 文件中引入坐标依赖
pom.xml 中,properties 标签改为:
dependencies 标签改为:<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties>
<dependencies> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies>
- 在 main 目录下创建 java 目录和 resources 目录
并分别标记为 Sources Root 和 Resources Root
3. 创建类和配置文件
-
在 java 目录下创建多个类
- 创建user实体类 org.lyy.entity.User
package org.lyy.entity; public class User { private Integer id; private String name; private Integer age; 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 Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
- 创建dao接口 org.lyy.dao.UserDao
package org.lyy.dao; import org.lyy.entity.User; import java.util.List; public interface UserDao { public void insertUser(User user); public List<User> queryAll(); }
- 创建service接口 org.lyy.service.UserService
package org.lyy.service; import org.lyy.entity.User; import java.util.List; public interface UserService { public void insertUser(User user); public List<User> queryAll(); }
- 创建service实现类,继承service接口 org.lyy.service.impl.UserServiceImpl
package org.lyy.service.impl; import org.lyy.entity.User; import org.lyy.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { @Override public void insertUser(User user) { System.out.println("service插入数据"); } @Override public List<User> queryAll() { System.out.println("service查询全部数据"); return null; } }
- 创建user实体类 org.lyy.entity.User
-
在 resources 目录下创建多个配置文件
- 创建applicationContext.xml ,存放 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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> </beans>
- 创建log4j.properties,存放日志相关配置
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=info, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPatern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n t # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
- 创建springmvc.xml,存放 SpringMVC 相关配置
<?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"> </beans>
- 创建SqlMapConfig.xml,存放 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"> <configuration> </configuration>
- 创建applicationContext.xml ,存放 Spring 相关配置
4. 部署项目到 tomcat 服务器
- 打开 Edit Configurations
- 添加 tomcat 服务器
- 配置 tomcat 服务器
- 运行服务器,测试服务器是否成功部署
三、搭建和测试 Spring
0. 目录结构
1. 完善 applicationContext.xml
<!-- 配置扫描器,spring管理的是service和dao层的注解,controller注解交给springmvc管理 -->
<context:component-scan base-package="org.lyy">
<!-- 配置要忽略的注解 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
2. 编写测试类
- 为 UserServiceImpl 类添加注解
@Service("userService") public class UserServiceImpl implements UserService{ ... }
- 编写测试类 org.lyy.test.ServiceTest
package org.lyy.test; import org.junit.Test; import org.lyy.service.UserService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ServiceTest { @Test public void run(){ // 获取context上下文对象 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 得到 service 对象 UserService service = (UserService)context.getBean("userService"); // 调用测试 service.queryAll(); } }
3. 测试 spring 框架
运行 run 方法,测试 spring 是否搭建成功
四、搭建和测试 springMVC
0. 目录结构
1. 完善 web.xml
- 配置过滤器,解决中文乱码问题
- 配置DispatcherServlet前端控制器
<!-- 配置过滤器,解决中文乱码问题-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 字符集初始化为 UTF-8 -->
<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>
<!-- 配置DispatcherServlet前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载 springmvc.xml -->
<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>
2. 完善 springmvc.xml
- 配置注解扫描器,只扫描 controller
- 配置视图解析器,控制 controller 跳转到 “/WEB-INF/pages/” 目录下,以 “xxx.jsp” 结尾的文件
- 开启对 springMVC 注解的支持
<!-- 扫描Controller的注解-->
<context:component-scan base-package="org.lyy">
<!-- 只扫描 controller-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 开启对SpringMVC注解的支持 -->
<mvc:annotation-driven/>
3. 编写测试类
- 创建UserController类 org.lyy.controller.UserController
package org.lyy.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @RequestMapping("queryAll") public String queryAll(){ System.out.println("controller查询全部数据"); return "success"; } }
- index.jsp 添加超链接,跳转访问 UserController 的 queryAll 方法
报 404 的话将路径改为 “./user/queryAll”,感谢 @信管亲爸 同学补充<%@ page contentType="text/html;charset=UTF-8" language="java"%> <html> <body> <a href="/user/queryAll">查询测试</a> </body> </html>
- WEB-INF 目录下新建 pages 目录,pages 目录下创建 success.jsp 页面,编写 success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>跳转成功</h1> </body> </html>
4. 测试 SpringMVC 框架
运行 tomcat 服务器,点击超链接看页面是否正常跳转,验证 SpringMVC 是否搭建成功
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener 错误的解决办法
五、Spring 整合 SpringMVC
0. 目录结构
1. 目的
在 controller 中能成功调用 service 对象中的方法
2. 修改 web.xml
配置 ContextLoaderListener 监听器,使项目在启动时就去加载applicationContext.xml的配置文件
<!-- 设置加载类路径的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置 spring 的监听器,默认只加载 WEB-INF 目录下的 applicationContext.xml 配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
注意:web.xml 中的文件配置有先后顺序,代码直接贴上去可能会报错,所以需要修改配置顺序,修改后的 web.xml :
<!-- 设置加载类路径的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置过滤器,解决中文乱码问题-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 字符集初始化为 UTF-8 -->
<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>
<!-- 配置 spring 的监听器,默认只加载 WEB-INF 目录下的 applicationContext.xml 配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置DispatcherServlet前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载 springmvc.xml -->
<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>
3. 修改 UserController
在controller中注入service对象,调用service对象的方法进行测试
package org.lyy.controller;
import org.lyy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/queryAll")
public String queryAll(){
System.out.println("controller查询全部数据");
// 调用注入的 userService 调用 queryAll 方法
userService.queryAll();
return "success";
}
}
4. 测试 Spring 是否整合 SpringMVC
当点击超链后,userService 调用 queryAll 方法能成功在控制台输出"service查询全部数据"说明整合成功
六、搭建和测试 MyBatis
0. 目录结构
1. 完善 SqlMapConfig.xml
添加数据源配置信息和引入映射文件
<!-- 配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射文件 -->
<mappers>
<package name="org.lyy.dao"/>
</mappers>
报错Cause: org.xml.sax.SAXParseException lineNumber: 2; columnNumber: 16; 文档根元素 " 的解决方案
2. 完善 UserDao
为方法添加注解
package org.lyy.dao;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.lyy.entity.User;
import java.util.List;
public interface UserDao {
@Insert("insert into user(name,age) values(#{name},#{age})")
public void insertUser(User user);
@Select("select * from user")
public List<User> queryAll();
}
3. 编写测试类
创建 DaoTest 类,并写入 testQueryAll 和 testInsert 测试方法对查询和插入进行测试
package org.lyy.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.junit.Test;
import org.lyy.dao.UserDao;
import org.lyy.entity.User;
import java.io.InputStream;
import java.util.List;
public class DaoTest {
// 测试 queryAll
@Test
public void testQueryAll() throws Exception {
// 加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
// 创建 sqlSession 对象
SqlSession session = factory.openSession();
// 获取代理对象
UserDao dao = session.getMapper(UserDao.class);
// 调用 queryAll
List<User> users = dao.queryAll();
for (User user : users) {
System.out.println(user.getId() + " " + user.getName() + " " + user.getAge());
}
// 释放资源
session.close();
is.close();
}
// 测试 insert
@Test
public void testInsert() throws Exception {
// 加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
// 创建 sqlSession 对象
SqlSession session = factory.openSession();
// 获取代理对象
UserDao dao = session.getMapper(UserDao.class);
// 创建 User 对象
User user = new User();
user.setName("fff");
user.setAge(18);
dao.insertUser(user);
// 提交事务
session.commit();
// 释放资源
session.close();
is.close();
}
}
4. 检测 MyBatis 是否搭建成功
- 右键 run testQueryAll(),查看输出窗口是否查询到 user 数据
- 右键 run testInsert() 后再 run testQueryAll(),查看输出窗口数据是否被插入
Mybatis遇到No constructor found in …的解决方法
七、Spring 整合 MyBatis
0. 目录结构
1. 目的
把 MyBatis 的数据源,SqlSession 和 dao 都交给 spring 管理
2. 完善 applicationContext.xml
- 把 SqlMapConfig.xml 配置文件中的内容配置到 applicationContext.xml 配置文件中
- 删除 SqlMapConfig.xml
<!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 配置 SqlSession 工厂 --> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 引入数据源 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置 Dao 接口所在类--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.lyy.dao"/> </bean>
3. 修改 UserDao 类
为 UserDao 添加 @Repository 注解
@Repository
public interface UserDao{
...
}
4. 修改 UserServiceImpl 类
在 UserServiceImpl 类中注入 dao 对象,dao 对象执行相应方法
package org.lyy.service.impl;
import org.lyy.dao.UserDao;
import org.lyy.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.lyy.service.UserService;
import java.util.List;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao dao;
@Override
public void insertUser(User user) {
System.out.println("service插入数据");
dao.insertUser(user);
}
@Override
public List<User> queryAll() {
System.out.println("service查询全部数据");
return dao.queryAll();
}
}
5. 修改 UserController.java
将从数据库查到的数据放入 Model 对象
package org.lyy.controller;
import org.lyy.entity.User;
import org.lyy.service.UserService;
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 java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/queryAll")
public String queryAll(Model model) {
System.out.println("controller查询全部数据");
// 调用注入的 userService 调用 queryAll 方法
List<User> users = userService.queryAll();
// 将 users 放入 users
model.addAttribute("users",users);
return "success";
}
@RequestMapping("/insert")
public String insert(User user) {
System.out.println("controller插入数据");
// 调用注入的 userService 调用 insert 方法
userService.insertUser(user);
return "success";
}
}
6. 修改 index.jsp
- 提交表单插入数据
- 点击超链接查询数据
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<body>
<a href="/user/queryAll">查询全部数据</a>
<br>
<form method="post" action="/user/insert">
姓名:<input type="text" name="name"><br>
年龄:<input type="text" name="age"><br>
<input type="submit" value="插入表单数据"><br>
</form>
</body>
</html>
7. 修改 success.jsp
添加展示数据
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>跳转成功</h1>
${users}
</body>
</html>
8. 整合完成
至此,Spring 整合 SpringMVC、MyBatis 完成
谢谢您能看到这,点个赞再走吧~
八、布置项目到阿里云
请移步:布置 SSM 项目到阿里云