赞
踩
学习视频来自于:秦疆(遇见狂神说)Bilibili地址
他的自学网站:kuangstudy
保持热爱、奔赴山河
知识要求
需要熟练掌握MySQL数据库(建表+CRUD),Spring、SpringMVC、JavaWeb、MyBatis、html、css、JavaScript、Jquery。
创建一个存放书籍数据的数据库表
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,'从进门到进牢');
<dependencies> <!--单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.10</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.7</version> </dependency> <!--数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.29</version> </dependency> <!--数据库连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.11</version> </dependency> <!--spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.22</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.22</version> </dependency> <!--aop织入--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.9.1</version> </dependency> <!--servlet、jsp、jstl--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</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>
druid.driverClassName=com.mysql.cj.jdbc.Driver
druid.url=jdbc:mysql://localhost:3306/ssmbuild?userUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT%2B8
druid.username=root
druid.password=root
IDEA关联数据库(关联后写mapper方便一些,不关联也能开发)
编写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> <!-- 日志--> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!-- 实体类别名--> <typeAliases> <package name="pers.tianyu.pojo"/> </typeAliases> <!-- mapper映射--> <mappers> <package name="pers.tianyu.dao"/> </mappers> </configuration>
package pers.tianyu.pojo;
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
/**
*有参/无参构造方法
*set/get方法
*toString方法
**/
}
package pers.tianyu.dao; import pers.tianyu.pojo.Books; import java.util.List; public interface BookMapper { // 增加一个Book int addBook(Books book); // 根据id删除一个Book,@Param("id"):可以为参数指别名 int deleteBookById(@Param("bookID") int id); // 更新Book int updateBook(Books book); // 根据id查询,返回Books Books queryBookById(@Param("bookID") int id); // 查询全部Book,返回list集合 List<Books> queryAllBook(); // 根据名字查询书籍 List<Books> queryBookByName(@Param("bookName") String bookName); }
<?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="pers.tianyu.dao.BookMapper"> <!-- 增加一个Book--> <insert id="addBook" parameterType="books"> insert into ssmbuild.books(bookName, bookCounts, detail) VALUES (#{bookName}, #{bookCounts}, #{detail}) </insert> <!-- 根据id删除一个Book--> <delete id="deleteBookById" parameterType="_int"> delete from ssmbuild.books where bookID = #{bookID} </delete> <!-- 更新Book--> <update id="updateBook" parameterType="books"> update ssmbuild.books set bookName = #{bookName}, bookCounts = #{bookCounts}, detail = #{detail} where bookID = #{bookID} </update> <!-- 根据id查询,返回Books--> <select id="queryBookById" resultType="books" parameterType="_int"> select bookID, bookName, bookCounts, detail from ssmbuild.books where bookID = #{bookID} </select> <!-- 查询全部Book,返回list集合--> <select id="queryAllBook" resultType="books"> select bookID, bookName, bookCounts, detail from ssmbuild.books </select> <!-- 根据名字查询书籍--> <select id="queryBookByName" resultType="books"> select bookID, bookName, bookCounts, detail from ssmbuild.books where bookName like "%"#{bookName}"%" </select> </mapper>
package pers.tianyu.service; import pers.tianyu.pojo.Books; import java.util.List; public interface BookService { // 增加一个Book int addBook(Books book); // 根据id删除一个Book int deleteBookById(int id); // 更新Book int updateBook(Books book); // 根据id查询,返回Books Books queryBookById(int id); // 查询全部Book,返回list集合 List<Books> queryAllBook(); // 根据名字查询书籍 List<Books> queryBookByName(String bookName); }
实现类:pers.tianyu.service.BookServiceImpl
package pers.tianyu.service; import pers.tianyu.dao.BookMapper; import pers.tianyu.pojo.Books; import java.util.List; public class BookServiceImpl implements BookService { // 调用dao层的操作,设置一个set接口,方便调用 private BookMapper bookMapper; public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public int addBook(Books book) { return bookMapper.addBook(book); } @Override public int deleteBookById(int id) { return bookMapper.deleteBookById(id); } @Override public int updateBook(Books book) { return bookMapper.updateBook(book); } @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); } }
<?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"> <!--配置整合mybatis--> <!-- 1.关联数据库配置文件--> <context:property-placeholder location="classpath:database.properties"/> <!-- 2.数据库连接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <!-- 配置连接池属性--> <property name="driverClassName" value="${druid.driverClassName}"/> <property name="url" value="${druid.url}"/> <property name="username" value="${druid.username}"/> <property name="password" value="${druid.password}"/> </bean> <!-- 3.配置SqlSessionFactory对象--> <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory"> <!-- 注入数据库连接池--> <property name="dataSource" ref="dataSource"/> <!-- 配置mybatis全局配置文件:mybatis-config.xml--> <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接口包--> <property name="basePackage" value="pers.tianyu.dao"/> </bean> </beans>
<?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 https://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相关bean--> <context:component-scan base-package="pers.tianyu.service"/> <!-- 2.BookServiceImpl注入容器--> <bean class="pers.tianyu.service.BookServiceImpl" id="bookService"> <property name="bookMapper" ref="bookMapper"/> </bean> <!-- 3.事务管理器--> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <!-- 注入数据库连接池--> <property name="dataSource" ref="dataSource"/> </bean> <!-- 4.aop事务支持--> <tx:advice transaction-manager="transactionManager" id="txAdvice"> <!-- 给那些方法配置事务,配置事务的传播特性--> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 5.配置事务切入--> <aop:config> <aop:pointcut id="txPointCut" expression="execution(* pers.tianyu.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> </beans>
<?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"> <!--注册DispatcherServlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 关联一个spring的配置文件 这里加载的是总spring配置文件,spring-dao.xml、spring-service.xml、springmvc-servlet.xml都被引入这个配置文件 --> <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> <!--SpringMVC乱码过滤器--> <filter> <filter-name>encoding</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置springMVC获取请求方式过滤器,配合RESTful风格使用 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Session过期时间--> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app>
<?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 https://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.支持mvc注解驱动--> <mvc:annotation-driven/> <!-- 2.让SpringMVC不处理静态资源(静态资源默认servlet配置)--> <mvc:default-servlet-handler/> <!-- 3.自动扫描包,让指定包下的注解生效,由IOC容器统一管理--> <context:component-scan base-package="pers.tianyu.controller"/> <!-- 4.视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀:自己的页面放哪里,地址就写哪里,不要照抄--> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 后缀--> <property name="suffix" value=".jsp"/> </bean> </beans>
<?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">
<!--引入配置文件-->
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:springmvc-servlet.xml"/>
</beans>
项目结构
package pers.tianyu.controller; 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 pers.tianyu.pojo.Books; import pers.tianyu.service.BookService; import java.util.List; @Controller @RequestMapping("/book") public class BookController { private BookService bookService; @Autowired @Qualifier(value = "bookService") public void setBookService(BookService bookService) { this.bookService = bookService; } }
//查询全部书籍信息,并返回到一个书记展示页面
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE 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: 4px; } </style> </head> <body> <h3> <a href="${pageContext.request.contextPath}/book/allBook"> 点击进入列表 </a> </h3> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>书籍列表</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 引入 Bootstrap --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <%--row clearfix表示不受其他样式控制,清除浮动--%> <div class="container"> <div class="row clearfix"> <div class="clo-md-12 column"> <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 class="col-md-4 column"> <%--查询书籍--%> <span style="color: red";font-weight:bold> ${msg} </span> <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post"> <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/${book.bookID}">修改</a><br> <a href="${pageContext.request.contextPath}/book/del/${book.bookID}">删除</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> </body> </html>
//跳转添加页面
@RequestMapping("/toAddBook")
public String toAddPaper(){
return "addBook";
}
//添加书籍信息
@RequestMapping("/addBook")
public String addPage(Books books){
bookService.addBook(books);
return "redirect:/book/allBook";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>新增书籍</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 引入 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> <form action="${pageContext.request.contextPath}/book/addBook" method="post"> <div class="form-group"> <label for="bkname">书籍名称:</label> <input type="text" name="bookName" id="bkname" required /><br><br><br> </div> <div class="form-group"> <label for="bkcounts">书记数量:</label> <input type="text" name="bookCounts" id="bkcounts" required /><br><br><br> </div> <div class="form-group"> <label for="bkdetail">书记详情:</label> <input type="text" name="detail" id="bkdetail" required /><br><br><br> </div> <input type="submit" value="添加"> </form> </div> </body> </html>
//删除书籍 RestFull风格
@RequestMapping("/del/{bookID}")
private String deleteBook(@PathVariable("bookID") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
//修改前信息回显 RestFull风格
@RequestMapping("/toUpdateBook/{bookID}")
public String toUpdateBook(Model model,@PathVariable("bookID") int id){
Books books = bookService.queryBookById(id);
model.addAttribute("book",books);
return "updateBook";
}
//修改书籍信息
@RequestMapping("/updateBook")
public String updateBook(Model model,Books books){
bookService.updateBook(books);
return "redirect:/book/allBook";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>修改信息</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 引入 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> <form action="${pageContext.request.contextPath}/book/updateBook" method="post"> <input type="hidden" name="bookID" value="${book.getBookID()}"/> <div class="form-group"> <label for="bkname">书籍名称:</label> <input type="text" name="bookName" id="bkname" value="${book.getBookName()}" required /><br><br><br> </div> <div class="form-group"> <label for="bkcounts">书记数量:</label> <input type="text" name="bookCounts" id="bkcounts" value="${book.getBookCounts()}" required /><br><br><br> </div> <div class="form-group"> <label for="bkdetail">书记详情:</label> <input type="text" name="detail" id="bkdetail" value="${book.getDetail()}" required /><br><br><br> </div> <input type="submit" value="保存"/> </form> </div> </body> </html>
// 查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
List<Books> list = bookService.queryBookByName(queryBookName);
if(list.isEmpty()){
model.addAttribute("msg","未查到");
}else {
model.addAttribute("list",list);
}
return "allBook";
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。