1.0 環境要求
- IDEA
- MySQL 5.7.19
- Tomcat 9
- Maven 3.6
1.1 數據庫
創建書籍數據庫表,包括書籍編號,書籍名稱,書籍數量以及書籍描述。
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '書id',
`bookName` VARCHAR(100) NOT NULL COMMENT '書名',
`bookCounts` INT(11) NOT NULL COMMENT '數量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'從入門到放棄'),
(2,'MySQL',10,'從刪庫到跑路'),
(3,'Linux',5,'從進門到進牢');
1.2 基本環境搭建
- 新建一Maven項目!ssmbuild,添加web的支持
- 導入相關的pom依賴和maven資源過濾
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fanjh</groupId>
<artifactId>ssmbuild</artifactId>
<version>1.0-SNAPSHOT</version>
<!--導入依賴-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--數據庫驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</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>
</project>
注意:這裏導包之後記得查看project structure中有無相關包,一般要手動導入
- 建立基本結構和框架:
- com.fanjh.pojo
- com.fanjh.dao
- com.fanjh.service
- com.fanjh.controller
- mybatis-config.xml
這裏給出最終結構
前端調用controller層, controller層調用service層,service層調用dao層
1.2 mybatis層編寫
- 數據庫配置文件database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=fjhmysql
- 連接數據庫
- 編寫mybatis核心配置文件: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>
<!--mybatis核心配置文件-->
<!--配置數據源等交給spring去做,這裏主要別名和註冊映射-->
<typeAliases>
<package name="com.fanjh.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.fanjh.dao.BookMapper"/>
</mappers>
</configuration>
- 編寫數據庫對應實體類:com.fanjh.pojo.Books
使用lombok插件
package com.fanjh.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
- 緊接着編寫dao層的mapper接口
package com.fanjh.dao;
import com.fanjh.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
//增刪改查方法
public interface BookMapper {
int addBook(Books book);
int deleteBookById(@Param("bookId") int id);
int updateBook(Books book);
Books queryBookById(@Param("bookId") int id);
List<Books> queryAllBook();
}
- 馬上編寫接口對應的Mapper.xml文件(對應sql語句), 需要註冊到mybatis.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.fanjh.dao.BookMapper">
<insert id = "addBook" parameterType="Books">
insert into ssmbuild.books(bookName, bookCounts, detail)
VALUES(#{bookName}, #{bookCounts}, #{detail})
</insert>
<delete id="deleteBookById" parameterType="int">
DELETE from ssmbuild.books where bookID = #{bookId}
</delete>
<update id="updateBook" parameterType="Books">
update ssmbuild.books
set bookName=#{bookName}, bookCounts=#{bookCounts}, detail=#{detail}
where bookID=#{bookID};
</update>
<select id="queryBookById" parameterType="int" resultType="Books">
select * from ssmbuild.books where bookID=#{bookId};
</select>
<select id="queryAllBook" resultType="Books">
select * FROM ssmbuild.books
</select>
</mapper>
至此,搞定dao層,接下來業務層。
- 編寫Service層接口和實現類
接口:
package com.fanjh.service;
import com.fanjh.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookService {
int addBook(Books book);
int deleteBookById(int id);
int updateBook(Books book);
Books queryBookById(int id);
List<Books> queryAllBook();
}
實現類:
package com.fanjh.service;
import com.fanjh.dao.BookMapper;
import com.fanjh.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
//service層調dao層
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books book) {
return bookMapper.addBook(book);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books book) {
return bookMapper.updateBook(book);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
可以看到,service層的方法都是直接調用dao層的方法,到此底層需求操作編寫完畢。
1.3 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">
<!--配置整合mybatis-->
<!--1.關聯數據庫文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2.連接池:
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>
<!--3.sqlsessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入數據庫連接池 -->
<property name="dataSource" ref="datasource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4.配置dao接口掃描包,動態的實現了Dao接口可以注入到spring容器中-->
<!--以前要新建一個dao接口實現類,然後在spring中註冊實現類-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlsessionfactory即可-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要掃描的包-->
<property name="basePackage" value="com.fanjh.dao"/>
</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">
<!--如果上面配置錯了,常會報錯:通配符很全面,但無法找到元素。。。的聲明-->
<!--1.掃描service包-->
<context:component-scan base-package="com.fanjh.service"/>
<!--2.將我們所有的業務類,注入到spring,可以通過配置或註解實現@Service @Autowired-->
<bean id="BookServiceImpl" class="com.fanjh.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3.聲明式事務管理期-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入數據庫連接池-->
<property name="dataSource" ref="datasource"/>
</bean>
</beans>
至此,spring層搞定,spring就是個大容器,整合dao層和service層,也是實現了dao層和service層的分離——解耦。
1.4 springMVC層
- 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">
<!--DispatchServlet-->
<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>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--亂碼過濾-->
<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: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
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--配置映射器、適配器、視圖解析器-->
<!--1.註解驅動-->
<mvc:annotation-driven/>
<!--2.靜態資源過濾-->
<mvc:default-servlet-handler/>
<!--3.掃描包-->
<context:component-scan base-package="com.fanjh.controller"/>
<!--4.視圖解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</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">
<!--spring核心配置文件-->
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
至此,所有的配置文件暫告一段落,接下來編寫Controller和視圖層,Controller和視圖層交互,然後調用service層。
- BookController類編寫,增刪改查書籍(Controller層的編寫需要實時對照視圖層)
package com.fanjh.controller;
import com.fanjh.pojo.Books;
import com.fanjh.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("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
//跳轉到增加書籍頁面
@RequestMapping("/toAddBook")
public String toAddBook(){
return "addBook";
}
//添加書籍的請求
@RequestMapping("/addBook")//執行完後,重定向到allbook頁面
public String addBook(Books books){
System.out.println("addBook=>" + books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
//跳轉到修改書籍頁面
@RequestMapping("/toUpdate")
public String toUpdateBook(int id, Model model){
Books books = bookService.queryBookById(id);//根據id取到圖書
model.addAttribute("Qbooks",books);//將圖書返回給前端
return "updateBook";
}
//修改書籍
//接收到前端傳來的數據,調用service層執行修改操作
@RequestMapping("/updateBook")
public String updateBook(Books books){
System.out.println("updateBook=>" + books);
bookService.updateBook(books);
return "redirect:/book/allBook";
}
//刪除書籍
@RequestMapping("/deleteBook/{bookId}")//restful風格
public String deleteBook(@PathVariable("bookId") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
}
- 編寫首頁index.jsp
<%--
Created by IntelliJ IDEA.
User: fjh990
Date: 2020/11/7
Time: 12:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首頁</title>
<style>
a{
text-decoration: none;
color: gold;
font-size: 50px;
}
h3{
width:500px;
height:80px;
margin:500px auto;
text-align: center;
line-height: 80px;
background: black;
border-radius: 6px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">進入書籍頁面</a>
</h3>
</body>
</html>
- 新建三個.jsp文件:
- allBook:顯示所有書籍
- addBook:增加書籍
- updateBook:修改書籍
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>
<%--增加書籍按鈕,點擊後跳到controller頁面,然後根據return值到addbook.jsp--%>
<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="${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/toUpdate?id=${book.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">刪除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
addBook.jsp:
<%@ 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>
<%--點擊添加按鈕後,跳轉到/book/addBook執行添加操作(屬性名一定要一致)--%>
<form action="${pageContext.request.contextPath}/book/addBook"
method="post">
書籍名稱:<input type="text" name="bookName" required><br><br><br>
書籍數量:<input type="text" name="bookCounts" required><br><br><br>
書籍詳情:<input type="text" name="detail" required><br><br><br>
<input type="submit" value="添加">
</form>
</div>
</body>
</html>
這裏拿增加書籍舉例梳理整個流程:
- 前端點擊新增書籍按鈕後,跳轉到controller找到/book/toAddBook,跳轉到toAddBook頁面
- 根據toAddBook頁面的return語句,拼接後找到/WEB-INF/jsp/addBook.jsp文件
- 根據頁面展示,填寫所要增加的書籍的內容
- 點擊“添加”按鈕,返回controller找到/book/addBook頁面,並傳回books信息
- controller層調用service層執行增加書籍操作。
- 返回到顯示書籍頁面
updateBook.jsp:
<%@ 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>
<%--我們提交了修改的sql請求,但是修改失敗,spring接管事務後不需要顯式的配置,不是事務問題
看一下sql語句,能否執行成功:sql執行失敗
前端傳遞隱藏域--%>
<form action="${pageContext.request.contextPath}/book/updateBook"
method="post">
<input type="hidden" name="bookID" value="${Qbooks.bookID}">
書籍名稱:<input type="text" name="bookName" value="${Qbooks.bookName}" required><br><br><br>
書籍數量:<input type="text" name="bookCounts" value="${Qbooks.bookCounts}" required><br><br><br>
書籍詳情:<input type="text" name="detail" value="${Qbooks.detail}" required><br><br><br>
<input type="submit" value="修改">
</form>
</div>
</body>
</html>
至此,整個項目整合完畢
最後
歡迎關注公衆號:前程有光,領取一線大廠Java面試題總結+各知識點學習思維導+一份300頁pdf文檔的Java核心知識點總結!