--- title: SSM整合 author: TianZD top: true cover: true toc: true mathjax: false summary: SSM整合学习笔记,粗略学了一下,没有参考价值 tags: - SSM - Java - 学习笔记 categories: - java reprintPolicy: cc_by abbrlink: 254393f0 date: 2022-04-29 11:10:43 coverImg: img: password: --- [toc] # 1、SpringMVC-SSM整合 ## 1.1、环境 > 环境 * IDE:IDEA 2021 1.1 * 项目管理:Maven ,apache-maven-3.8.1 * JAVA:JDK 16.01 * Web服务器:apache-tomcat-9.0.50 * 数据库:MySQL 8.0.26 * 数据库管理工具:Navicat premium 15 > 数据库环境 ```sql 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,'从进门到坐牢'); ``` > 基本环境搭建 * 新建maven工程 * 配置pom.xml * 导入依赖 * 配置静态资源 ```xml junit junit 4.12 test mysql mysql-connector-java 8.0.25 com.mchange c3p0 0.9.5.2 javax.servlet servlet-api 2.5 javax.servlet.jsp jsp-api 2.2 javax.servlet jstl 1.2 org.mybatis mybatis 3.5.7 org.mybatis mybatis-spring 2.0.2 org.springframework spring-webmvc 5.3.9 org.springframework spring-jdbc 5.3.9 log4j log4j 1.2.17 src/main/java **/*.properties **/*.xml false src/main/resources **/*.properties **/*.xml false ``` > IDEA连接数据库 ![image-20210815222657080](https://gitee.com/tianzhendong/img/raw/master//images/image-20210815222657080.png) > 建立项目包结构 * dao * pojo * controller * service > 建立核心配置文件 * spring:applicationContext.xml ```xml ``` * mybatis:mybatis-config.xml和database.properties mybatis-config.xml ```xml ``` database.properties ```properties jdbc.driver=com.mysql.cj.jdbc.Driver #如果使用mysql8.0以上,需要增加时区设置 jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai jdbc.username=root jdbc.password=123456 ``` * log4j.properties ```properties #将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码 log4j.rootLogger=DEBUG,console,file #控制台输出的相关设置 log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n #文件输出的相关设置 log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/tian.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n #日志输出级别 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG ``` ## 1.2、Mybatis层 主要是dao层和service层,底层相关,MVC的Model层,数据和业务 > pojo层 ```java public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; //get、set、toString、construct } ``` > dao层 * 接口 ```java public interface BookMapper { //add int addBook(Books books); //delete int deleteBook(@Param("bookID") int id); //update int updateBook(Books books); //select one Books selectBookById(@Param("bookID") int id); //select all List selectBookAll(); } ``` * Mapper.xml ```xml insert into ssmbuild.books (bookName, bookCounts, detail) values (#{bookName},#{bookCounts},#{detail}); delete from ssmbuild.books where bookID = #{bookID}; update ssmbuild.books set bookName = #{bookName}, bookCounts = #{bookCounts}, detail = #{detail} where bookID = #{bookID}; ``` * 绑定mapper.xml到mybatis-config.xml配置文件中 ```xml ``` > service层 * BookService接口 ```java public interface BookService { //add int addBook(Books books); //delete int deleteBook(int id); //update int updateBook(Books books); //select one Books selectBookById(int id); //select all List selectBookAll(); } ``` * 接口实现类 ```java public class BookServiceImpl implements BookService{ //业务层调用dao层:组合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 selectBookById(int id) { return bookMapper.selectBookById(id); } @Override public List selectBookAll() { return bookMapper.selectBookAll(); } } ``` ## 1.3、Spring层 > dao层 spring-dao.xml * 关联数据库配置文件 * 连接池 * sqlSessionFactory * sqlSession ```xml ``` > service spring-service.xml * 扫描service下的包 * 将业务类注入到spring,可以通过配置或者注解实现 * 声明式事务配置 * AOP事务支持 ```xml ``` ## 1.4、SpringMVC层 > 增加web支持 > web.xml * dispatchservlet * 乱码过滤 ```xml dispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springmvc-servlet.xml 1 dispatcherServlet / encodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding utf-8 encodingFilter /* 15 ``` > springmvc-servlet.xml ```xml ``` ## 1.5、配置文件整合 applicationContext.xml ```xml ``` # 2、实际业务实现 ## 2.1、查询书籍功能 ### 查询 将controller和web交互 > controller *BookController.class* ```java @Controller @RequestMapping("/book") public class BookController { //controller层调用service层 @Autowired @Qualifier("BookServiceImpl") private BookService bookService; //查询全部书籍,并返回书籍展示页面 public String selectAllBook(Model model) { List books = bookService.selectBookAll(); model.addAttribute("list", books); return "allBook"; } } ``` > jsp * allBook.jsp * index.jsp,设置由首页跳转 ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> 书籍展示

书籍展示

``` ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> $Title$ $END$

进入书籍展示页面

``` ### 错误 ```bash org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tian.service.BookService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier("BookServiceImpl")} ``` bean不存在 > 解决 web.xml中需要引入applicationContxt.xml而不是springmvc-config.xml ### 美化 > 首页 ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> 首页

进入书籍展示页面

``` ![](https://gitee.com/tianzhendong/img/raw/master//images/image-20210816033535794.png) > 查询页 ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> 书籍展示
书籍列表
书籍ID 书籍名称 书籍数量 书籍描述
${books.bookID} ${books.bookName} ${books.bookCounts} ${books.detail}
``` ![image-20210816201951940](https://gitee.com/tianzhendong/img/raw/master//images/image-20210816201951940.png) ## 2.2、添加书籍功能 > 待跳转页面 addBook.jsp ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> 添加书籍页面
书籍名称:
书籍数量:
书籍描述:
``` ![image-20210816205546620](https://gitee.com/tianzhendong/img/raw/master//images/image-20210816205546620.png) > controller ```java // 跳转到添加书籍界面 @RequestMapping("/toAddBook") public String toAddBook() { return "addBook"; } //添加书籍请求 @RequestMapping("/addBook") public String addBook(Books book) { bookService.addBook(book); return "redirect:/book/allBook"; } ``` > 跳转按钮 allBook.jsp ```xml 添加书籍 ``` ![image-20210816210610577](https://gitee.com/tianzhendong/img/raw/master//images/image-20210816210610577.png) ## 2.3、修改、删除书籍 > 按钮 allBook.jsp ```jsp  修改 | 删除  ``` ![image-20210816221451118](https://gitee.com/tianzhendong/img/raw/master//images/image-20210816221451118.png) > controller ```java //跳转到修改请求页面 @RequestMapping("/toUpdateBook/{bookId}") public String toUpdateBook(@PathVariable("bookId") int id, Model model) { Books books = bookService.selectBookById(id); model.addAttribute("bookSelected", books); return "updateBook"; } //修改书籍 @RequestMapping("/updateBook") public String updateBook(Books 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"; } } ``` > 待跳转页面 updateBook.jsp ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> 修改书籍
<%--隐藏于传递不需要用户修改的bookID--%>
书籍名称:
书籍数量:
书籍描述:
``` ![image-20210816223906448](https://gitee.com/tianzhendong/img/raw/master//images/image-20210816223906448.png)