环境要求:
- IDEA
- MySQL 8.0 CE
- Tomcat 9.0.41
- Maven 3.6.3
完整的项目地址为:https://codechina.csdn.net/dreaming_coder/ssm
1. 创建数据库
/*
Navicat MySQL Data Transfer
Source Server : ice
Source Server Version : 80021
Source Host : localhost:3306
Source Database : ssm
Target Server Type : MYSQL
Target Server Version : 80021
File Encoding : 65001
Date: 2021-01-14 21:34:07
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for books
-- ----------------------------
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`book_id` int NOT NULL AUTO_INCREMENT COMMENT '书本编号',
`book_name` varchar(100) NOT NULL COMMENT '书名',
`book_counts` int NOT NULL COMMENT '数量',
`detail` varchar(200) DEFAULT NULL COMMENT '描述',
PRIMARY KEY (`book_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of books
-- ----------------------------
INSERT INTO `books` VALUES ('1', 'Java', '1', '从入门到放弃');
INSERT INTO `books` VALUES ('2', 'MySQL', '10', '从删库到跑路');
INSERT INTO `books` VALUES ('3', 'Linux', '5', '从进门到进牢');
2. 新建 Maven 项目
-
添加 web 支持
-
导入相关依赖
<dependencies> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</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.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.2</version> </dependency> <!-- 偷懒依赖 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies>
-
Maven 设置静态资源过滤
<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.ice.pojo
-
com.ice.mapper
-
com.ice.service
-
com.ice.controller
-
mybatis-config.xml
<?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
<?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" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> </beans>
-
3. Mybatis 层编写
-
数据库配置文件 database.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&useSSL=true&useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=root
-
IDEA 关联数据库
-
编写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> <!-- 设置别名 --> <typeAliases> <package name="com.ice.pojo"/> </typeAliases> </configuration>
-
编写实体类
package com.ice.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Books { private int id; private String name; private int counts; private String detail; }
-
编写 Dao 层的 Mapper 接口
package com.ice.mapper; import com.ice.pojo.Books; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BookMapper { // 增加一本书 int addBook(@Param("book") Books book); // 删除一本书 int deleteBookById(@Param("id") int id); // 更新一本书 int updateBook(@Param("book") Books book); // 根据 id 查询一本书 Books queryBookById(@Param("id") int id); // 查询全部的书 List<Books> queryAllBooks(); }
-
编写接口对应的 Mapper.xml 文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ice.mapper.BookMapper"> <insert id="addBook" parameterType="Books"> insert into ssm.books (book_name, book_counts, detail) values (#{name}, #{counts}, #{detail}); </insert> <delete id="deleteBookById" parameterType="int"> delete from ssm.books where book_id = #{id}; </delete> <update id="updateBook" parameterType="Books"> update ssm.books set book_name = #{name}, book_counts = #{counts}, detail = #{detail} where book_id = #{id}; </update> <select id="queryBookById" parameterType="int" resultMap="bookMap"> select * from ssm.books where book_id = #{id}; </select> <select id="queryAllBooks" resultMap="bookMap"> select * from ssm.books; </select> <resultMap id="bookMap" type="Books"> <id property="id" column="book_id"/> <result property="name" column="book_name"/> <result property="counts" column="book_counts"/> <result property="details" column="details"/> </resultMap> </mapper>
-
编写Service层的接口和实现类
【接口】
package com.ice.service; import com.ice.pojo.Books; import java.util.List; public interface BookService { // 增加一本书 int addBook(Books book); // 删除一本书 int deleteBookById(int id); // 更新一本书 int updateBook(Books book); // 根据 id 查询一本书 Books queryBookById(int id); // 查询全部的书 List<Books> queryAllBooks(); }
【实现类】
package com.ice.service; import com.ice.mapper.BookMapper; import com.ice.pojo.Books; import java.util.List; public class BookServiceImpl implements BookService { private BookMapper bookMapper; public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public int addBook(Books book) { return bookMapper.addBook(book); } @Override public int deleteBookById(int id) { return bookMapper.deleteBookById(id); } @Override public int updateBook(Books book) { return bookMapper.updateBook(book); } @Override public Books queryBookById(int id) { return bookMapper.queryBookById(id); } @Override public List<Books> queryAllBooks() { return bookMapper.queryAllBooks(); } }
4. Spring 层
-
配置Spring整合MyBatis,我们这里数据源使用 c3p0 连接池,编写 Spring 整合 Mybatis 的相关的配置文件 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 http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 关联数据库配置文件 --> <context:property-placeholder location="classpath:database.properties"/> <!-- 数据库连接池 --> <!-- dbcp: 半自动化操作,不能自动连接 c3p0: 自动化操作(自动化加载配置文件,并且可以自动设置到对象) druid hikari --> <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> <!-- SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 绑定 mybatis 配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!-- 配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 --> <!-- 新的方式,不需要实现类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入 sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 要扫描的 Dao 包--> <property name="basePackage" value="com.ice.mapper"/> </bean> </beans>
-
Spring 整合 service 层
<?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下的包 --> <context:component-scan base-package="com.ice.service"/> <!-- 将所有业务类注入到spring,可以配置,可以注解 --> <bean id="bookServiceImpl" class="com.ice.service.BookServiceImpl"> <property name="bookMapper" ref="bookMapper"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource"/> </bean> </beans>
5. Spring MVC 层
-
配置 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"> <!--1.注册servlet--> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--通过初始化参数指定配置文件的位置,进行关联--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <!-- 启动顺序,数字越小,启动越早 --> <load-on-startup>1</load-on-startup> </servlet> <!--所有请求都会被springmvc拦截 --> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 2.编码过滤器 --> <filter> <filter-name>encoding</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>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 3.超时时间 --> <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 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- mvc注解驱动 --> <mvc:annotation-driven /> <!-- 让Spring MVC不处理静态资源 --> <mvc:default-servlet-handler/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 后缀 --> <property name="suffix" value=".jsp"/> </bean> <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 --> <context:component-scan base-package="com.ice.controller"/> </beans>
-
Spring 配置整合文件,applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="classpath:spring-dao.xml"/> <import resource="classpath:spring-service.xml"/> <import resource="classpath:spring-mvc.xml"/> </beans>
6. Controller 和视图层
-
BookController 类编写
package com.ice.controller; import com.ice.pojo.Books; import com.ice.service.BookService; 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("/book") public class BookController { @Autowired @Qualifier("bookServiceImpl") private BookService bookService; // 查询全部书籍,并返回一个书籍展示页面 @RequestMapping("/list") public String list(Model model) { List<Books> list = bookService.queryAllBooks(); model.addAttribute("list", list); return "list"; } @RequestMapping("/toAddBook") public String toAddBook() { return "addBook"; } @RequestMapping("/add") public String add(Books book) { bookService.addBook(book); return "redirect:/book/list"; } @RequestMapping("/toUpdateBook") public String toUpdateBook(Model model, int id) { Books book = bookService.queryBookById(id); model.addAttribute("book", book); return "updateBook"; } @RequestMapping("/update") public String update(Model model, Books book) { bookService.updateBook(book); return "redirect:/book/list"; } @RequestMapping("/delete/{bookId}") public String delete(@PathVariable("bookId") int id) { bookService.deleteBookById(id); return "redirect:/book/list"; } }
-
编写首页 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <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}/book/list">进入书籍页面</a></h3> </body> </html>
-
书籍列表页面 list.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}/book/toAddBook">新增</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="book" items="${requestScope.get('list')}"> <tr> <td>${book.getId()}</td> <td>${book.getName()}</td> <td>${book.getCounts()}</td> <td>${book.getDetail()}</td> <td> <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getId()}">更改</a> | <a href="${pageContext.request.contextPath}/book/delete/${book.getId()}">删除</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> </body> </html>
-
添加书籍页面:addBook.jsp
<%@ 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}/book/add" method="post"> 书籍名称:<input type="text" name="name"><br><br><br> 书籍数量:<input type="text" name="counts"><br><br><br> 书籍详情:<input type="text" name="detail"><br><br><br> <input type="submit" value="添加"> </form> </div> </body> </html>
-
修改书籍页面 updateBook.jsp
<%@ 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}/book/update" method="post"> <input type="hidden" name="id" value="${book.getId()}"/> 书籍名称:<input type="text" name="name" value="${book.getName()}"/> 书籍数量:<input type="text" name="counts" value="${book.getCounts()}"/> 书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/> <input type="submit" value="提交"/> </form> </div> </body> </html>