###快速上手SSM(Spring,SpringMVC,Mybatis)框架整合項目 環境要求: IDEA MySQL 8.0.25 Tomcat 9 Maven 3.6 資料庫環境: 創建一個存放書籍數據的資料庫表 CREATE DATABASE `ssmbooks`; USE `ssmbooks ...
快速上手SSM(Spring,SpringMVC,Mybatis)框架整合項目
環境要求:
- IDEA
- MySQL 8.0.25
- Tomcat 9
- Maven 3.6
資料庫環境:
創建一個存放書籍數據的資料庫表
CREATE DATABASE `ssmbooks`;
USE `ssmbooks`;
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`)
);
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'從入門到放棄'),
(2,'MySQL',10,'從刪庫到跑路'),
(3,'Linux',5,'從進門到進牢');
基本環境搭建:
1、新建一Maven項目!ssmbooks , 添加web的支持
2、導入相關的pom依賴!
<!--依賴:junit,資料庫驅動,連接池,servlet,jsp,mybatis,mybatis-spring,spring,-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--資料庫驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</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.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
3、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>
4、建立基本結構和配置框架!
- com.bai.pojo
- com.bai.dao
- com.bai.service
- com.bai.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
Mybatis層編寫
1、資料庫配置文件 database.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbooks?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
2、IDEA關聯資料庫
3、編寫MyBatis的核心配置文件
<!-- 配置數據源 交給spring去做-->
<!-- 別名-->
<typeAliases>
<package name="com.bai.pojo"/>
</typeAliases>
<!-- 註冊BookMapper.xml-->
<mappers>
<mapper class="com.bai.dao.BookMapper"></mapper>
</mappers>
4、編寫資料庫對應的實體類 com.bai.pojo.Books
使用lombok插件!
package com.bai.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;
}
5、編寫Dao層的 Mapper介面!
package com.bai.dao;
import com.bai.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
// 添加一本書
int addBook(Books books);
// 刪除一本書
int deleteBookById(@Param("bookId") int id);
// 更新一本書
int updateBook(Books books);
// 查詢一本書
Books queryBookById(@Param("bookId") int id);
// 查詢全部的書
List<Books> queryAllBook();
// 通過名字查詢書籍
List<Books> queryBookByName(@Param("BookName") String BookName);
}
6、編寫介面對應的 Mapper.xml 文件。需要導入MyBatis的包;
<?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.bai.dao.BookMapper">
<!-- 添加一本書-->
<insert id="addBook" parameterType="com.bai.pojo.Books">
insert into ssmbooks.books ( bookName, bookCounts, detail)
values (#{bookName},#{bookCounts},#{detail})
</insert>
<!-- 刪除一本書-->
<delete id="deleteBookById" parameterType="int">
delete from ssmbooks.books where bookID = #{bookId}
</delete>
<!-- 更新一本書-->
<update id="updateBook" parameterType="com.bai.pojo.Books">
update ssmbooks.books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID}
</update>
<!-- 通過id查詢書籍-->
<select id="queryBookById" resultType="com.bai.pojo.Books">
select * from ssmbooks.books where bookID=#{bookId}
</select>
<!-- 查詢全部的書-->
<select id="queryAllBook" resultType="com.bai.pojo.Books">
select * from ssmbooks.books
</select>
<!-- 通過名字查詢書籍-->
<select id="queryBookByName" resultType="com.bai.pojo.Books">
select * from ssmbooks.books where bookName like concat('%',#{BookName},'%')
</select>
</mapper>
7、編寫Service層的介面和實現類
介面:
package com.bai.service;
import com.bai.pojo.Books;
import java.util.List;
public interface BookService {
// 添加一本書
int addBook(Books books);
// 刪除一本書
int deleteBookById(int id);
// 更新一本書
int updateBook(Books books);
// 查詢一本書通過id
Books queryBookById(int id);
// 查詢全部的書
List<Books> queryAllBook();
// 查詢一本書通過名字
List<Books> queryBookByName(String BookName);
}
實現類:
package com.bai.service;
import com.bai.dao.BookMapper;
import com.bai.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("BookServiceImpl")
public class BookServiceImpl implements BookService{
//service層調dao層: 組合dao
@Autowired
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
public List<Books> queryBookByName(String BookName) {
return bookMapper.queryBookByName(BookName);
}
}
OK,到此,底層需求操作編寫完畢!
Spring層
1、配置Spring整合MyBatis,我們這裡數據源使用c3p0連接池;
2、我們去編寫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
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置整合mybatis -->
<!-- 1.關聯資料庫配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 2.資料庫連接池 dbcp: 半自動化操作,不能自動連接 c3p0:自動化操作(自動化的載入配置文件,並且可以自動設置到對象中!)-->
<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="classpath:mybatis-config.xml"/>
</bean>
<!-- 配置dao介面掃描包,動態的實現了dao介面可以註入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 1.註入 sqlSessionFactory-->
<!-- 繼承就使用: sqlSessionFactoryBeanName 私有化就使用:sqlSessionTemplateBeanName-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 2.掃描dao包-->
<property name="basePackage" value="com.bai.dao"/>
</bean>
</beans>
3、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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.掃描service下的包-->
<context:component-scan base-package="com.bai.service"/>
<!-- 2.將我們所有的業務類,註入到spring中,可以通過配置,或註解實現自動裝配-->
<!-- <bean id="BookServiceImpl" class="com.bai.service.BookServiceImpl">-->
<!-- <property name="bookMapper" ref="bookMapper"/>-->
<!-- </bean>-->
<!-- 3.聲明式事務配置-->
<bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 註入數據源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 4.aop事務支持-->
</beans>
Spring層搞定!再次理解一下,Spring就是一個大雜燴,一個容器!對吧!
SpringMVC層
1、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">
<!--DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</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>DispatcherServlet</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>
2、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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 1.註解驅動-->
<mvc:annotation-driven/>
<!-- 2.靜態資源過濾-->
<mvc:default-servlet-handler/>
<!-- 3.掃描包:controller-->
<context:component-scan base-package="com.bai.controller"/>
<!-- 4.配置jsp 顯示ViewResolver視圖解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
3、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>
Controller 和 視圖層編寫
**1、BookController 類編寫 **
package com.bai.controller;
import com.bai.pojo.Books;
import com.bai.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 {
//controller層調service層
@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 toAddPaper() {
return "addBook";
}
//添加書籍的請求
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("Books=>:"+books);
bookService.addBook(books);
return "redirect:/book/allbook";
}
//跳轉到修改書籍頁面
@RequestMapping("/toUpdate")
public String toUpdatePaper(int id,Model model){
Books books = bookService.queryBookById(id);
model.addAttribute("QBook", books);
return "updateBook";
}
//修改書籍請求
@RequestMapping("/updateBook")
public String UpdateBook(Books books,Model model) {
System.out.println("UpdateBook=>:"+books);
bookService.updateBook(books);
// 出現的問題:我們提交了修改的SQL請求,但是修改失敗。
// 我們看一下sql語句,能否執行成功? 執行失敗:發現sql語句需要傳遞一個id進行修改
// Books books1 = bookService.queryBookById(books.getBookID());
// model.addAttribute("books1", books1);
return "redirect:/book/allbook";
}
//刪除書籍請求
@RequestMapping("/del/{bookid}")
public String DeleteBook(@PathVariable("bookid") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allbook";
}
//通過名字查詢書籍請求
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model) {
List<Books> list = bookService.queryBookByName(queryBookName);
model.addAttribute("list", list);
if (list.size()==0){
model.addAttribute("msg", "未查到數據");
}
return "allbook";
}
}
2、編寫首頁 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首頁</title>
</head>
<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>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allbook">進入書籍頁面</a>
</h3>
</body>
</html>
3、書籍列表頁面 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>
<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>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allbook">顯示全部書籍</a>
</div>
<div class="col-md-4 column">
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
<span style="color: red;font-weight: bold">${msg}</span>
<input type="text" name="queryBookName" class="form-control" placeholder="請輸入要查詢的書籍">
<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="${requestScope.get('list')}">
<tr>
<td>${book.getBookID()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.getBookID()}">更改</a> | <%-- //老式的傳參--%>
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">刪除</a> <%-- //Restful風格傳參--%>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
5、添加書籍頁面: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/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>
</body>
</html>
7、修改書籍頁面 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/updateBook" method="post">
<%--出現的問題:我們提交了修改的SQL請求,但是修改失敗。
我們看一下sql語句,能否執行成功? 執行失敗:發現sql語句需要傳遞一個id進行修改--%>
<%-- 前端傳參隱藏域--%>
<input type="hidden" name="bookID" value="${QBook.getBookID()}"/>
書籍名稱:<input type="text" name="bookName" value="${QBook.getBookName()}"/>
書籍數量:<input type="text" name="bookCounts" value="${QBook.getBookCounts()}"/>
書籍詳情:<input type="text" name="detail" value="${QBook.getDetail() }"/>
<input type="submit" value="提交"/>
</form>
</div>
</body>
</html>
配置Tomcat,進行運行!
項目結構
這裡我們只是使用了SSM框架完成了基本的增刪改查功能模塊的網頁