前言
本文为 SpringMVC + Spring + Mybatis整合教程 相关详细介绍,从数据库数据准备
、相关依赖包添加
、创建项目基本结构和配置框架
,到Mybatis层的编写
、Spring层的编写
、SpringMVC层的编写
,再到前端页面编写
等,最后进行运行与测试
,按步骤对SSM框架整合进行详细的解析~
????博主主页:小新要变强 的主页
????Java全栈学习路线可参考:【Java全栈学习路线】最全的Java学习路线及知识清单,Java自学方向指引,内含最全Java全栈学习技术清单~
????算法刷题路线可参考:算法刷题路线总结与相关资料分享,内含最详尽的算法刷题路线指南及相关资料分享~
????Java微服务开源项目可参考:企业级Java微服务开源项目(开源框架,用于学习、毕设、公司项目、私活等,减少开发工作,让您只关注业务!)
目录
文章标题
一、数据库数据准备
运行以下sql脚本:
CREATE DATABASE `ssm`;
USE `ssm`;
DROP TABLE IF EXISTS `users`;
CREATE TABLE `ssm`.`users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名',
`sex` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '性别,0男,1女',
`tel` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '联系电话',
`mail` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邮件',
`status` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '状态,0正常,1禁用',
PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;
INSERT INTO `users`(`user_name`, `sex`, `tel`, `mail`, `status`) VALUES
('admin', '0', '123456', '', '0'),
('user1', '0', '123456', '', '0');
创建一个名为ssm的数据库,并在此数据库中创建users数据表,表中包含的属性:“用户名”,“性别”,“联系电话”,“邮件”,“状态”。
二、添加相关依赖包
????新建一个Maven项目(名称叫ssm-user),并添加web支持后,添加以下pom依赖。
pom.xml:
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
</dependencies>
????进行Maven资源过滤设置
pom.xml:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
三、创建项目基本结构和配置框架
- com.pojo
- com.dao
- com.service
- com.controller
四、Mybatis层的编写
????(1)添加数据库配置文件 database.properties,方便管理
database.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1/ssm?serverTimezone=UTC&&useUnicode=true&&characterEncoding=utf8&&useSSL=false
jdbc.username=root
jdbc.password=root
????(2)添加实体Users,使用lombok来创建get/set方法
Users.java:
package com.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 用户实体类
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Users {
private Integer userId;
private String userName;
private String sex;
private String tel;
private String mail;
private String status;
}
????(3)编写Dao层的 Mapper 接口
UsersMapper.java:
package com.dao;
import com.pojo.Users;
import java.util.List;
/**
* 用户 mapper
*/
public interface UsersMapper {
/**
* 查询所有用户
*/
List<Users> queryAll();
/**
* 根据ID查询用户
*/
Users queryById(int id);
/**
* 添加用户
*/
int addUser(Users users);
/**
* 修改用户
*/
int updateUser(Users users);
/**
* 根据ID删除用户
*/
int deleteById(int id);
}
????(4)编写接口对应的 Mapper.xml 文件
UsersMapper.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.dao.UsersMapper">
<resultMap id="users" type="com.pojo.Users">
<result column="user_id" property="userId" />
<result column="user_name" property="userName" />
<result column="sex" property="sex" />
<result column="tel" property="tel" />
<result column="mail" property="mail" />
<result column="status" property="status" />
</resultMap>
<select id="queryAll" resultMap="users">
SELECT * FROM `users`
</select>
<select id="queryById" resultMap="users">
SELECT * FROM `users`
where user_id = #{id}
</select>
<insert id="addUser">
INSERT INTO `users`(`user_name`, `sex`, `tel`, `mail`, `status`)
VALUES
(#{userName}, #{sex}, #{tel}, #{mail}, #{status})
</insert>
<update id="updateUser">
UPDATE `users` SET
`user_name` = #{userName},
`sex` = #{sex},
`tel` = #{tel},
`mail` = #{mail}
WHERE `user_id` = #{userId}
</update>
<delete id="deleteById">
delete from users where user_id=#{userId}
</delete>
</mapper>
????(5)编写Service层的接口和实现类
UsersService.java:
package com.service;
import com.pojo.Users;
import java.util.List;
public interface UsersService {
/**
* 查询所有用户
*/
List<Users> queryAll();
/**
* 根据ID查询用户
*/
Users queryById(int id);
/**
* 添加用户
*/
int addUser(Users users);
/**
* 修改用户
*/
int updateUser(Users users);
/**
* 根据ID删除用户
*/
int deleteById(int id);
}
UsersServiceImpl.java:
package com.service.impl;
import com.dao.UsersMapper;
import com.pojo.Users;
import com.service.UsersService;
import java.util.List;
public class UsersServiceImpl implements UsersService {
//调用dao层的操作,设置一个set接口,方便Spring管理
private UsersMapper usersMapper;
public void setUsersMapper(UsersMapper usersMapper) {
this.usersMapper = usersMapper;
}
@Override
public List<Users> queryAll() {
return usersMapper.queryAll();
}
@Override
public Users queryById(int id) {
return usersMapper.queryById(id);
}
@Override
public int addUser(Users users) {
users.setStatus("0");
return usersMapper.addUser(users);
}
@Override
public int updateUser(Users users) {
return usersMapper.updateUser(users);
}
@Override
public int deleteById(int id) {
return usersMapper.deleteById(id);
}
}
五、Spring层的编写
????编写Spring整合Mybatis的相关的配置文件
配置Spring整合MyBatis,我们这里数据源使用c3p0连接池。
spring-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: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/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置整合mybatis -->
<!-- 1.关联数据库文件 -->
<context:property-placeholder location="classpath:config/database.properties"/>
<!-- 2.数据库连接池 -->
<!--数据库连接池
dbcp 半自动化操作 不能自动连接
c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
-->
<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}"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:config/mybatis-config.xml"/>
</bean>
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--解释 : https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.dao"/>
</bean>
</beans>
????编写Spring整合service层的相关配置文件
spring-service.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"
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">
<!-- 扫描service相关的bean -->
<context:component-scan base-package="com.service" />
<!--BookServiceImpl注入到IOC容器中-->
<bean id="UsersServiceImpl" class="com.service.impl.UsersServiceImpl">
<property name="usersMapper" ref="usersMapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
spring就是一个容器,作用是用来管理其它东西。
六、SpringMVC层的编写
????配置web.xml与spring-mvc.xml配置文件
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--一定要注意:我们这里加载的是总的配置文件,之前被这里坑了!-->
<param-value>classpath:config/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--encodingFilter-->
<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>
<!--Session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解驱动 -->
<mvc:annotation-driven/>
<!-- 2.静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示ViewResolver视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 4.扫描web相关的bean -->
<context:component-scan base-package="com.controller"/>
</beans>
????编写Controller层
UsersController.java:
package com.controller;
import com.pojo.Users;
import com.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/users")
public class UsersController {
@Autowired
@Qualifier("UsersServiceImpl")
private UsersService usersService;
/**
* 查询所有用户
*/
@RequestMapping("/all")
public String list(Model model) {
List<Users> list = usersService.queryAll();
model.addAttribute("list", list);
return "users/allUsers";
}
/**
* 根据ID查询用户
*/
@RequestMapping("/{id}")
public String queryById(@PathVariable int id,Model model) {
model.addAttribute("users",usersService.queryById(id));
return "users/info";
}
/**
* 去添加用户页面
*/
@RequestMapping("/toAdd")
public String toAddUser() {
return "users/add";
}
/**
* 添加用户
*/
@RequestMapping("/add")
public String addUser(Users users) {
usersService.addUser(users);
return "redirect:/users/all";
}
/**
* 去修改页面
* @return
*/
@RequestMapping("/toUpdate")
public String toUpdateUser(int id,Model model) {
model.addAttribute("users",usersService.queryById(id));
return "users/update";
}
/**
* 修改用户
*/
@RequestMapping("/update")
public String updateUser(Users users) {
usersService.updateUser(users);
return "redirect:/users/all";
}
/**
* 根据ID删除用户
*/
@RequestMapping("/del/{id}")
public String deleteById(@PathVariable int id) {
usersService.deleteById(id);
return "redirect:/users/all";
}
}
七、前端页面编写
????(1)首页: index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
<title>首页</title>
<style type="text/css">
a {
text-decoration: none;
color: black;
font-size: 18px;
}
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 4px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/users/all">点击进入列表页</a>
</h3>
</body>
</html>
????(2)用户列表页面:allUser.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户列表</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>用户列表</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/users/toAdd">新增</a>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>序号</th>
<th>用户名称</th>
<th>用户性别</th>
<th>用户电话</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="user" items="${requestScope.get('list')}">
<tr>
<td>${user.getUserId()}</td>
<td>${user.getUserName()}</td>
<td>${user.getSex()==0?"男":"女"}</td>
<td>${user.getTel()}</td>
<td>
<a href="${pageContext.request.contextPath}/users/${user.getUserId()}">详情</a> |
<a href="${pageContext.request.contextPath}/users/toUpdate?id=${user.getUserId()}">更改</a> |
<a href="${pageContext.request.contextPath}/users/del/${user.getUserId()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
????(3)添加用户页面:add.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增用户</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>新增用户</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/users/add" method="post">
用户名称:<input type="text" name="userName"><br><br><br>
用户性别:
<input type="radio" name="sex" value="0" checked>男
<input type="radio" name="sex" value="1">女
<br><br><br>
用户电话:<input type="text" name="tel"><br><br><br>
用户邮箱:<input type="text" name="mail"><br><br><br>
<input type="submit" value="添加">
</form>
</div>
????(4)修改用户页面:update.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改用户</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改用户</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/users/update" method="post">
<input type="hidden" name="userId" value="${users.getUserId()}"/>
用户名称:<input type="text" name="userName" value="${users.getUserName()}"><br><br><br>
用户性别:
<input type="radio" name="sex" value="0" ${users.getSex()==0?"checked":""} >男
<input type="radio" name="sex" value="1" ${users.getSex()!=0?"checked":""} >女
<br><br><br>
用户电话:<input type="text" name="tel" value="${users.getTel()}"><br><br><br>
用户邮箱:<input type="text" name="mail" value="${users.getMail()}"><br><br><br>
<input type="submit" value="修改">
</form>
</div>
????(5)用户详情页面:info.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>详情信息</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>详情信息</small>
</h1>
</div>
</div>
</div>
用户名称:${users.getUserName()} <br>
用户性别:${users.getSex()==0?"男":"女"} <br>
用户电话:${users.getTel()} <br>
用户邮箱:${users.getMail()} <br>
用户状态:${users.getStatus()==0?"正常":"禁用"} <br>
<a href="${pageContext.request.contextPath}/users/all">返回</a>
</div>
八、运行与测试
项目的整体结构如下:
SSM项目整合已经完全的OK,整个项目构建完毕,配置Tomcat就可以运行进行测试!
后记
????Java全栈学习路线可参考:【Java全栈学习路线】最全的Java学习路线及知识清单,Java自学方向指引,内含最全Java全栈学习技术清单~
????算法刷题路线可参考:算法刷题路线总结与相关资料分享,内含最详尽的算法刷题路线指南及相关资料分享~