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{
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核心知识点总结!