SSM框架简单整合学习
1、准备工作:
框架搭建的环境准备,包括IDEA开发工具、maven环境搭建、Mysql
服务、Sqlyog
可视化界面、tomcat服务
2、步骤:
2.1数据库环境:
创建数据库表books,存放书籍信息包括:编号,名字,数量,价格,描述:
# 1.创建数据库
CREATE DATABASE ssmbuild_study;
# 2.使用数据库
USE ssmbuild_study;
# 3. 删除books表(如果该表存在)
DROP TABLE IF EXISTS books;
# 4. 创建books表
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书籍编号',
`bookName` VARCHAR(100) NOT NULL COMMENT '书籍名称',
`bookCounts` INT(11) NOT NULL COMMENT '库存数量',
`bookPrice` DOUBLE NOT NULL COMMENT '书籍价格',
`detail` VARCHAR(200) NOT NULL COMMENT '书籍描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
# 5.插入数据
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`bookPrice`,`detail`)VALUES
(1,'Java编程思想', 169, 103.8, '从入门到放弃'),
(2,'MySQL技术内幕', 100, 79.4, '七天精通MySQL'),
(3,'Java核心技术卷1', 59, 89.6, '半个月从进门到崩溃'),
(4,'Java核心技术卷2', 104, 78.3, '原地爆炸'),
(5,'Spring源码解析', 206, 68.7, '看到怀疑人生');
# 6验证表创建是否成功:
SELECT * FROM books;
查看数据库表创建是否成功:
2.2搭建项目,准备环境
1、新建maven项目,ssmbuild_study
,添加web支持
2、导入相关的maven依赖(junit
、数据库驱动,数据库连接池,jsp
、mybatis
、mybatis-spring
、spring-webmvc
、spring-jdbc
、lombok
)
<!--1.导入项目所需要的maven依赖-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</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.9</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.15</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
3、maven的静态资源过滤问题:
<!--2.maven静态资源过滤问题-->
<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>
4、项目的基本结构:分层创建包:
- 实体类:
pojo
service
层:service
dao
层:dao
controller
层:controller
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>
</configuration>
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">
</beans>
2.3 Mybatis
层编写
1、数据库配置文件:db.properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/ssmbuild_study?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
db.username=root
db.password=****
2、数据库对应实体类:pojo
包中编写books
类
package com.kevin.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author : kevin ding
* @date : 2022/2/4 13:51
* @description : 数据库表books对应的实体类
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int booID;
private String bookName;
private int bookCounts;
private double bookPrice;
private String detail;
}
3、dao
层编写BooksMapper
接口及对应的BooksMapper.xml
BooksMapper
接口的编写:
package com.kevin.dao;
import com.kevin.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author : kevin ding
* @date : 2022/2/4 13:57
* @description : BooksMapper的接口,包括和数据库交互的抽象方法 增删改查
*/
public interface BooksMapper {
//1.增 增加一条数据信息
int addBooks(Books books);
//2.删 根据id删除一条数据信息
int deleteBooksById(@Param("bookID") int id);
//3.改 修改数据信息
int updateBooks(Books books);
//4.查 根据id查询对应的数据
Books queryBooksById(@Param("bookID") int id);
//4.查 查询全部数据
List<Books> queryAllBooks();
}
BooksMapper.xml
的编写:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kevin.dao.BooksMapper">
<!--1.增加一条数据信息-->
<insert id="addBooks" parameterType="Books">
insert into ssmbuild_study.books(bookName, bookCounts, bookPrice, detail)
values (#{bookName}, #{bookCounts}, #{bookPrice}, #{detail})
</insert>
<!--2.根据id删除一条数据信息-->
<delete id="deleteBooksById" parameterType="int">
delete from ssmbuild_study.books
where bookID = #{bookID}
</delete>
<!--3.修改数据信息-->
<update id="updateBooks" parameterType="Books">
update ssmbuild_study.books
set bookName = #{bookName}, bookCounts = #{bookCounts}, bookPrice = #{bookPrice}, detail = #{detail}
where bookID = #{bookID};
</update>
<!--4.根据id查询对应的数据-->
<select id="queryBooksById" parameterType="int" resultType="Books">
select * from ssmbuild_study.books
where bookID = #{bookID};
</select>
<!--5.查询全部数据-->
<select id="queryAllBooks" resultType="Books">
SELECT * from ssmbuild_study.books;
</select>
</mapper>
4、service
层编写BookService
接口及接口实现类,用于调用dao
层
- BookService接口的编写,抽象方法与dao层的抽象方法类似
package com.kevin.service;
import com.kevin.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author : kevin ding
* @date : 2022/2/4 14:13
* @description : BookService接口的编写,抽象方法用于调用dao层方法
*/
public interface BookService {
//1.增 增加一条数据信息
int addBooks(Books books);
//2.删 根据id删除一条数据信息
int deleteBooksById(int id);
//3.改 修改数据信息
int updateBooks(Books books);
//4.查 根据id查询对应的数据
Books queryBooksById(int id);
//4.查 查询全部数据
List<Books> queryAllBooks();
}
- BookServiceImpl:实现BookService接口,重写抽象方法,调用dao层的方法,和数据库进行交互
package com.kevin.service;
import com.kevin.dao.BooksMapper;
import com.kevin.pojo.Books;
import java.util.List;
/**
* @author : kevin ding
* @date : 2022/2/4 14:14
* @description : BookService的实现类,实现BookService类,重写其抽象方法
*/
public class BooksServiceImpl implements BookService{
// service层调用dao层,该实现类中需要定义dao层的属性
private BooksMapper booksMapper;
public void setBooksMapper(BooksMapper booksMapper) {
this.booksMapper = booksMapper;
}
@Override
public int addBooks(Books books) {
return booksMapper.addBooks(books);
}
@Override
public int deleteBooksById(int id) {
return booksMapper.deleteBooksById(id);
}
@Override
public int updateBooks(Books books) {
return booksMapper.updateBooks(books);
}
@Override
public Books queryBooksById(int id) {
return booksMapper.queryBooksById(id);
}
@Override
public List<Books> queryAllBooks() {
return booksMapper.queryAllBooks();
}
}
5、Mybatis
核心配置文件,完成相关项的配置,包括起别名、添加mapper映射等
<?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.kevin.pojo"/>
</typeAliases>
<mappers>
<mapper resource="com/kevin/dao/BooksMapper.xml"/>
</mappers>
</configuration>
2.4Spring
层编写
该层主要完成与dao
、service
层的配置,上接MVC
和前端的交互,下接Mybatis
和数据库的交互,起到一个承上启下,进行中间连接整合的作用
1、spring
和dao
层的整合:spring-dao.xml
,并将其导入到总的spring
配置文件中
- 绑定数据源配置
- 创建dataSource的bean
- 创建sqlSessionFactory的bean
- (创建sqlSessionTemplate)
<?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.关联数据库配置文件database.properties-->
<context:property-placeholder location="classpath:db.properties"/>
<!--2.数据库连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--<property name="driverClassName" value="${driver}"/>-->
<!--<property name="url" value="${url}"/>-->
<!--<property name="username" value="${username}"/>-->
<!--<property name="password" value="${password}"/>-->
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssmbuild_study?useSSL=true&Unicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="****"/>
<property name="password" value="****"/>
</bean>
<!--3.创建sqlSessionFactory的bean-->
<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接口包,使得mapper的实现类由spring创建-->
<property name="basePackage" value="com.kevin.dao"/>
</bean>
</beans>
2、spring
和service
层的整合:spring-service.xml
- 扫描service包,自动注入
- service包中的实现类注入到bean
- 配置事务管理器
- 配置aop织入事务
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--1. 扫描service包 自动注入-->
<context:component-scan base-package="com.kevin.service"/>
<!--2.将bookService实现类注入bean-->
<bean id="bookService" class="com.kevin.service.BookServiceImpl">
<property name="booksMapper" ref="booksMapper"/>
</bean>
<!--3.配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--将数据源注入-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4. 配置事务-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置aop织入事务-->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.kevin.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
2.5 SpringMVC
层的编写
该层主要负责controller层和前端的交互
1、编写web.xml
- 注册dispatcherServlet:此处需要注意,绑定的spring配置文件为总的配置文件
- 解决乱码问题
<?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">
<!--1.注册dispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--绑定总的spring配置文件:applicationContext.xml-->
<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>
<!--2.解决乱码问题-->
<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>
</web-app>
2、创建spring-mvc.xml配置文件:
- 开启SpringMVC的注解驱动
- 静态资源默认的servlet配置
- 配置视图解析器
- 扫描web相关的bean
<?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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置SpringMVC-->
<!--1. 开启SpringMVC的注解驱动-->
<mvc:annotation-driven/>
<!--2. 静态资源默认的servlet配置-->
<mvc:default-servlet-handler/>
<!--3.配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--4.扫描web相关的bean-->
<context:component-scan base-package="com.kevin.controller"/>
</beans>
3、controller包中编写BooksController类,用于获取前端请求,跳转jsp页面,调用service层处理请求:
package com.kevin.controller;
import com.kevin.pojo.Books;
import com.kevin.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;
/**
* @author : kevin ding
* @date : 2022/2/4 14:41
* @description : controller层获取前端的请求,调用service层处理请求
*/
@Controller
@RequestMapping("/books")
public class BooksController {
// controller层调用service层
@Autowired
@Qualifier("bookServiceImpl")
private BookService bookService;
// 获取全部数据信息
@RequestMapping("/allBook")
public String getAllBooks(Model model){
List<Books> booksList = bookService.queryAllBooks();
model.addAttribute("queryResult", booksList);
return "allBooks";
}
}
3、跳转到了allBooks页面,在WEB-INF下新建jsp包,创建allBooks.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.staticfile.org/twitter-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">
<%--toAddBooks请求--%>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/books/toAddBooksPages">新增书籍</a>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/books/getAllBooks">显示全部书籍</a>
</div>
<div class="col-md-8 column">
<%--查询书籍请求--%>
<form class="form-inline" action="${pageContext.request.contextPath}/books/queryBooks" method="post" style="float: right">
<span style="color:red; font-weight:bold">${error}</span>
<input type="text" name="queryBookName" class="form-control" placeholder="请输入需要查询的书籍名称">
<input type="submit" value="查询" class="btn btn-primary">
</form>
</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>
<th>操作</th>
</tr>
</thead>
<%--书籍从数据库中查询出来,从这个list中遍历出来:foreach遍历--%>
<tbody>
<%--
foreach遍历,会在文件头部导入:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
--%>
<c:forEach var="books" items="${booksList}">
<tr>
<td>${books.bookID}</td>
<td>${books.bookName}</td>
<td>${books.bookCounts}</td>
<td>${books.bookPrice}</td>
<td>${books.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/books/toUpdateBooksPages?id=${books.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/books/deleteBooks/${books.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
4、将所有的spring配置文件均导入到总的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>
5、index.jsp:
<%--
Created by IntelliJ IDEA.
User: DCH
Date: 2022/2/2
Time: 16:53
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style type="text/css">
a {
text-decoration: none;
color: black;
font-size: 18px;
}
h2 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 4px;
}
</style>
</head>
<body>
<h2>
<a href="${pageContext.request.contextPath}/books/getAllBooks">点击进入书籍列表页</a>
</h2>
</body>
</html>
6、配置tomcat,启动运行(启动tomcat之前需要将所有的依赖在artifact中建立lib包)
tomcat成功启动之后,跳转到首页index.jsp:
2.6 Controller和jsp的完善
完成对数据库的增删改查操作
1、新增书籍:controller层:
/**
* 跳转到增加书籍页面:addBooks页面
* @return
*/
@RequestMapping("/toAddBooksPages")
public String toAddBooksPages(){
return "addBooks";
}
/**
* 添加书籍信息的请求
* @param books
* @return 添加完毕之后,重定向回到首页的请求中 @RequestMapping("/getAllBooks")
*/
@RequestMapping("/addBooks")
public String addBooks(Books books){
System.out.println("新添加的书籍:" + books);
bookService.addBooks(books);
// 新增书籍之后,重定向到书籍列表显示页面
return "redirect:/books/getAllBooks";
}
编写addBooks.jsp:
<%--
Created by IntelliJ IDEA.
User: DCH
Date: 2022/2/2
Time: 21:42
To change this template use File | Settings | File Templates.
--%>
<%@ 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.staticfile.org/twitter-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}/books/addBooks" method="post">
<%--name属性的值必须和数据库字段的名字一致,否则会报错;添加required属性之后,字段不能传空值--%>
<div class="form-group">
<label>书籍名称</label>
<input type="text" name="bookName" class="form-control" required>
</div>
<div class="form-group">
<label>书籍数量</label>
<input type="text" name="bookCounts" class="form-control" required>
</div>
<div class="form-group">
<label>书籍价格</label>
<input type="text" name="bookPrice" class="form-control" required>
</div>
<div class="form-group">
<label>书籍详情</label>
<input type="text" name="detail" class="form-control" required>
</div>
<input type="submit" class="form-control" value="添加">
</form>
</div>
</body>
</html>
点击书籍列表显示页面的新增书籍按钮,跳转:
点击添加按钮后,操作数据库完成新增,随后重定向到显示书籍列表页:
2、修改书籍信息:
/**
* 跳转到修改书籍页面:updateBooks页面
* 跳转页面之后,先显示原有的书籍信息(查询)
* @return
*/
@RequestMapping("/toUpdateBooksPages")
public String toUpdateBooksPages(int id, Model model){
Books books = bookService.queryBooksById(id);
System.out.println("根据id查询到的数据为:" + books);
// 通过model将获取到的数据传回给前端
model.addAttribute("queryResult",books);
return "updateBooks";
}
/**
* 修改书籍信息的请求
* @param books
* @return 添加完毕之后,重定向回到首页的请求中 @RequestMapping("/getAllBooks")
*/
@RequestMapping("/updateBooks")
public String updateBooks(Books books){
System.out.println("修改的书籍:" + books);
// service层调用方法更新
bookService.updateBooks(books);
// 修改后,重定向到书籍列表显示页面
return "redirect:/books/getAllBooks";
}
编写updateBooks.jsp:
<%--
Created by IntelliJ IDEA.
User: DCH
Date: 2022/2/3
Time: 9:07
To change this template use File | Settings | File Templates.
--%>
<%@ 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.staticfile.org/twitter-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}/books/updateBooks" method="post">
<%--此处需要新加一个隐藏的id字段内容,因为在update时,需要传入4个字段,而目前只有名称,数量,详情三个 --%>
<input type="hidden" name="bookID" value="${queryResult.bookID}">
<%--name属性的值必须和数据库字段的名字一致,否则会报错;添加required属性之后,字段不能传空值--%>
<div class="form-group">
<label>书籍名称</label>
<%--前端传进去哪个值,value中可以通过model中的键将该字段取出--%>
<input type="text" name="bookName" class="form-control" value="${queryResult.bookName}" required>
</div>
<div class="form-group">
<label>书籍数量</label>
<input type="text" name="bookCounts" class="form-control" value="${queryResult.bookCounts}" required>
</div>
<div class="form-group">
<label>书籍价格</label>
<input type="text" name="bookPrice" class="form-control" value="${queryResult.bookPrice}" required>
</div>
<div class="form-group">
<label>书籍详情</label>
<input type="text" name="detail" class="form-control" value="${queryResult.detail}" required>
</div>
<input type="submit" class="form-control" value="修改">
</form>
</div>
</body>
</html>
点击书籍列表页的修改按钮,跳转至修改页面,对选中的书籍编号进行修改,会先查询出该条数据显示出来:
点击修改之后,后端dao层完成对数据的update操作,修改成功之后,重定向到显示所有列表页面:
3、删除书籍:删除之后,跳转到获取所有书籍信息页面:
//通过restFul风格
@RequestMapping("/deleteBooks/{bookID}")
public String deleteBooks(@PathVariable("bookID") int id){
// service 层调用删除方法
bookService.deleteBooksById(id);
// 删除之后,重定向到书籍列表显示页面
return "redirect:/books/getAllBooks";
}
在书籍列表页面,点击右侧的删除按钮,直接完成删除,删除后重定向到书籍列表显示页面:
4、查询书籍信息(ByName):
查询结果无论单个或者多个均用list存储,在展示给前端时可以复用allBooks.jsp显示。
// 查询书籍
@RequestMapping("queryBooks")
public String queryBooks(String queryBookName, Model model){
List<Books> booksList = new ArrayList<>();
booksList = bookService.queryBooksByName(queryBookName);
for (Books books : booksList) {
System.out.println("查询出来的book信息为:" + books);
}
if(booksList.size() == 0){
booksList = bookService.queryAllBooks();
model.addAttribute("error", "未查到该书籍");
}
// 查询全部和查询单个页面可以复用,需要使用 List 接受并传递给前端
model.addAttribute("booksList", booksList);
return "allBooks";
}
根据指定名字查询书籍:
- 若没有查到该信息,显示未找到,并返回所有书籍信息:
- 查询到了对应的书籍:
至此,整合项目搭建完毕。完成了通过前端实现对后端的访问:项目分层结构如下所示:
controller层接收前端请求,调用service层,service层调用dao层,dao层负责完成和数据库的交互,并将处理结果沿路返回至controller层,controller层接收到处理后的数据,通过Model给前端进行解析并展示出来。