來源:B站狂神說
第一步、創建數據庫
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,'從進門到進牢');
第二步、Maven導包,過濾資源
<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.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</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>
第三步、構建基本結構和配置框架
-
com.xian.pojo
-
com.xian.dao
-
com.xian.service
-
com.xian.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層
數據庫配置db.properties(Mysql 8.0 配置時區)
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/ssmbuild?serverTimezone=UTC&useUnicode=ture&characterEncoding=UTF-8 name=root password=123456
編寫Mybatis核心配置文件
<?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.xian.pojo"/> </typeAliases> <mappers> <mapper class="com.xian.dao.BookMapper"/> </mappers> </configuration>
構建實體類com.xian.pojo.Books
package com.xian.pojo; public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; public Books() { } public Books(int bookID, String bookName, int bookCounts, String detail) { this.bookID = bookID; this.bookName = bookName; this.bookCounts = bookCounts; this.detail = detail; } public int getBookID() { return bookID; } public void setBookID(int bookID) { this.bookID = bookID; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public int getBookCounts() { return bookCounts; } public void setBookCounts(int bookCounts) { this.bookCounts = bookCounts; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } @Override public String toString() { return "Books{" + "bookID=" + bookID + ", bookName='" + bookName + '\'' + ", bookCounts=" + bookCounts + ", detail='" + detail + '\'' + '}'; } }
編寫Mapper接口和對應的xml文件
package com.xian.dao; import com.xian.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(); }
xml(update需要注意id問題)
<?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.xian.dao.BookMapper"> <insert id="addBook" parameterType="Books"> insert into ssmbuild.books (bookName,bookCounts,detail) values (#{bookNmae},#{bookCounts},#{detail}) </insert> <delete id="deleteBookById" parameterType="int"> delete from ssmbuild.books where bookID=#{id} </delete> <update id="updateBook" parameterType="Books"> update ssmbuild.books set bookName=#{bookName}, bookCounts=#{bookCounts}, detail=#{detail} where bookID=#{id} </update> <select id="queryBookById" resultType="Books" parameterType="int"> select * from ssmbuild.books where bookID=#{id} </select> <select id="queryAllBook" resultType="Books"> select * from ssmbuild.books </select> </mapper>
編寫Service層的接口和實現類
package com.xian.service; import com.xian.pojo.Books; import java.util.List; public interface BookService { //增 int addBook(Books books); //刪 int deleteBookById(int id); //改 int updateBook(Books books ); //查 Books queryBookById(int id); List<Books> queryAllBook(); }
實現類(實現類的關鍵就是注入的BookMapper,每次執行BookMapper里的方法)自旋棧溢出
package com.xian.service; import com.xian.dao.BookMapper; import com.xian.pojo.Books; import java.util.List; public class BookServiceImpl implements BookService { 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(); } }
Spring層
Spring整合Mybatis使用c3p0連接池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"> <!--關聯數據庫--> <context:property-placeholder location="classpath:db.properties"/> <!--數據庫連接池--> <bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driver}"/> <property name="jdbcUrl" value="${url}"/> <property name="user" value="${name}"/> <property name="password" value="${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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dateSource"></property> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <property name="basePackage" value="com.xian.dao"/> </bean> </beans>
Spring整合Sevrice層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"> <context:component-scan base-package="com.xian.service"></context:component-scan> <bean id="BookServiceImpl" class="com.xian.service.BookServiceImpl"> <property name="bookMapper" ref="bookMapper"></property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dateSource"/> </bean> </beans>
Spring MVC層
web.xml(注意整合過程導入applicationContext.xml配置整體的ApplicationContext.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"> <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-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 https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <context:component-scan base-package="com.xian.controller"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
Spring配置整合文件applicatioContext.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="spring-dao.xml"/> <import resource="spring-service.xml"/> <import resource="spring-mvc.xml"/> </beans>
底層配置文件結束,Controller和視圖層編寫
package com.xian.controller;
import com.xian.pojo.Books;
import com.xian.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.RequestMapping;
import java.util.List;
@Controller
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
//查詢全部並顯示
public String AllBook(Model model){
List<Books> books=bookService.queryAllBook();
model.addAttribute("list",books);
return "allBook";
}
@RequestMapping("/toAddBook")
//請求跳轉到添加的頁面
public String addBook(){
return "addBook";
}
@RequestMapping("/addPaper")
//執行添加操作
public String addPaper(Books books){
bookService.addBook(books);
return "redirect:/allBook";
}
@RequestMapping("/toUpdateBook")
//獲取當前值,為表單填充數據
public String toUpdateBook(int id, Model model) {
Books books = bookService.queryBookById(id);
model.addAttribute("book",books);
return "updateBook";
}
@RequestMapping("/updateBook")
//id為隱形傳參(沒有id屬性更新必然失敗)
public String updateBook(Books books){
bookService.updateBook(books);
return "redirect:/allBook";
}
@RequestMapping("/del")
//delete直接操作不需要跳轉
public String delete(int id){
bookService.deleteBookById(id);
return "redirect:/allBook";
}
}
編寫首頁index.xml
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>首頁</title> </head> <body> <h3> <a href="${pageContext.request.contextPath}/allBook">查看全部書籍</a> </h3> </body> </html>
編寫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}/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.getBookID()}</td> <td>${book.getBookName()}</td> <td>${book.getBookCounts()}</td> <td>${book.getDetail()}</td> <td> <a href="${pageContext.request.contextPath}/toUpdateBook?id=${book.getBookID()}">更改</a> | <a href="${pageContext.request.contextPath}/del?id=${book.getBookID()}">刪除</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> </body> </html>
編寫addbook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <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"> <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}/addPaper" 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>
編寫updateBook.xml(update需要id參數,隱形傳輸,不然SQL執行失敗)配置日志查錯方便
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </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}/updateBook" method="post"> <input type="hidden" name="bookID" value="${book.bookID}"> 書籍名稱:<input type="text" name="bookName" value="${book.bookName}" required><br><br><br> 書籍數量:<input type="text" name="bookCounts" value="${book.bookCounts}" required><br><br><br> 書籍詳情:<input type="text" name="detail" value="${book.detail}" required><br><br><br> <input type="submit" value="修改"> </form> </div> </body> </html>
拓展:配置日志
Mybatis-config.xml
<settings> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings>
項目結構: