一、运行环境
-
JDK 17
; -
IDEA 2021.2
; -
MySQL 8.0.28
; -
Tomcat 9.0.60
; -
Maven 3.8.4
;
二、Maven 依赖及资源过滤设置:pom.xml
<!--依赖-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--数据库连接池 c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!--Servlet-JSP-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</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.9</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.18</version>
</dependency>
<!--Spring Java 注解:JDK11 以上需要-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<!--AOP 织入-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.8</version>
</dependency>
</dependencies>
<!--静态资源导出-->
<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>
三、搭建项目基本结构
-
包名及文件名均可自定义:
四、编写配置文件
4.1 数据库配置文件:
-
database.properties
:
# mysql8 驱动
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf8&useSSL=true
jdbc.username=用户名
jdbc.password=密码
4.2 配置 MyBatis 层:
- 创建实体类
- 在
pojo
目录下创建数据库对应的实体类;
- 编写 dao 层
-
目录结构:
-
创建 Dao 层的 Mapper 接口:如:
BookMapper
:
public interface BookMapper {
// 操作数据库方法
// 如:查询全部Book,返回list集合
List<Books> queryAllBook();
}
- 创建接口对应的
Mapper.xml
文件:如BookMapper.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对应一个接口文件-->
<mapper namespace="com.study.dao.BookMapper">
<!--对应接口的具体sql-->
<!--如:查询全部Book-->
<select id="queryAllBook" resultType="Books">
select *
from `books`;
</select>
</mapper>
- 编写 service 层
-
目录结构:
-
创建 Service 层的接口:如
BookService
public interface BookService {
// 业务方法
// 如:查询全部Book,返回list集合
List<Books> queryAllBook();
}
- 创建 Service 层的实现类:如
BookServiceImpl
public class BookServiceImpl implements BookService {
// service层调用dao层:组合dao
private BookMapper bookMapper;
// 设置set接口,方便Spring管理
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public List<Books> queryAllBook() {
// 调用dao层的方法
return bookMapper.queryAllBook();
}
// ....其它业务实现方法
}
- 配置核心配置文件:
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>
<!--1. 标准日志(可更换其它日志)-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--2. 设置别名:扫描包的方式-->
<typeAliases>
<!--实体类的包名称-->
<package name="com.study.pojo"/>
</typeAliases>
<!--3. 注册 Mapper.xml-->
<mappers>
<!--1. 接口类方式(对应dao层的接口类)-->
<mapper class="com.study.dao.BookMapper"/>
<!--2. 资源文件方式-->
<!--<mapper resource="com/study/dao/BookMapper.xml"/>-->
<!--3. 扫描包方式-->
<!--<package name="com.study.dao"/>-->
</mappers>
</configuration>
4.3 配置 Spring 层:
- Spring 就是一个容器,整合 dao 层和 service 层;
- Spring 整合 MyBatis 层
- 数据源为
c3p0
,可更换为其它数据源; - 配置 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
https://www.springframework.org/schema/context/spring-context.xsd">
<!--配置整合mybatis-->
<!--1. 关联数据库文件:通过spring读取-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2. 数据库连接池
dbcp:半自动化操作,不能自动连接
c3p0:自动化操作(自动的加载配置文件,并且设置到对象里面)
druid、hikari
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置c3p0连接池属性 -->
<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"/>
<!--绑定Mybatis配置文件(spring整合Mybatis) 注意 value后面加classpath:-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4. 配置扫描Dao接口包,动态实现Dao接口注入到spring容器中(不需要创建dao接口的实现类)-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描Dao接口包-->
<property name="basePackage" value="com.study.dao"/>
</bean>
</beans>
- Spring 整合 service 层
- 配置 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
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1. 扫描service下的包-->
<context:component-scan base-package="com.study.service"/>
<!--2. 将所有的service业务类,注入到spring:通过配置或注解实现-->
<bean id="BookServiceImpl" class="com.study.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3. 配置声明式事务 JDBC 事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4. AOP 配置事务切入,需导入AOP织入包及导入头文件(可不配置)-->
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<!-- <tx:advice id="txAdvice" transaction-manager="transactionManager">-->
<!-- <!–给哪些方法配置事务–>-->
<!-- <!–配置事务的传播特性,propagation:传播–>-->
<!-- <tx:attributes>-->
<!-- <tx:method name="*" propagation="REQUIRED"/>-->
<!-- </tx:attributes>-->
<!-- </tx:advice>-->
<!--配置事务切入-->
<!-- <aop:config>-->
<!-- <aop:pointcut id="txPointCut" expression="execution(* com.study.dao.*.*(..))"/>-->
<!-- <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>-->
<!-- </aop:config>-->
</beans>
4.4 配置 SpringMVC 层
-
模块添加 web 框架支持:
-
配置
web.xml
:- 注意:加载的是 spring 总的配置文件
applicationContext.xml
;
- 注意:加载的是 spring 总的配置文件
<?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. DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--注意:这里加载的是总的配置文件,总配置文件中,通过import引入其它配置文件-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--启动级别-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--所有请求都会被springmvc拦截,不包含.jsp -->
<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过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
- 配置 SpringMVC 的配置文件:如
springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--配置SpringMVC-->
<!-- 1. 开启SpringMVC注解驱动,注意导入mvc的头文件-->
<mvc:annotation-driven/>
<!--2. 静态资源过滤-->
<mvc:default-servlet-handler/>
<!--3. 扫描包:Controller-->
<context:component-scan base-package="com.study.controller"/>
<!--4. 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
-
创建对应的 jsp 目录:
-
整合 Spring 总配置文件:
applicationContext.xml
-
web.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">
<!--dao层-->
<import resource="spring-dao.xml"/>
<!--service层-->
<import resource="spring-service.xml"/>
<!--controller层-->
<import resource="springmvc-servlet.xml"/>
</beans>
五、Controller 和视图层编写
5.1 Controller
-
创建 Controller 类:如
BookController
-
示意图:
@Controller
@RequestMapping("/book")
public class BookController {
// controller调service层
// 注解方式实现自动装配Bean
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
// 示例方法
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
// 重定向
// return "redirect:/book/allBook";
}
// ...其它方法
}
5.2 视图页面
- 在 jsp 目录下,创建对应的视图页面:
allBook.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>
<!-- 引入 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>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a>
</div>
<%--添加书籍查询功能--%>
<div class="col-md-8 column">
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post"
style="float: right">
<%--前端返回错误信息--%>
<span style="color:red;font-weight: bold">
${error}
</span>
<input type="text" name="queryBookName" class="form-control" placeholder="输入查询书名" required>
<input type="submit" value="查询" class="btn btn-primary">
</form>
</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="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.bookID}">更改</a>
|
<%--RestFul风格--%>
<a href="${pageContext.request.contextPath}/book/delBook/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
5.3 运行测试
- 测试数据数据库:
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4;
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
-
配置 Tomcat;
-
注意:需要添加 lib 依赖,否则报错:
-
运行测试:
网友评论