110_SSM框架
- 2021 年 9 月 12 日
- 筆記
- 120_SpringMVC
目錄
需求分析->功能設計->資料庫設計
環境要求
環境
要求
資料庫環境
CREATE DATABASE `ssm`CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `ssm`;
CREATE TABLE `ssm`.`books` ( `book_id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '書id', `book_name` VARCHAR(100) NOT NULL COMMENT '書名', `book_count` INT(10) NOT NULL COMMENT '數量', `book_detail` VARCHAR(1000) NOT NULL COMMENT '描述', PRIMARY KEY (`book_id`) ) ENGINE=INNODB CHARSET=utf8 COLLATE=utf8_general_ci;
INSERT INTO `ssm`.`books` (`book_name`, `book_count`, `book_detail`) VALUES ('Java', '1', '從入門到放棄');
INSERT INTO `ssm`.`books` (`book_name`, `book_count`, `book_detail`) VALUES ('MySQL', '11', '從刪庫到跑路');
INSERT INTO `ssm`.`books` (`book_name`, `book_count`, `book_detail`) VALUES ('Linux', '5', 'j');
SELECT * FROM books LIMIT 0, 1000;
基本環境搭建
創建maven項目
pom.xml添加依賴,添加資源導出
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="//maven.apache.org/POM/4.0.0"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qing</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- //mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!-- //mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!-- //mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!-- //mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- //mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- //mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!-- //mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- //mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- //mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- //mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<!-- //mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
<!-- //mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<!--配置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>
</project>
idea連接資料庫
提交項目到Git
[email protected]:wl3pbzhyq/ssm.git
創建基礎包
創建配置文件
db.properties
driver=com.mysql.jdbc.Driver
# 如果使用的是MySQL8.0+,增加一個時區的配置:&serverTimezone=Asia/Shanghai
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"//mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--開啟駝峰映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--別名-->
<typeAliases>
<package name="com.qing.pojo"/>
</typeAliases>
</configuration>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="//www.springframework.org/schema/beans"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//www.springframework.org/schema/beans
//www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
創建實體類
package com.qing.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookId;
private String bookName;
private int bookCount;
private String bookDetail;
}
創建Mapper介面和Mapper.xml
package com.qing.dao;
import com.qing.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BooksMapper {
/**
* 新增書
* @param books
* @return
*/
int add(Books books);
/**
* 根據Id刪除書
* @param bookId
* @return
*/
int deleteById(@Param("bookId") int bookId);
/**
* 修改書
* @param books
* @return
*/
int update(Books books);
/**
* 根據Id獲取書
* @param bookId
* @return
*/
Books getBooksById(@Param("bookId") int bookId);
/**
* 獲取全部書
* @return
*/
List<Books> listBooks();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"//mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qing.dao.BooksMapper">
<!--新增書-->
<insert id="add" parameterType="Books">
insert into ssm.books(book_name, book_count, book_detail)
values (#{bookName},#{bookCount},#{bookDetail})
</insert>
<!--根據Id刪除書-->
<delete id="deleteById" parameterType="int">
delete from ssm.books where book_id = #{bookId}
</delete>
<!--修改書-->
<update id="update" parameterType="Books">
update ssm.books
set book_name=#{bookName},book_count=#{bookCount},book_detail=#{bookDetail}
where book_id=#{bookId}
</update>
<!--根據Id獲取書-->
<select id="getBooksById" parameterType="int" resultType="Books">
select * from ssm.books
where book_id=#{bookId}
</select>
<!--獲取全部書-->
<select id="listBooks" resultType="Books">
select * from ssm.books
</select>
</mapper>
註冊Mapper到mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"//mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--別名-->
<typeAliases>
<package name="com.qing.pojo"/>
</typeAliases>
<!-- 將包內的映射器介面實現全部註冊為映射器 -->
<mappers>
<package name="com.qing.dao"/>
</mappers>
</configuration>
創建Service介面和實現類
package com.qing.service;
import com.qing.pojo.Books;
import java.util.List;
public interface BooksService {
/**
* 新增書
* @param books
* @return
*/
int add(Books books);
/**
* 根據Id刪除書
* @param bookId
* @return
*/
int deleteById(int bookId);
/**
* 修改書
* @param books
* @return
*/
int update(Books books);
/**
* 根據Id獲取書
* @param bookId
* @return
*/
Books getBooksById(int bookId);
/**
* 獲取全部書
* @return
*/
List<Books> listBooks();
}
package com.qing.service;
import com.qing.dao.BooksMapper;
import com.qing.pojo.Books;
import java.util.List;
public class BooksServiceImpl implements BooksService {
// service調dao層,組合Dao
private BooksMapper booksMapper;
public void setBooksMapper(BooksMapper booksMapper) {
this.booksMapper = booksMapper;
}
public int add(Books books) {
return booksMapper.add(books);
}
public int deleteById(int bookId) {
return booksMapper.deleteById(bookId);
}
public int update(Books books) {
return booksMapper.update(books);
}
public Books getBooksById(int bookId) {
return booksMapper.getBooksById(bookId);
}
public List<Books> listBooks() {
return booksMapper.listBooks();
}
}
Spring配置文件
創建配置文件 spring-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="//www.springframework.org/schema/beans"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xmlns:context="//www.springframework.org/schema/context"
xsi:schemaLocation="//www.springframework.org/schema/beans
//www.springframework.org/schema/beans/spring-beans.xsd //www.springframework.org/schema/context //www.springframework.org/schema/context/spring-context.xsd">
<!--關聯資料庫配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--連接池
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>
<!--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">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要掃描的dao包-->
<property name="basePackage" value="com.qing.dao"/>
</bean>
</beans>
創建配置文件 spring-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="//www.springframework.org/schema/beans"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xmlns:context="//www.springframework.org/schema/context"
xmlns:tx="//www.springframework.org/schema/tx"
xmlns:aop="//www.springframework.org/schema/aop"
xsi:schemaLocation="//www.springframework.org/schema/beans
//www.springframework.org/schema/beans/spring-beans.xsd
//www.springframework.org/schema/context
//www.springframework.org/schema/context/spring-context.xsd
//www.springframework.org/schema/tx
//www.springframework.org/schema/tx/spring-tx.xsd
//www.springframework.org/schema/aop
//www.springframework.org/schema/aop/spring-aop.xsd">
<!--掃描service下的包-->
<context:component-scan base-package="com.qing.service"/>
<!--將業務類注入到Spring,通過配置,也可以通過註解實現-->
<bean id="BookServiceImpl" class="com.qing.service.BooksServiceImpl">
<property name="booksMapper" ref="booksMapper"/>
</bean>
<!--聲明式事務配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入數據源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--aop事務支援-->
<!--結合aop實現事務的織入-->
<!--配置事務通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--給那些方法配置事務-->
<!--配置事務的傳播特性-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事務切入-->
<aop:config>
<aop:pointcut id="txPointCout" expression="execution(* com.qing.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCout"/>
</aop:config>
</beans>
創建配置文件 spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="//www.springframework.org/schema/beans"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="//www.springframework.org/schema/mvc"
xmlns:context="//www.springframework.org/schema/context"
xsi:schemaLocation="//www.springframework.org/schema/beans
//www.springframework.org/schema/beans/spring-beans.xsd
//www.springframework.org/schema/mvc
//www.springframework.org/schema/mvc/spring-mvc.xsd
//www.springframework.org/schema/context
//www.springframework.org/schema/context/spring-context.xsd">
<!--註解驅動-->
<mvc:annotation-driven/>
<!--靜態資源過濾-->
<mvc:default-servlet-handler/>
<!--掃描包-->
<context:component-scan base-package="com.qing.controller"/>
<!--視圖解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
applicationContext.xml導入spring-dao.xml spring-service.xml spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="//www.springframework.org/schema/beans"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//www.springframework.org/schema/beans
//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>
項目添加web框架支援
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee //xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--DispatchServlet-->
<servlet>
<servlet-name>spingmvc</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>spingmvc</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>
創建Controller
package com.qing.controller;
import com.qing.pojo.Books;
import com.qing.service.BooksService;
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("/books")
public class BooksController {
@Autowired
@Qualifier("BookServiceImpl")
private BooksService booksService;
@RequestMapping("/listBooks")
public String listBooks(Model model) {
List<Books> list = booksService.listBooks();
model.addAttribute("list",list);
return "listBooks";
}
}
創建首頁和書庫頁
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首頁</title>
</head>
<body>
<h1><a href="${pageContext.request.contextPath}/books/listBooks">進入書庫</a></h1>
</body>
</html>
<%@ taglib prefix="c" uri="//java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>書庫</title>
</head>
<body>
<h1>書庫</h1>
<div>
<table class="table table-hover table-striped">
<thead>
<tr>
<th>書籍編號</th>
<th>書籍名稱</th>
<th>書籍數量</th>
<th>書籍描述</th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookId}</td>
<td>${book.bookName}</td>
<td>${book.bookCount}</td>
<td>${book.bookDetail}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>