整合SSM架構-簡易圖書管理系統
1、建立資料庫
CREATE DATABASE ssmbuild;
USE ssmbuild;
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=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,"Java",1,"從入門到入土"),
(2,"MySQL",10,"從删庫到跑路"),
(3,"Linux",5,"從入門到入獄");
2、導入依賴以及解決靜态資源導出問題
<!--依賴:junit、資料庫驅動、連接配接池、servlet、jsp、mybatis、mybatis-spring、spring、lombok-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<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>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</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>
3、建立項目結構
dao、service、pojo、controller
4、配置檔案
- 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:springmvc-servlet.xml"/>
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
</beans>
- 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>
<typeAliases>
<package name="com.lengzher.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.lengzher.dao.BookMapper"/>
</mappers>
</configuration>
5、建立實體類
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
private int id;
private String bookName;
private int bookCount;
private String detail;
}
6、持久層-Mybatis
- 接口
public interface BooksMapper {
//查詢一本書
Books queryBookById(@Param("bookID") int id);
//查詢全部的書
List<Books> queryBooks();
//添加一本書
int addBook(Books books);
//修改
int updateBook(Books books);
//删除
int delBook(@Param("bookID") int id);
}
- 接口對應的Mapper檔案
<?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.lengzher.dao.BooksMapper">
<select id="queryBookById" parameterType="int" resultType="Books">
select * from books where BookID = #{BookID}
</select>
<select id="queryBooks" resultType="Books">
select * from books
</select>
<insert id="addBook" parameterType="Books">
insert into books (bookName, bookCounts, detail) values
(#{bookName},#{bookCounts},#{detail})
</insert>
<update id="updateBook" parameterType="Books">
update books set bookName=(#{bookName}),bookCounts=(#{bookCounts}),detail=(#{detail})
</update>
<delete id="delBook" parameterType="int">
delete from books where BookID = #{BookID}
</delete>
</mapper>
- 在mybatis-config.xml中注冊Mapper
<mappers>
<mapper class="com.lengzher.dao.BooksMapper"/>
</mappers>
7、業務層
- 接口
public interface BookService {
//查詢一本書
Books queryBookById( int id);
//查詢全部的書
List<Books> queryBooks();
//添加一本書
int addBook(Books books);
//修改
int updateBook(Books books);
//删除
int delBook( int id);
}
- 接口實作類
public class BookServiceImpl implements BookService{
//Service層調用Dao層
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper){
this.bookMapper = bookMapper;
}
public Books queryBookById(int id) {
return this.bookMapper.queryBookById(id);
}
public List<Books> queryBooks() {
return this.bookMapper.queryBooks();
}
public int addBook(Books books) {
return this.bookMapper.addBook(books);
}
public int updateBook(Books books) {
return this.bookMapper.updateBook(books);
}
public int delBook(int id) {
return this.bookMapper.delBook(id);
}
}
8、Spring架構使用
- 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/beans/context.xsd
">
<!--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"/>
<!--綁定mybatis的配置檔案-->
<property name="configLocation" value="mybatis-config.xml"/>
</bean>
<!--配置dao接口掃描包,動态地實作了Dao接口可以注入到Spring容器中!-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--掃描包-->
<property name="basePackage" value="com.lengzher.dao"/>
</bean>
</beans>
- 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/beans/context.xsd
">
<!--掃描service下的包-->
<context:component-scan base-package="com.lengzher.service"/>
<!--将所有的業務類注入到spring,可以通過配置或者注解實作-->
<bean id="BookServiceImpl" class="com.lengzher.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--聲明式事務-->
<bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入資料源-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
9、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:springmvc-servlet.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>
- 配置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
http://www.springframework.org/schema/cache/mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--注解驅動-->
<mvc:annotation-driven/>
<!--靜态資源過濾-->
<mvc:default-servlet-handler/>
<!--掃描包-->
<context:component-scan base-package="com.lengzher.controller"/>
<!--視圖解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".sjp"/>
</bean>
</beans>
Tips:架構已經整合完了,記得在applicationContext.xml檔案中導入其他三個配置檔案:
<import resource="classpath:springmvc-servlet.xml"/>
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
10、查詢功能實作
- 控制層代碼
@Controller
@RequestMapping("/book")
public class BookController {
//controller層調用service層
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查詢全部書籍,并傳回書籍展示頁面
@RequestMapping("/allBook")
public String list(Model model){
List<Books> books = bookService.queryBooks();
model.addAttribute("list",books);
return "allBook";
}
}
- 首頁index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首頁</title>
<style>
*{margin:0; padding:0}
body{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
a{
padding:10px;
text-decoration: none;
color: black;
font-size: 18px;
border-radius: 5px;
box-shadow: 2px 2px 5px 5px black;
}
</style>
</head>
<a href="${pageContext.request.contextPath}book/allBook" target="_blank" rel="external nofollow" style="align-content: center">跳轉到書籍展示頁面</a>
</body>
</html>
- 書籍展示頁面allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: 17700
Date: 2021/9/16
Time: 15:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>書籍展示</title>
<%--Bootsrap美化界面--%>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-4 column">
<div class="page-header">
<h1>
<small>書籍清單</small>
</h1>
</div>
</div>
</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>
</tr>
</thead>
<%--将書籍從資料庫中查詢出來,從這個list中周遊出來:foreach--%>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</body>
</html>
11、添加書籍
- 在書籍展示頁面添加:添加書籍按鈕
<a href="${pageContext.request.contextPath}/book/toAddPager" target="_blank" rel="external nofollow" style="float: right; font-size: 20px;text-decoration: underline;color:gray">
<h5>新增書籍</h5>
</a>
- 控制層實作跳轉
//跳轉到添加書籍頁面
@RequestMapping("/toAddPager")
public String goAddBook() {
return "addBook";
}
- 建立添加書籍頁面
<%@ 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" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" 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/addBook"method="post">
書籍名稱:<input type="text" name="bookName"><br><br><br>
書籍數量:<input type="text" name="bookCounts"><br><br><br>
書籍詳情:<input type="text" name="detail"><br><br><br>
<input type="submit" value="添加">
</form>
</div>
- 控制層添加書籍
//添加書籍頁面
@RequestMapping("/addBook")
public String addBook(Books books) {
System.out.println("addBook=》"+books);
bookService.addBook(books);
return "redirect:/book/allBook";//重定向到首頁
}
12、删除書籍
//删除書籍
@RequestMapping("/delBook/{bookId}")
public String delBook(@PathVariable("bookId") int id){
bookService.delBook(id);
return "redirect:/book/allBook";
}
13、搜尋功能
- 前端添加搜尋框
<form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="text-decoration: underline;color:gray;height: 10px ">
<input type="submit" value="查詢">
<input type="text" name="queryBookName" placeholder="請輸入要查詢的書籍">
</form>
- 持久層接口
//通過書名查詢書籍
List<Books> queryBookByName(String bookName);
- 持久層接口實作Mapper
<select id="queryBookByName" resultType="Books">
select * from books where bookName like "%"#{bookName}"%";
</select>
- 業務層接口
//通過書名查詢書籍
List<Books> queryBookByName(String bookName);
- 業務層接口實作類
public List<Books> queryBookByName(String bookName) {
return this.bookMapper.queryBookByName(bookName);
}
- 控制層
//搜尋書籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
List<Books> list = bookService.queryBookByName(queryBookName);
model.addAttribute("list",list);
return "allBook";
}