5 整合SSM框架
環境
- IDEA 2020.2
- MySQL 5.7.29
- Tomcat 9
- Maven 3.6
資料庫環境
創建一個資料庫及表格
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、新建一個Maven專案!ssmbuild,添加web支持!
2、匯入相關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.zzb</groupId>
<artifactId>ssmbuild</artifactId>
<version>1.0-SNAPSHOT</version>
<!--匯入依賴,需要Junit,資料庫驅動,資料庫連接池,servlet,jsp,el運算式,mybatis,mybatis-spring,spring,偷懶用的lombok-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!--資料庫連接池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</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.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
<!--靜態資源過濾問題-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
3、確定專案基本框架!

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>
database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=1234
MyBatis 層撰寫
1、創建物體類Book
package com.zzb.pojo;
public class Book {
private int bookId;
private String bookName;
private int bookCount;
private String detail;
public Book() {
}
public Book(int bookId, String bookName, int bookCount, String detail) {
this.bookId = bookId;
this.bookName = bookName;
this.bookCount = bookCount;
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 getBookCount() {
return bookCount;
}
public void setBookCount(int bookCount) {
this.bookCount = bookCount;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "Book{" +
"bookId=" + bookId +
", bookName='" + bookName + '\'' +
", bookCount=" + bookCount +
", detail='" + detail + '\'' +
'}';
}
}
2、撰寫Mapper層Mapper介面
package com.zzb.mapper;
import com.zzb.pojo.Book;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
// 增加一本書
int addBook(Book book);
// 洗掉一本書
int deleteBookById(@Param("bookId") int id);
// 更新一本書
int updateBook(Book book);
// 查詢一本書
Book queryBookById(@Param("bookId") int id);
// 查詢所有書
List<Book> queryAllBook();
}
3、撰寫對應的Mapper.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.zzb.mapper.BookMapper">
<insert id="addBook" parameterType="Book">
INSERT INTO books(bookName, bookCount, detail) VALUES (#{bookName}, #{bookCount}, #{detail})
</insert>
<delete id="deleteBookById" parameterType="int">
DELETE FROM books WHERE bookId = #{bookId}
</delete>
<update id="updateBook" parameterType="Book">
UPDATE books SET bookName = #{bookName}, bookCount = #{bookCount}, detail = #{detail} WHERE bookId = #{bookId}
</update>
<select id="queryBookById" parameterType="int">
SELECT * FROM book WHERE bookId = #{bookId}
</select>
<select id="queryAllBook" resultType="Book">
SELECT * FROM book
</select>
</mapper>
4、撰寫Service層的介面和實作類
package com.zzb.service;
import com.zzb.pojo.Book;
import java.util.List;
public interface BookService {
// 增加一本書
int addBook(Book book);
// 洗掉一本書
int deleteBookById(int id);
// 更新一本書
int updateBook(Book book);
// 查詢一本書
Book queryBookById(int id);
// 查詢所有書
List<Book> queryAllBook();
}
package com.zzb.service;
import com.zzb.mapper.BookMapper;
import com.zzb.pojo.Book;
import java.util.List;
public class BookServiceImpl implements BookService{
// 組合Mapper層
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Book book) {
return bookMapper.addBook(book);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Book book) {
return bookMapper.updateBook(book);
}
public Book queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Book> queryAllBook() {
return bookMapper.queryAllBook();
}
}
5、配置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.zzb.pojo"/>
</typeAliases>
<!--注冊Mapper-->
<mappers>
<mapper />
</mappers>
</configuration>
Spring 層撰寫
1、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">
<!--1、關聯資料庫組態檔-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2、資料庫連接池-->
<!--資料庫連接池
dbcp 半自動化操作 不能自動連接
c3p0 自動化操作(自動的加載組態檔 并且設定到物件里面)
-->
<bean id="dataSource" >
<!-- 配置連接池屬性 -->
<property name="driverClass" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${jdbc.driver}"/>
<property name="jdbcUrl" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${jdbc.url}"/>
<property name="user" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${jdbc.username}"/>
<property name="password" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${jdbc.password}"/>
<!-- c3p0連接池的私有屬性 -->
<property name="maxPoolSize" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/30"/>
<property name="minPoolSize" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/10"/>
<!-- 關閉連接后不自動commit -->
<property name="autoCommitOnClose" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/false"/>
<!-- 獲取連接超時時間 -->
<property name="checkoutTimeout" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/10000"/>
<!-- 當獲取連接失敗重試次數 -->
<property name="acquireRetryAttempts" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/2"/>
</bean>
<!--3、SqlSessionFactory-->
<bean id="sqlSessionFactory" >
<!--注入資料庫連接池-->
<property name="dataSource" ref="dataSource"/>
<!--配置MyBatis核心組態檔-->
<property name="configLocation" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/classpath:mybatis-config.xml"/>
</bean>
<!--4、配置掃描Dao介面包,動態實作Dao介面注入到spring容器中-->
<!--解釋 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean >
<!--注入SqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/sqlSessionFactory"/>
<!--配置需要掃描的包-->
<property name="basePackage" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/com.zzb.mapper"/>
</bean>
</beans>
2、Spring 整合 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.zzb.service"/>
<!--2、將業務層實作類注入到Spring中-->
<bean id="bookServiceImpl" >
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3、配置事務管理器-->
<bean id="transactionManager" >
<!--注入資料庫連接池-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4、AOP織入事務管理-->
</beans>
Spring MVC 層
1、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">
<!--自動掃描包,讓指定包下的注解生效,由IOC容器統一管理-->
<context:component-scan base-package="com.zzb.controller"/>
<!--讓Spring MVC不處理靜態資源,例如.mp3 .css .jpg等不走視圖決議器-->
<mvc:default-servlet-handler/>
<!--
支持mvc注解驅動
在spring中一般采用@RequestMapping注解來完成映射關系
要想使@RequestMapping注解生效
必須向背景關系中注冊DefaultAnnotationHandlerMapping
和一個AnnotationMethodHandlerAdapter實體
這兩個實體分別在類級別和方法級別處理,
而annotation-driven配置幫助我們自動完成上述兩個實體的注入
-->
<mvc:annotation-driven/>
<!--視圖決議器-->
<bean id="InternalResourceViewResolver">
<!--前綴-->
<property name="prefix" value="https://www.cnblogs.com/WEB-INF/jsp/"/>
<!--后綴-->
<property name="suffix" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/.jsp"/>
</bean>
</beans>
2、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="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
3、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>
Controller 和視圖層撰寫
1、查詢全部書籍, BookController 類撰寫
package com.zzb.controller;
import com.zzb.pojo.Book;
import com.zzb.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
@RequestMapping("/book")
public class BookController {
// controller層呼叫業務層
// 自動裝備指定引數
@Autowired
@Qualifier("bookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
public String allBook(Model model){
List<Book> bookList = bookService.queryAllBook();
model.addAttribute("bookList", bookList);
return "allBook";
}
}
2、撰寫首頁 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<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>
</head>
<body>
<h3>
<a href="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${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 >
<div >
<div >
<div >
<h1>
<small>書籍串列 —— 顯示所有書籍</small>
</h1>
</div>
</div>
</div>
<div >
<div >
<a href="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${pageContext.request.contextPath}/book/toAddBook">新增</a>
</div>
</div>
<div >
<div >
<table >
<thead>
<tr>
<th>書籍編號</th>
<th>書籍名字</th>
<th>書籍數量</th>
<th>書籍詳情</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${requestScope.get('bookList')}">
<tr>
<td>${book.getBookId()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCount()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookId()}">更改</a>
|
<a href="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${pageContext.request.contextPath}/book/del/${book.getBookId()}">洗掉</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
4、添加書籍,BookController類撰寫
// 添加書籍功能
// 首先跳轉到添加書籍頁面
@RequestMapping("toAddBook")
public String toAddBook(){
return "addBook";
}
// 執行資料添加
@RequestMapping("addBook")
public String addBook(Book book){
int i = bookService.addBook(book);
if(i == 1){
System.out.println("書籍添加成果!");
}else{
System.out.println("書籍添加失敗!");
}
return "redirect:/book/allBook";
}
5、添加書籍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 >
<div >
<div >
<div >
<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="bookCount"><br><br><br>
書籍詳情:<input type="text" name="detail"><br><br><br>
<input type="submit" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/添加">
</form>
</div>
</body>
</html>
6、修改書籍,BookController類撰寫
// 修改書籍資訊
// 跳轉到書籍資訊修改頁面
@RequestMapping("toUpdateBook")
public String toUpdateBook(@RequestParam("id") int bookId, Model model){
// 首先查詢到書籍的原資訊,在頁面中進行展示
Book book = bookService.queryBookById(bookId);
System.out.println(book.toString());
model.addAttribute("book", book);
return "updateBook";
}
// 執行修改資料操作
@RequestMapping("updateBook")
public String updateBook(Book book){
int i = bookService.updateBook(book);
if(i == 1){
System.out.println("修改書籍成功!");
}else{
System.out.println("修改書籍失敗!");
}
return "redirect:/book/allBook";
}
7、修改書籍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 >
<div >
<div >
<div >
<h1>
<small>修改書籍書籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<%--隱藏域傳遞書籍id--%>
<input type="hidden" name="bookId" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${book.getBookId()}">
書籍名稱:<input type="text" name="bookName" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${book.getBookName()}"><br><br><br>
書籍數量:<input type="text" name="bookCount" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${book.getBookCount()}"><br><br><br>
書籍詳情:<input type="text" name="detail" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/${book.getDetail()}"><br><br><br>
<input type="submit" value="https://www.cnblogs.com/zzbstudy/archive/2020/12/17/修改">
</form>
</div>
</body>
</html>
8、洗掉資料,BookController類撰寫
// 洗掉一本書籍
@RequestMapping("/deleteBook/{id}")
public String deleteBook(@PathVariable("id") int bookId){
int i = bookService.deleteBookById(bookId);
if(i == 1){
System.out.println("洗掉書籍成功!");
}else{
System.out.println("洗掉書籍失敗!");
}
return "redirect:/book/allBook";
}
9、配置Tomcat,運行,測驗
問題說明:
1、手動為專案添加lib檔案夾,在其中添加專案所需要的包,否則專案會報錯!

2、由于xml檔案中使用了中文注釋,需要在pom組態檔中,添加如下配置,使專案整體編碼為utf-8,否則報錯!
<properties>
<project.build.sourceEncoding>UTF8</project.build.sourceEncoding>
</properties>
專案結構圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/236394.html
標籤:其他
上一篇:位元組跳動CEO被員工懟:不爽退群啊!互聯網公司員工這么豪橫?
下一篇:C++基礎知識篇:C++ 字串
