1.0 环境要求
- IDEA
- MySQL 5.7.19
- Tomcat 9
- Maven 3.6
1.1 数据库
创立书籍数据库表,包含书籍编号,书籍名称,书籍数量以及书籍形容。
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.2 根本环境搭建
- 新建一 Maven 我的项目!ssmbuild,增加 web 的反对
- 导入相干的 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.fanjh</groupId>
<artifactId>ssmbuild</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 导入依赖 -->
<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</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>
</project>
留神:这里导包之后记得查看 project structure 中有无相干包,个别要手动导入
- 建设根本构造和框架:
- com.fanjh.pojo
- com.fanjh.dao
- com.fanjh.service
- com.fanjh.controller
- mybatis-config.xml
这里给出最终构造
前端调用 controller 层,controller 层调用 service 层,service 层调用 dao 层
1.2 mybatis 层编写
- 数据库配置文件 database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=fjhmysql
- 连贯数据库
- 编写 mybatis 外围配置文件: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>
<!--mybatis 外围配置文件 -->
<!-- 配置数据源等交给 spring 去做,这里次要别名和注册映射 -->
<typeAliases>
<package name="com.fanjh.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.fanjh.dao.BookMapper"/>
</mappers>
</configuration>
- 编写数据库对应实体类:com.fanjh.pojo.Books
应用 lombok 插件
package com.fanjh.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;
}
- 紧接着编写 dao 层的 mapper 接口
package com.fanjh.dao;
import com.fanjh.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
// 增删改查办法
public interface BookMapper {int addBook(Books book);
int deleteBookById(@Param("bookId") int id);
int updateBook(Books book);
Books queryBookById(@Param("bookId") int id);
List<Books> queryAllBook();}
- 马上编写接口对应的 Mapper.xml 文件(对应 sql 语句), 须要注册到 mybatis.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.fanjh.dao.BookMapper">
<insert id = "addBook" parameterType="Books">
insert into ssmbuild.books(bookName, bookCounts, detail)
VALUES(#{bookName}, #{bookCounts}, #{detail})
</insert>
<delete id="deleteBookById" parameterType="int">
DELETE from ssmbuild.books where bookID = #{bookId}
</delete>
<update id="updateBook" parameterType="Books">
update ssmbuild.books
set bookName=#{bookName}, bookCounts=#{bookCounts}, detail=#{detail}
where bookID=#{bookID};
</update>
<select id="queryBookById" parameterType="int" resultType="Books">
select * from ssmbuild.books where bookID=#{bookId};
</select>
<select id="queryAllBook" resultType="Books">
select * FROM ssmbuild.books
</select>
</mapper>
至此,搞定 dao 层,接下来业务层。
- 编写 Service 层接口和实现类
接口:
package com.fanjh.service;
import com.fanjh.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookService {int addBook(Books book);
int deleteBookById(int id);
int updateBook(Books book);
Books queryBookById(int id);
List<Books> queryAllBook();}
实现类:
package com.fanjh.service;
import com.fanjh.dao.BookMapper;
import com.fanjh.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
//service 层调 dao 层
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {this.bookMapper = bookMapper;}
public int addBook(Books book) {return bookMapper.addBook(book);
}
public int deleteBookById(int id) {return bookMapper.deleteBookById(id);
}
public int updateBook(Books book) {return bookMapper.updateBook(book);
}
public Books queryBookById(int id) {return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {return bookMapper.queryAllBook();
}
}
能够看到,service 层的办法都是间接调用 dao 层的办法,到此底层需要操作编写结束。
1.3 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">
<!-- 配置整合 mybatis-->
<!--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="10000"/>
<!-- 当获取连贯失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--3.sqlsessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="datasource"/>
<!-- 配置 MyBaties 全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4. 配置 dao 接口扫描包,动静的实现了 Dao 接口能够注入到 spring 容器中 -->
<!-- 以前要新建一个 dao 接口实现类,而后在 spring 中注册实现类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入 sqlsessionfactory 即可 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 要扫描的包 -->
<property name="basePackage" value="com.fanjh.dao"/>
</bean>
</beans>
- 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">
<!-- 如果下面配置错了,常会报错:通配符很全面,但无奈找到元素。。。的申明 -->
<!--1. 扫描 service 包 -->
<context:component-scan base-package="com.fanjh.service"/>
<!--2. 将咱们所有的业务类,注入到 spring,能够通过配置或注解实现 @Service @Autowired-->
<bean id="BookServiceImpl" class="com.fanjh.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 层搞定,spring 就是个大容器,整合 dao 层和 service 层,也是实现了 dao 层和 service 层的拆散——解耦。
1.4 springMVC 层
- 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">
<!--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: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
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置映射器、适配器、视图解析器 -->
<!--1. 注解驱动 -->
<mvc:annotation-driven/>
<!--2. 动态资源过滤 -->
<mvc:default-servlet-handler/>
<!--3. 扫描包 -->
<context:component-scan base-package="com.fanjh.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">
<!--spring 外围配置文件 -->
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
至此,所有的配置文件暂告一段落,接下来编写 Controller 和视图层,Controller 和视图层交互,而后调用 service 层。
- BookController 类编写,增删改查书籍(Controller 层的编写须要实时对照视图层)
package com.fanjh.controller;
import com.fanjh.pojo.Books;
import com.fanjh.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 {
@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 toAddBook(){return "addBook";}
// 增加书籍的申请
@RequestMapping("/addBook")// 执行完后,重定向到 allbook 页面
public String addBook(Books books){System.out.println("addBook=>" + books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
// 跳转到批改书籍页面
@RequestMapping("/toUpdate")
public String toUpdateBook(int id, Model model){Books books = bookService.queryBookById(id);// 依据 id 取到图书
model.addAttribute("Qbooks",books);// 将图书返回给前端
return "updateBook";
}
// 批改书籍
// 接管到前端传来的数据,调用 service 层执行批改操作
@RequestMapping("/updateBook")
public String updateBook(Books books){System.out.println("updateBook=>" + books);
bookService.updateBook(books);
return "redirect:/book/allBook";
}
// 删除书籍
@RequestMapping("/deleteBook/{bookId}")//restful 格调
public String deleteBook(@PathVariable("bookId") int id){bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
}
- 编写首页index.jsp
<%--
Created by IntelliJ IDEA.
User: fjh990
Date: 2020/11/7
Time: 12:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> 首页 </title>
<style>
a{
text-decoration: none;
color: gold;
font-size: 50px;
}
h3{
width:500px;
height:80px;
margin:500px auto;
text-align: center;
line-height: 80px;
background: black;
border-radius: 6px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook"> 进入书籍页面 </a>
</h3>
</body>
</html>
- 新建三个.jsp 文件:
- allBook:显示所有书籍
- addBook:减少书籍
- updateBook: 批改书籍
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>
<!-- 引入 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>
<%-- 减少书籍按钮, 点击后跳到 controller 页面,而后依据 return 值到 addbook.jsp--%>
<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="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.bookID}"> 批改 </a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}"> 删除 </a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
addBook.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> 新增书籍 </title>
<!-- 引入 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>
<%-- 点击增加按钮后,跳转到 /book/addBook 执行增加操作(属性名肯定要统一)--%>
<form action="${pageContext.request.contextPath}/book/addBook"
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>
这里拿减少书籍举例梳理整个流程:
- 前端点击新增书籍按钮后,跳转到 controller 找到 /book/toAddBook,跳转到 toAddBook 页面
- 依据 toAddBook 页面的 return 语句,拼接后找到 /WEB-INF/jsp/addBook.jsp 文件
- 依据页面展现,填写所要减少的书籍的内容
- 点击“增加”按钮,返回 controller 找到 /book/addBook 页面,并传回 books 信息
- controller 层调用 service 层执行减少书籍操作。
- 返回到显示书籍页面
updateBook.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> 批改书籍 </title>
<!-- 引入 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>
<%-- 咱们提交了批改的 sql 申请,然而批改失败,spring 接管事务后不须要显式的配置,不是事务问题
看一下 sql 语句,是否执行胜利:sql 执行失败
前端传递暗藏域 --%>
<form action="${pageContext.request.contextPath}/book/updateBook"
method="post">
<input type="hidden" name="bookID" value="${Qbooks.bookID}">
书籍名称:<input type="text" name="bookName" value="${Qbooks.bookName}" required><br><br><br>
书籍数量:<input type="text" name="bookCounts" value="${Qbooks.bookCounts}" required><br><br><br>
书籍详情:<input type="text" name="detail" value="${Qbooks.detail}" required><br><br><br>
<input type="submit" value="批改">
</form>
</div>
</body>
</html>
至此,整个我的项目整合结束
最初
欢送关注公众号:前程有光,支付一线大厂 Java 面试题总结 + 各知识点学习思维导 + 一份 300 页 pdf 文档的 Java 外围知识点总结!