一、運(yùn)行環(huán)境
-
JDK 17
稿饰; -
IDEA 2021.2
锦秒; -
MySQL 8.0.28
; -
Tomcat 9.0.60
喉镰; -
Maven 3.8.4
旅择;
二、Maven 依賴及資源過濾設(shè)置:pom.xml
<!--依賴-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!--數(shù)據(jù)庫(kù)驅(qū)動(dòng)-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--數(shù)據(jù)庫(kù)連接池 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>
<!--靜態(tài)資源導(dǎo)出-->
<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>
三侣姆、搭建項(xiàng)目基本結(jié)構(gòu)
-
包名及文件名均可自定義:
四生真、編寫配置文件
4.1 數(shù)據(jù)庫(kù)配置文件:
-
database.properties
:
# mysql8 驅(qū)動(dòng)
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/數(shù)據(jù)庫(kù)名?useUnicode=true&characterEncoding=utf8&useSSL=true
jdbc.username=用戶名
jdbc.password=密碼
4.2 配置 MyBatis 層:
- 創(chuàng)建實(shí)體類
- 在
pojo
目錄下創(chuàng)建數(shù)據(jù)庫(kù)對(duì)應(yīng)的實(shí)體類脖咐;
- 編寫 dao 層
-
目錄結(jié)構(gòu):
創(chuàng)建 Dao 層的 Mapper 接口:如:
BookMapper
:
public interface BookMapper {
// 操作數(shù)據(jù)庫(kù)方法
// 如:查詢?nèi)緽ook,返回list集合
List<Books> queryAllBook();
}
- 創(chuàng)建接口對(duì)應(yīng)的
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">
<!--對(duì)應(yīng)接口類:每一個(gè)mapper對(duì)應(yīng)一個(gè)接口文件-->
<mapper namespace="com.study.dao.BookMapper">
<!--對(duì)應(yīng)接口的具體sql-->
<!--如:查詢?nèi)緽ook-->
<select id="queryAllBook" resultType="Books">
select *
from `books`;
</select>
</mapper>
- 編寫 service 層
-
目錄結(jié)構(gòu):
創(chuàng)建 Service 層的接口:如
BookService
public interface BookService {
// 業(yè)務(wù)方法
// 如:查詢?nèi)緽ook,返回list集合
List<Books> queryAllBook();
}
- 創(chuàng)建 Service 層的實(shí)現(xiàn)類:如
BookServiceImpl
public class BookServiceImpl implements BookService {
// service層調(diào)用dao層:組合dao
private BookMapper bookMapper;
// 設(shè)置set接口,方便Spring管理
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public List<Books> queryAllBook() {
// 調(diào)用dao層的方法
return bookMapper.queryAllBook();
}
// ....其它業(yè)務(wù)實(shí)現(xiàn)方法
}
- 配置核心配置文件:
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. 標(biāo)準(zhǔn)日志(可更換其它日志)-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--2. 設(shè)置別名:掃描包的方式-->
<typeAliases>
<!--實(shí)體類的包名稱-->
<package name="com.study.pojo"/>
</typeAliases>
<!--3. 注冊(cè) Mapper.xml-->
<mappers>
<!--1. 接口類方式(對(duì)應(yīng)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 就是一個(gè)容器汇歹,整合 dao 層和 service 層屁擅;
- Spring 整合 MyBatis 層
- 數(shù)據(jù)源為
c3p0
,可更換為其它數(shù)據(jù)源产弹; - 配置 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. 關(guān)聯(lián)數(shù)據(jù)庫(kù)文件:通過spring讀取-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2. 數(shù)據(jù)庫(kù)連接池
dbcp:半自動(dòng)化操作派歌,不能自動(dòng)連接
c3p0:自動(dòng)化操作(自動(dòng)的加載配置文件,并且設(shè)置到對(duì)象里面)
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"/>
<!--關(guān)閉連接后不自動(dòng)commit -->
<property name="autoCommitOnClose" value="false"/>
<!--獲取連接超時(shí)時(shí)間 -->
<property name="checkoutTimeout" value="10000"/>
<!--當(dāng)獲取連接失敗重試次數(shù) -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--3. 配置SqlSessionFactory對(duì)象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--數(shù)據(jù)源-->
<property name="dataSource" ref="dataSource"/>
<!--綁定Mybatis配置文件(spring整合Mybatis) 注意 value后面加classpath:-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4. 配置掃描Dao接口包胶果,動(dòng)態(tài)實(shí)現(xiàn)Dao接口注入到spring容器中(不需要?jiǎng)?chuàng)建dao接口的實(shí)現(xiàn)類)-->
<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業(yè)務(wù)類,注入到spring:通過配置或注解實(shí)現(xiàn)-->
<bean id="BookServiceImpl" class="com.study.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3. 配置聲明式事務(wù) JDBC 事務(wù)-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入數(shù)據(jù)庫(kù)連接池-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4. AOP 配置事務(wù)切入斤斧,需導(dǎo)入AOP織入包及導(dǎo)入頭文件(可不配置)-->
<!--結(jié)合AOP實(shí)現(xiàn)事務(wù)的織入-->
<!--配置事務(wù)通知-->
<!-- <tx:advice id="txAdvice" transaction-manager="transactionManager">-->
<!-- <!–給哪些方法配置事務(wù)–>-->
<!-- <!–配置事務(wù)的傳播特性,propagation:傳播–>-->
<!-- <tx:attributes>-->
<!-- <tx:method name="*" propagation="REQUIRED"/>-->
<!-- </tx:attributes>-->
<!-- </tx:advice>-->
<!--配置事務(wù)切入-->
<!-- <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>
<!--啟動(dòng)級(jí)別-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--所有請(qǐng)求都會(huì)被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. 設(shè)置Session過期時(shí)間-->
<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注解驅(qū)動(dòng),注意導(dǎo)入mvc的頭文件-->
<mvc:annotation-driven/>
<!--2. 靜態(tài)資源過濾-->
<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>
-
創(chuàng)建對(duì)應(yīng)的 jsp 目錄:
-
整合 Spring 總配置文件:
applicationContext.xml
-
web.xml
中需要加載這個(gè)總配置文件游昼;
-
<?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
創(chuàng)建 Controller 類:如
BookController
-
示意圖:
@Controller
@RequestMapping("/book")
public class BookController {
// controller調(diào)service層
// 注解方式實(shí)現(xiàn)自動(dòng)裝配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 視圖頁(yè)面
- 在 jsp 目錄下,創(chuàng)建對(duì)應(yīng)的視圖頁(yè)面:
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 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">
<%--前端返回錯(cuò)誤信息--%>
<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>書籍編號(hào)</th>
<th>書籍名字</th>
<th>書籍?dāng)?shù)量</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風(fēng)格--%>
<a href="${pageContext.request.contextPath}/book/delBook/${book.bookID}">刪除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
5.3 運(yùn)行測(cè)試
- 測(cè)試數(shù)據(jù)數(shù)據(jù)庫(kù):
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 '數(shù)量',
`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,'從刪庫(kù)到跑路'),
(3,'Linux',5,'從進(jìn)門到進(jìn)牢');
配置 Tomcat烘豌;
-
注意:需要添加 lib 依賴载庭,否則報(bào)錯(cuò):
-
運(yùn)行測(cè)試: