整合SSM框架
1、環境說明
環境:
- IDEA 2018
- MySql 8.0.23
- Tomcat 9
- Maven 3.6
- jdk 1.8+
要求:
- 需要熟練掌握MySQL資料庫,Spring,JavaWeb及MyBatis知識,簡單的前端知識
2、資料庫環境
建立一個存放書籍資料的資料庫表
CREATE TABLE books(
bookID INT PRIMARY KEY AUTO_INCREMENT ,
bookName VARCHAR(100) NOT NULL ,
bookCounts INT NOT NULL ,
detail VARCHAR(200) NOT NULL
)default CHARSET=utf8;
INSERT INTO books VALUES
(1,"Spring",1,"從入門到放棄"),
(2,"MyBatis",10,"從刪庫到跑路"),
(3,"SpringMvc",5,"從進門到進牢")
3、基本環境搭建
3.1、新建一個Maven專案
3.2、匯入相關依賴
<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.23</version>
</dependency>
<!--資料庫連線池:c3p0 dbcp -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</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.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
3.3、Maven資源過濾設定
<!--靜態資源匯出問題-->
<!--在build中配置resources,來防止我們資源匯出失敗的問題-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
3.4、建立基本結構和配置框架
- com.shun.pojo 實體層
- com.shun.dao
- com.shun.service
- com.shun.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>
4、Mybatis層編寫
- 資料庫配置檔案 database.properties
jdbc.driver=com.mysql.jdbc.Driver
# 如果使用的是MySql8.0+,增加一個時區的配置;serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/springmvc?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
注意:database.properties檔案中不能有空格!
- 關聯資料庫
<context:property-placeholder location="classpath:database.properties"/>
- 編寫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.shun.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.shun.dao.BookMapper"/>
</mappers>
</configuration>
-
編寫資料庫對應的實體類 pojo.Books
使用Lombok外掛
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private Integer bookID;
private String bookName;
private Integer bookCounts;
private String detail;
}
- 編寫Dao層 的 Mapper介面!
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();
}
- 編寫介面對應的 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.shun.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into springmvc.books(bookName, bookCounts, detail)
values (#{bookName},#{bookCounts},#{detail})
</insert>
<delete id="deleteBookById" parameterType="int">
delete from springmvc.books where bookID = #{bookId}
</delete>
<update id="updateBook" parameterType="Books">
update springmvc.books
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID = #{bookID};
</update>
<select id="queryBookById" resultType="Books">
select * from springmvc.books
where bookID = #{bookId}
</select>
<select id="queryAllBook" resultType="list">
select * from springmvc.books
</select>
</mapper>
-
編寫Service層的介面和實現類
介面:
public interface BookService {
//增加一本書
int addBook(Books books);
//刪除一本書
int deleteBookById(int id);
//更新一本書
int updateBook(Books books);
//查詢一本書
Books queryBookById(int id);
//查詢全部的書
List<Books> queryAllBook();
}
實現類:
public class BookServiceImpl implements BookService {
//呼叫dao層的操作,設定一個set介面,方便Spring管理
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();
}
}
OK,到此,底層需求操作編寫完畢!
5、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
">
<!--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="1000"/>
<!–當獲取連線失敗重試次數–>
<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>
<!--4.配置dao介面掃描包,動態的實現了Dao介面可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入 sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要掃描的dao包-->
<property name="basePackage" value="com.shun.dao"/>
</bean>
</beans>
注意:資料庫錯誤,建議使用spring預設連線池
<!--spring預設連線池-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
- 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
">
<!--掃描service下的包-->
<context:component-scan base-package="com.shun.service"/>
<!--2.將我們所有的業務類,注入到Spring,可以通過配置,或者註解實現-->
<bean id="BookServiceImpl" class="com.shun.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層搞定!
6、SpringMVC層
- web.xml
web專案建立方式:
右鍵專案 --> Add Frameworks Support --> Java EE --> Web Application --> 選中,然後點選OK,就建立成功了!
<?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: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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://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.shun.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
">
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
配置檔案,暫時結束!Controller 和 檢視層編寫
7、Controller 和 檢視層編寫
- BookController 類編寫 , 方法一:查詢全部書籍
@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";
}
}
- 編寫首頁 index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
<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="${pageContext.request.contextPath}/book/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}/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="${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/toUpdateBook?id=${book.getBookID()}">更改</a> |
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">刪除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
- BookController 類編寫 , 方法二:新增書籍
@RequestMapping("/toAddBook")
public String toAddPaper() {
return "addBook";
}
@RequestMapping("/addBook")
public String addPaper(Books books) {
System.out.println(books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
- 新增書籍頁面:addBook.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>
<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>
- BookController 類編寫 , 方法三:修改書籍
@RequestMapping("/toUpdateBook")
public String toUpdateBook(Model model, int id) {
Books books = bookService.queryBookById(id);
System.out.println(books);
model.addAttribute("book",books );
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Model model, Books book) {
System.out.println(book);
bookService.updateBook(book);
Books books = bookService.queryBookById(book.getBookID());
model.addAttribute("books", books);
return "redirect:/book/allBook";
}
- 修改書籍頁面 updateBook.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>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<input type="hidden" name="bookID" value="${book.getBookID()}"/>
書籍名稱:<input type="text" name="bookName" value="${book.getBookName()}"/>
書籍數量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/>
書籍詳情:<input type="text" name="detail" value="${book.getDetail() }"/>
<input type="submit" value="提交"/>
</form>
</div>
</body>
</html>
- BookController 類編寫 , 方法四:刪除書籍
@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
- 配置Tomcat,進行執行!
到目前為止,這個SSM專案整合已經完全的OK了,可以直接執行進行測試!
8、專案結構圖
- 總目錄
- src目錄
- web目錄