前言
本章将通过一个图书管理案例,将之前所学到的MyBatis,Spring,SpringMVC的知识串起来,整合SSM框架。
使用的技术:
- MySQL(8.0.28)
- MyBatis (3.5.7)
- Spring
- SpringMVC
- 页面展示部分用了一点儿BootStrap
- Lombok
使用IDEA进行开发。
源码托管到了Gitee上:https://gitee.com/blossoming819/ssmbuild.git
1、搭建数据库
CREATEDATABASE`ssmbuild`;USE`ssmbuild`;DROPTABLEIFEXISTS`books`;CREATETABLE`books`(`bookID`INT(10)NOTNULLAUTO_INCREMENTCOMMENT'书id',`bookName`VARCHAR(100)NOTNULLCOMMENT'书名',`bookCounts`INT(11)NOTNULLCOMMENT'数量',`detail`VARCHAR(200)NOTNULLCOMMENT'描述',KEY`bookID`(`bookID`))ENGINE=INNODBDEFAULTCHARSET=utf8
INSERTINTO`books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES(1,'Java',1,'从入门到放弃'),(2,'MySQL',10,'从删库到跑路'),(3,'Linux',5,'从进门到进牢');
2、导入依赖
使用Maven构建项目,导入依赖更方便,只需在Maven项目中的pom.xml中添加配置即可,依赖可以在Maven仓库中获取到。
<dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency><!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.5</version></dependency><!--servlet jsp--><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>2.1</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.7</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.18</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.18</version></dependency></dependencies>
为了避免资源或者配置找不到的问题,我们在Maven的配置里添加资源过滤,依然是在pom.xml中配置。
<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>
3、构建项目结构
首先需要新建一个图书类
Books
packagecom.princehan.pojo;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;/**
* @Description
* @Author:PrinceHan
* @CreateTime:2022/4/19 12:51
*/@Data@NoArgsConstructor@AllArgsConstructorpublicclassBooks{privateint bookID;privateString bookName;privateint bookCounts;privateString detail;}
4、配置SSM框架
整合SSM要实现dao,service,controller三个方面
4.1、dao层
配置MyBatis
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><!--核心配置文件--><configuration><settings><settingname="logImpl"value="STDOUT_LOGGING"/><settingname="cacheEnabled"value="true"/></settings><typeAliases><packagename="com.princehan.pojo"/></typeAliases><mappers><mapperclass="com.princehan.dao.BookMapper"/></mappers></configuration>
编写连接数据库的配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=0925
由于本案例使用的数据源为c3p0,所以前缀要加上
jdbc
,在测试过程中,发现不加会报错
配置dao层的spring,连接MyBatis
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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"><!--关联数据库配置文件--><context:property-placeholderlocation="classpath:database.properties"/><!--连接池--><!--使用c3p0的数据源--><beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"><propertyname="driverClass"value="${jdbc.driver}"/><propertyname="jdbcUrl"value="${jdbc.url}"/><propertyname="user"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></bean><!--sqlSessionfactory--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><propertyname="dataSource"ref="dataSource"/><!--绑定MyBatis--><propertyname="configLocation"value="classpath:mybatis-config.xml"/></bean><!--配置扫描dao--><beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"><propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/><propertyname="basePackage"value="com.princehan.dao"/></bean></beans>
编写
BookMapper
接口
packagecom.princehan.dao;importcom.princehan.pojo.Books;importorg.apache.ibatis.annotations.Param;importjava.util.List;/**
* @Description
* @Author:PrinceHan
* @CreateTime:2022/4/19 12:57
*/publicinterfaceBookMapper{intaddBook(Books book);intdeleteBookById(@Param("bookID")int id);intupdateBook(Books book);BooksqueryBookById(@Param("bookID")int id);List<Books>queryAllBook();List<Books>queryBookByName(@Param("bookName")String name);}
编写
BookMapper
接口的映射
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.princehan.dao.BookMapper"><insertid="addBook"parameterType="Books">
insert into books(bookName, bookCounts, detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert><deleteid="deleteBookById">
delete
from books
where bookID = #{bookID}
</delete><updateid="updateBook"parameterType="Books">
update books
set bookName = #{bookName},
bookCounts = #{bookCounts},
detail = #{detail}
where bookID = #{bookID}
</update><selectid="queryBookById"resultType="Books">
select *
from books
where bookID = #{bookID}
</select><selectid="queryAllBook"resultType="Books">
select *
from books
</select><selectid="queryBookByName"resultType="Books">
select *
from books
where bookName = #{bookName};
</select></mapper>
4.2、service层
编写
BookService
接口
packagecom.princehan.service;importcom.princehan.pojo.Books;importorg.apache.ibatis.annotations.Param;importjava.util.List;/**
* @Description
* @Author:PrinceHan
* @CreateTime:2022/4/19 13:17
*/publicinterfaceBookService{intaddBook(Books book);intdeleteBookById(@Param("bookID")int id);intupdateBook(Books book);BooksqueryBookById(@Param("bookID")int id);List<Books>queryAllBook();List<Books>queryBookByName(@Param("bookName")String name);}
编写实现类
packagecom.princehan.service;importcom.princehan.dao.BookMapper;importcom.princehan.pojo.Books;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjava.util.List;/**
* @Description
* @Author:PrinceHan
* @CreateTime:2022/4/19 13:17
*/@Service//service注解表示这是一个bean,放入到了IOC容器publicclassBookServiceImplimplementsBookService{//业务层调用dao层privateBookMapper bookMapper;@AutowiredpublicvoidsetBookMapper(BookMapper bookMapper){this.bookMapper = bookMapper;}@OverridepublicintaddBook(Books book){return bookMapper.addBook(book);}@OverridepublicintdeleteBookById(int id){return bookMapper.deleteBookById(id);}@OverridepublicintupdateBook(Books book){return bookMapper.updateBook(book);}@OverridepublicBooksqueryBookById(int id){return bookMapper.queryBookById(id);}@OverridepublicList<Books>queryAllBook(){return bookMapper.queryAllBook();}@OverridepublicList<Books>queryBookByName(String name){return bookMapper.queryBookByName(name);}}
配置spring的service层
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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"><context:component-scanbase-package="com.princehan.service"/><!--BookServiceImpl注入到IOC容器中,使用注解可以不配置这个--><!-- <bean id="BookServiceImpl" class="com.princehan.service.BookServiceImpl">--><!-- <property name="bookMapper" ref="bookMapper"/>--><!-- </bean>--><beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><propertyname="dataSource"ref="dataSource"/></bean></beans>
4.3、controller层
编写
BookController
接口
packagecom.princehan.controller;importcom.princehan.pojo.Books;importcom.princehan.service.BookService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importjava.util.List;/**
* @Description
* @Author:PrinceHan
* @CreateTime:2022/4/19 14:11
*/@Controller@RequestMapping("/book")publicclassBookController{@Autowired//自动装配// @Qualifier("BookServiceImpl")privateBookService bookService;}
配置spring的controller层
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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
http://www.springframework.org/schema/mvc/spring-mvc.xsd"><mvc:annotation-driven/><mvc:default-servlet-handler/><context:component-scanbase-package="com.princehan.controller"/><beanid="internalResourceViewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><propertyname="prefix"value="/WEB-INF/jsp/"/><propertyname="suffix"value=".jsp"/></bean></beans>
4.4、整合dao,service,controller层
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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
http://www.springframework.org/schema/mvc/spring-mvc.xsd"><importresource="classpath:spring-dao.xml"/><importresource="classpath:spring-service.xml"/><importresource="classpath:springmvc-servlet.xml"/></beans>
5、功能实现
5.1、配置web.xml
<?xml version="1.0" encoding="UTF-8"?><web-appxmlns="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><param-value>classpath:applicationContext.xml</param-value></init-param><!--启动级别-1--><load-on-startup>1</load-on-startup></servlet><!--/ 匹配所有的请求;(不包括.jsp)--><!--/* 匹配所有的请求;(包括.jsp)--><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>
5.2、编写主页index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html><head><title>首页</title><styletype="text/css">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><ahref="${pageContext.request.contextPath}/book/allbook">书籍界面</a></h3></body></html>
5.3、展示所有书籍allBook.jsp
编写展示页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html><head><title>数据展示部分</title><!-- 引入 Bootstrap --><linkhref="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"rel="stylesheet"></head><body><divclass="container"><divclass="row clearfix"><divclass="col-md-12 column"><divclass="page-header"><h1><small>书籍列表 —— 显示所有书籍</small></h1></div></div></div><divclass="row"><divclass="col-md-4 column"><aclass="btn btn-primary"href="${pageContext.request.contextPath}/book/toAddBook">新增</a></div><divclass="col-md-4 column"></div><divclass="col-md-4 column"><formclass="form-inline"action="${pageContext.request.contextPath}/book/queryBook"method="post"style="float: right"><spanstyle="color:red;font-weight: bold">${error}</span><inputtype="text"name="queryBookName"class="form-control"placeholder="输入查询书名"required><inputtype="submit"value="查询"class="btn btn-primary"></form></div></div><divclass="row clearfix"><divclass="col-md-12 column"><tableclass="table table-hover table-striped"><thead><tr><th>书籍编号</th><th>书籍名字</th><th>书籍数量</th><th>书籍详情</th><th>操作</th></tr></thead><tbody><c:forEachvar="book"items="${list}"><tr><td>${book.bookID}</td><td>${book.bookName}</td><td>${book.bookCounts}</td><td>${book.detail}</td><td><ahref="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.bookID}">更改</a> |
<ahref="${pageContext.request.contextPath}/book/del/${book.bookID}">删除</a></td></tr></c:forEach></tbody></table></div></div></div></body></html>
编写controller
@RequestMapping("/allbook")publicStringqueryAllBook(Model model){List<Books> books = bookService.queryAllBook();
model.addAttribute("list", books);return"allBook";}
当点击书籍界面时,发动请求,service层获取到书籍列表,通过model携带数据,跳转到allBook.jsp页面。
5.4、修改书籍
这一功能的完成可以分为两步进行:跳转到修改页面,修改书籍,因此有两个请求。
修改指定的书籍需要传递书籍的id
<ahref="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.bookID}">更改</a>
修改页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html><head><title>Title</title><linkhref="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"rel="stylesheet"></head><body><divclass="container"><divclass="row clearfix"><divclass="col-md-12 column"><divclass="page-header"><h1><small>修改书籍</small></h1></div></div></div><formaction="${pageContext.request.contextPath}/book/updateBook"method="post"><inputtype="hidden"name="bookID"value="${book.bookID}"><divclass="form-group"><labelfor="bookName">书籍名称</label><inputtype="text"id="bookName"name="bookName"value="${book.bookName}"class="form-controller"required></div><divclass="form-group"><labelfor="bookCounts">书籍数量</label><inputtype="text"id="bookCounts"name="bookCounts"value="${book.bookCounts}"class="form-controller"required></div><divclass="form-group"><labelfor="detail">书籍详情</label><inputtype="text"id="detail"name="detail"value="${book.detail}"class="form-controller"required></div><divclass="form-group"><inputtype="reset"value="重置"><inputtype="submit"value="提交"></div></form></div></body></html>
跳转到修改页面
@RequestMapping("/toUpdateBook")publicStringtoUpdateBook(Model model,int id){Books book = bookService.queryBookById(id);System.out.println(book);
model.addAttribute("book", book);return"updateBook";}
修改数据,前端的数据通过name属性,被controller获取到,这里我们获取的是一个对象。
@RequestMapping("/updateBook")publicStringupdateBook(Books book){
bookService.updateBook(book);return"redirect:/book/allbook";}
修改后重定向至展示书籍的界面。
5.5、删除书籍
根据书籍id删除书籍,请求上需要携带id,这里使用的是Restful风格,更加简洁。
<ahref="${pageContext.request.contextPath}/book/del/${book.bookID}">删除</a>
@RequestMapping("/del/{id}")publicStringdeleteBook(@PathVariableint id){
bookService.deleteBookById(id);return"redirect:/book/allbook";}
删除后重定向至书籍展示页面。
5.6、添加书籍
依然可以分成两步进行,跳转到书籍增添页面,增添书籍。
书籍增添页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html><head><title>Title</title><!-- 引入 Bootstrap --><linkhref="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"rel="stylesheet"></head><body><divclass="container"><divclass="row clearfix"><divclass="col-md-12 column"><divclass="page-header"><h1><small>新增书籍</small></h1></div></div></div><formaction="${pageContext.request.contextPath}/book/addBook"method="post"><divclass="form-group"><labelfor="bookName">书籍名称</label><inputtype="text"id="bookName"name="bookName"required></div><divclass="form-group"><labelfor="bookCounts">书籍数量</label><inputtype="text"id="bookCounts"name="bookCounts"required></div><divclass="form-group"><labelfor="detail">书籍详情</label><inputtype="text"id="detail"name="detail"required></div><divclass="form-group"><inputtype="submit"value="添加"></div></form></div></body></html>
跳转到书籍增添页面
@RequestMapping("/toAddBook")publicStringtoAddPaper(){return"addBook";}
增添书籍
@RequestMapping("/addBook")publicStringaddBook(Books book){
bookService.addBook(book);return"redirect:/book/allbook";}
5.7、查询书籍
<formclass="form-inline"action="${pageContext.request.contextPath}/book/queryBook"method="post"style="float: right"><spanstyle="color:red;font-weight: bold">${error}</span><inputtype="text"name="queryBookName"value="${queryBookName} class="form-control"placeholder="输入查询书名"required><inputtype="submit"value="查询"class="btn btn-primary"></form>
@RequestMapping("/queryBook")publicStringqueryBook(String queryBookName,Model model){List<Books> books = bookService.queryBookByName(queryBookName);if(books.size()>0){
model.addAttribute("list", books);}else{
model.addAttribute("error","查无此书");}
model.addAttribute("queryBookName", queryBookName);return"allBook";}
6、小结
到此为止,通过这个小案例完成了SSM的整合,实现了对书籍的增删改查,希望能对大家有帮助。
版权归原作者 理想- 所有, 如有侵权,请联系我们删除。