SsmBuild
ssm整合:Mybatis层
1.数据库准备工作
CREATE DATABASE ssmbuild;
USE ssmbuild;
DROP TABLE
IF
EXISTS TABLE 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, '从进门到进牢' );
2.依赖导入以及静态资源过滤
<!--依赖:junit,数据库驱动,连接池,servlet,jsp,mybatis,mybatis-spring,spring-->
<dependencies>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</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 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--jsp-->
<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>
<!-- mybatis-spring-->
<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.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
<!--静态资源导出问题-->
<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.数据库连接
注意设置 *serverTimezone=Asia/Shanghai*
4.创建项目目录结构
5.添加配置文件
在resources文件夹中创建以下配置文件
1.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>
<typeAliases>
<package name="com.tz.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.tz.mapper.BookMapper"/>
</mappers>
</configuration>
2.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
3.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=root
- applicationContext.xml的标准模板,也是标准的spring.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 https://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>
- 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>
6.创建实体类、持久层
1.在pojo文件夹下创建实体类Books.java
package com.tz.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;
}
2.在mapper文件夹下创建接口类BookMapper.java
package com.tz.mapper;
import com.tz.pojo.Books;
import java.util.List;
public interface BookMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBook(Books books);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBook();
}
3.在mapper文件夹下创建BookMapper.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.tz.mapper.BookMapper">
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books(bookName,bookCounts,detail)
value (#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBook" 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" resultType="Books">
select *
from ssmbuild.books
where bookID=#{bookID};
</select>
<select id="queryAllBook" resultType="Books">
select *
from ssmbuild.books;
</select>
</mapper>
注意:此处为Mapper.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> </mapper>
7.业务层Service
1.业务层接口类BookService.java
package com.tz.service;
import com.tz.pojo.Books;
import java.util.List;
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBook(int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBook();
}
2.接口实现类BookServiceImpl.java
package com.tz.service;
import com.tz.mapper.BookMapper;
import com.tz.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService{
//service层调用持久层:组合dao
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books books) {
return bookMapper.addBook(books);
}
@Override
public int deleteBook(int id) {
return bookMapper.deleteBook(id);
}
@Override
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
8.整合完Mybatis层后,文件架结构如下
ssm整合:Spring层
1.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
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://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="10000"/>
<!--当偶去连接失败后,重试次数-->
<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>
<!--配置dao接口扫描包,动态的实现了dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--要注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.tz.mapper"/>
</bean>
</beans>
在recourse文件夹下创建spring-dao.xml文件,spring-dao.xml文件主要用来配置数据库连接
2.Spring-service.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
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.扫描service下的包-->
<context:component-scan base-package="com.tz.service"/>
<!--2.将我们所有的业务类注入到Spring,可以通过配置,或者注解实现-->
<bean id="BookServiceImpl" class="com.tz.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3.声明事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4.声明事务-->
</beans>
在recourse文件夹下创建spring-service.xml,spring-service.xml用来绑定service业务。
-
在applicationContext.xml文件中导入spring-service.xml和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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="classpath: spring-dao.xml"/> <import resource="classpath: spring-service.xml"/> </beans>
ssm整合:SpringMVC层
1.增加web的支持
2.web.xml
- 注意web.xml必须为4.0版本
<?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>
在recourses下创建出spring-mvc.xml文件。
然后再applictionContext.xml中添加一行,导入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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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>
3.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
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.注解驱动-->
<mvc:annotation-driven/>
<!--2.静态资源过滤-->
<mvc:default-servlet-handler/>
<!--3.扫描包:controller-->
<context:component-scan base-package="com.tz.controller"/>
<!--4.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
注意上方的链接不能写错,顺序也不能写错
完善CRUD书籍功能
1.BookController.java
在controller文件夹中创建BookController.java用来控制页面的跳转
package com.tz.controller;
import com.tz.pojo.Books;
import com.tz.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;
@Controller
@RequestMapping("/book")
public class BookController {
//controller调用service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部的书籍,并且返回到一个书籍展示页面
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list=bookService.queryAllBook();
model.addAttribute("list",list);
return "allBook";
}
}
2.allBook.jsp
创建一个jsp文件夹,在内部创建一个allBook.jsp的页面
allBook.jsp的作用:从主页面index.jsp
发送的请求,经过Controller处理后,跳转到allBook.jsp
页面
<%--
Created by IntelliJ IDEA.
User: TZ
Date: 2020/12/8
Time: 16:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍展示</title>
</head>
<body>
<h1>书籍展示页面</h1>
</body>
</html>
3.index.jsp
添加一个链接
<%--
Created by IntelliJ IDEA.
User: TZ
Date: 2020/12/8
Time: 15:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
</h3>
</body>
</html>
4.运行一下tomcat
跳转成功。
-
美化一下前端页面
index.jsp页面中添加css样式
<%-- Created by IntelliJ IDEA. User: TZ Date: 2020/12/8 Time: 15:11 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: black; font-size: 18px; } h3{ width: 180px; height: 38px; margin: 100px auto; text-align: center; line-height: 38px; background: deepskyblue; border-radius: 5px; } </style> </head> <body> <h3> <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a> </h3> </body> </html>
2.在web.xml文件中添加BootStrap框架美化界面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: TZ
Date: 2020/12/8
Time: 16:10
To change this template use File | Settings | File Templates.
--%>
<%@ 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 colum">
<div class="page-header">
<h1>
<small>书籍列表-----显示所有书籍</small>
</h1>
</div>
</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>
</tr>
</thead>
<%--书籍从数据库里面查询出来,从这个list中遍历出来:foreach--%>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
5.完善功能页面
-
index.jsp
<%-- Created by IntelliJ IDEA. User: TZ Date: 2020/12/8 Time: 15:11 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: black; font-size: 18px; } h3{ width: 180px; height: 38px; margin: 100px auto; text-align: center; line-height: 38px; background: deepskyblue; border-radius: 5px; } </style> </head> <body> <h3> <a href="${pageContext.request.contextPath}/book/allBook">进入查询书籍页面</a> </h3> </body> </html>
-
updateBook.jsp
<%-- Created by IntelliJ IDEA. User: TZ Date: 2020/12/8 Time: 20:57 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>修改书籍</title> <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 colum"> <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="${QBook.bookID}" > <div class="form-group"> <label for="bkname">书籍名称:</label> <input type="text" name="bookName" class="form-control" id="bkname" value="${QBook.bookName}" required > </div> <div class="form-group"> <label for="bkcount">书籍数量:</label> <input type="text" name="bookCounts" class="form-control" id="bkcount" value="${QBook.bookCounts}" required> </div> <div class="form-group"> <label for="detail">书籍描述:</label> <input type="text" name="detail" class="form-control" id="detail" value="${QBook.detail}" required> </div> <div class="form-group"> <input type="submit" class="form-control" value="修改"> </div> </form> </div> </body> </html>
-
allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: TZ Date: 2020/12/8 Time: 16:10 To change this template use File | Settings | File Templates. --%> <%@ 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 colum"> <div class="page-header"> <h1> <small>书籍列表-----显示所有书籍</small> </h1> </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> <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> <%--书籍从数据库里面查询出来,从这个list中遍历出来:foreach--%> <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/toUpdateBook?id=${book.bookID}">修改</a> | <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}" >删除</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> </body> </html>
-
addBook.jsp
<%-- Created by IntelliJ IDEA. User: TZ Date: 2020/12/8 Time: 19:36 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>添加书籍</title> <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 colum"> <div class="page-header"> <h1> <small>新增书籍</small> </h1> </div> </div> </div> <form action="${pageContext.request.contextPath}/book/addBook" method="post"> <div class="form-group"> <label for="bkname">书籍名称</label> <input type="text" name="bookName" class="form-control" id="bkname" required > </div> <div class="form-group"> <label for="bkcount">书籍数量</label> <input type="text" name="bookCounts" class="form-control" id="bkcount" required> </div> <div class="form-group"> <label for="detail">书籍描述</label> <input type="text" name="detail" class="form-control" id="detail" required> </div> <div class="form-group"> <input type="submit" class="form-control" value="添加"> </div> </form> </div> </body> </html>
6.完善Controller
在Controller中完善增删改查的功能
package com.tz.controller;
import com.tz.pojo.Books;
import com.tz.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 {
//controller调用service层
@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 toAddPaper(){
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("addBook=>"+books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
//跳转到修改页面
@RequestMapping("/toUpdateBook")
public String toUpdateBook(int id,Model model){
Books books = bookService.queryBookById(id);
model.addAttribute("QBook",books);
return "updateBook";
}
//修改书籍
@RequestMapping("/updateBook")
public String updateBook(Books books){
System.out.println(books);
bookService.updateBook(books);
return "redirect:/book/allBook";
}
//删除书籍
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id){
bookService.deleteBook(id);
return "redirect:/book/allBook";
}
}
7.aop
1.在pom.xml中添加事务依赖
<?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>tz.ssmbuild</groupId>
<artifactId>ssmbuild</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>12</maven.compiler.source>
<maven.compiler.target>12</maven.compiler.target>
</properties>
<!--依赖:junit,数据库驱动,连接池,servlet,jsp,mybatis,mybatis-spring,spring-->
<dependencies>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</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 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--jsp-->
<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>
<!-- mybatis-spring-->
<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.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- 事务植入-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
<!--静态资源导出问题-->
<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>
2.添加和配置事务
在spring-service.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--1.扫描service下的包-->
<context:component-scan base-package="com.tz.service"/>
<!--2.将我们所有的业务类注入到Spring,可以通过配置,或者注解实现-->
<bean id="BookServiceImpl" class="com.tz.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3.声明事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4.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="txPointCut" expression="execution(* com.tz.mapper.*.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
注意文件的头部约束!!!!!!!
3.注意导入事务jar包
8.开启Mybatis日志
在mybatis-config.xml文件中添加logImpl的配置
<?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>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.tz.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.tz.mapper.BookMapper"/>
</mappers>
</configuration>
9.搜索功能
添加搜索功能需要在多个页面中添加功能
最终代码
- controller
BookController.java
package com.tz.controller;
import com.tz.pojo.Books;
import com.tz.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.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
//controller调用service层
@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 toAddPaper(){
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("addBook=>"+books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
//跳转到修改页面
@RequestMapping("/toUpdateBook")
public String toUpdateBook(int id,Model model){
Books books = bookService.queryBookById(id);
model.addAttribute("QBook",books);
return "updateBook";
}
//修改书籍
@RequestMapping("/updateBook")
public String updateBook(Books books){
System.out.println(books);
bookService.updateBook(books);
return "redirect:/book/allBook";
}
//删除书籍
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id){
bookService.deleteBook(id);
return "redirect:/book/allBook";
}
//根据名称查询书籍
@RequestMapping("/queryBookByName")
public String queryBook(String queryBookName,Model model){
List<Books> list = bookService.queryBookByName(queryBookName);
//如果没有查询到,就返回全部书籍,并且将错误信息提交给前端
if (list==null){
list=bookService.queryAllBook();
model.addAttribute("error","未找到");
}
model.addAttribute("list",list);
return "allBook";
}
}
-
mapper
-
BookMapper.java
package com.tz.mapper; import com.tz.pojo.Books; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BookMapper { //增加一本书 int addBook(Books books); //删除一本书 int deleteBook(@Param("bookID") int id); //更新一本书 int updateBook(Books books); //查询一本书 Books queryBookById(@Param("bookID") int id); //查询全部的书 List<Books> queryAllBook(); //根据书名查询书籍 List<Books> queryBookByName(@Param("bookName") String bookName); }
-
BookMapper.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.tz.mapper.BookMapper"> <insert id="addBook" parameterType="Books"> insert into ssmbuild.books (bookName,bookCounts,detail) value (#{bookName},#{bookCounts},#{detail}); </insert> <delete id="deleteBook" 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" resultType="Books"> select * from ssmbuild.books where bookID=#{bookID}; </select> <select id="queryAllBook" resultType="Books"> select * from ssmbuild.books; </select> <select id="queryBookByName" resultType="Books"> select * from ssmbuild.books where bookName Like '%${bookName}%' ; </select> </mapper>
-
-
service
-
BookService.java
package com.tz.service; import com.tz.pojo.Books; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BookService { //增加一本书 int addBook(Books books); //删除一本书 int deleteBook(int id); //更新一本书 int updateBook(Books books); //查询一本书 Books queryBookById(int id); //查询全部的书 List<Books> queryAllBook(); //根据名称查询书籍 List<Books> queryBookByName(String bookName); }
-
BookServiceImpl.java
package com.tz.service; import com.tz.mapper.BookMapper; import com.tz.pojo.Books; import java.util.List; public class BookServiceImpl implements BookService{ //service层调用持久层:组合dao private BookMapper bookMapper; public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public int addBook(Books books) { return bookMapper.addBook(books); } @Override public int deleteBook(int id) { return bookMapper.deleteBook(id); } @Override public int updateBook(Books books) { return bookMapper.updateBook(books); } @Override public Books queryBookById(int id) { return bookMapper.queryBookById(id); } @Override public List<Books> queryAllBook() { return bookMapper.queryAllBook(); } @Override public List<Books> queryBookByName(String bookName) { return bookMapper.queryBookByName(bookName); } }
-
allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: TZ Date: 2020/12/8 Time: 16:10 To change this template use File | Settings | File Templates. --%> <%@ 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 colum"> <div class="page-header"> <h1> <small>书籍列表-----显示所有书籍</small> </h1> </div> </div> <div class="row"> <div class="col-md-4 column"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a> <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a> </div> <div class="col-md-8 column"> <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBookByName" 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> <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> <%--书籍从数据库里面查询出来,从这个list中遍历出来:foreach--%> <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/toUpdateBook?id=${book.bookID}">修改</a> | <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}" >删除</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> </body> </html>