[SpringMVC 04] SSM图书管理系统整合
SSM_整合
1. 背景搭建
1.1 数据库:
books(bookID, bookName, bookCounts, detail), bookID是自增的
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
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,'从进门到进牢');
1.2.项目配置
新建和Mybatis层的配置,包括pojo、dao、service
1.2.1配置pom.xml
新建maven普通项目, 配置pom.xml
文件(导入依赖、静态资源导出问题配置)
<!--依赖: junit,
数据库驱动,连接池,
servlet,jsp,jstl
mybatis, mybatis-spring, spring-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</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.6</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.2.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.13</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>
1.2.2 测试连接数据库
更换数据库: 在schema中
1.2.3 构建包结构
java:com.roy.pojo, dao, service, controller
resources: 数据库连接信息:database.properties
连接数据库: mybatis-config.xml
, spring托管: applicationContext.xml
,
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=123456
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>
<!--只做typealias和部分映射-->
<typeAliases>
<package name="com.roy.pojo"/>
</typeAliases>
</configuration>
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>
1.2.4 Java构建
Pojo层:
pojo.Books
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private Integer bookID;
private String bookName;
private Integer bookCounts;
private String detail;
}
dao层:
dao.BooksMapper
public interface BookMapper {
//add, delete, update, query
int addBook(Books books);
int deleteBookById(@Param("bookId")int id);//可以取别名
int updateBook(Books books);
Books queryBookById(@Param("bookId")int id);//写param后,在xml中不需要写paramType, alt+/可以自动补充
List<Books> queryAllBook();
}
dao层接口的实现xml:
(不出现提示信息的方法:在settings-->Languages &Frameworks-->SQL Dialects中配置数据库类型,将项目添加进来,配置完成后Apply-OK)
dao.BooksMapper.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.roy.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books (bookName, bookCounts, detail)
values (#{bookName},#{bookCounts},#{detail})
</insert>
<delete id="deleteBookById" parameterType="int">
delete from 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" parameterType="int" resultType="Books">
select * from books where bookID=#{bookID}
</select>
<select id="queryAllBook" resultType="Books">
select * from books
</select>
</mapper>
写完去mybatis-config.xml注册
<mappers>
<mapper class="com.roy.dao.BookMapper"/>
</mappers>
Service层
需要调用dao层写好的Mapper, 使用组合思想,并写set方法,方便spring注入
BookService接口
public interface BookService {
int addBook(Books books);
int deleteBookById(int id);
int updateBook(Books books);
Books queryBookById(int id);
List<Books> queryAllBook();
}
BookServiceImpl
public class BookServiceImpl implements BookService{
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {//重点,组合思想
this.bookMapper = bookMapper;
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
1.3. Spring整合
1.3.1 把mybatis整合到Spring中
(同时把dao层整合到spring中,配置第四点)
写spring-dao.xml, 其中:关联数据库、写连接池、获得sqlSessionFactory
<?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">
<!-- 11取数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 22配置连接池-->
<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"/>
<property name="initialPoolSize" value="10"/>
</bean>
<!-- 33sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 44添加自动扫描BookMapper.xml文件注入到Spring中托管
(以前需要在dao层重新写.java实现类并继承SqlSessionFactory或DaoSupport-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 此处为引用上面的sqlSessionFactory, 但不是ref,是string类型,所以用value-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 添加要扫描的包-->
<property name="basePackage" value="com.roy.dao"/>
</bean>
</beans>
(之前的dao层的Mapper.xml不能被托管到sping中,需要手动写一个Mapper.java的实现类,现在用动态扫描)
1.3.2 整合service层
新建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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--11扫描service包-->
<context:component-scan base-package="com.roy.service"/>
<!--22将所有业务类,注入spring(配置或注解)
注解: 添加@Service, 要注入的属性上写@AutoWired(属性必须有set方法,否则不能注入-->
<bean id="BookServiceImpl" class="com.roy.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--33 声明式事务配置(所有的增删改查都需要式事务的)-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--44 aop织入其他切面,需要导入包-->
</beans>
1.3.3 整合SpringMVC
1.给项目添加web支持, 然后修改web.xml文件
2.web.xml:(三件事情: DispatcherServlet, 乱码过滤, session过期时间)
<?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>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
<!-- 注意添加的是总的配置,applicationContext,不是mvc的配置-->
</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>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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
写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
https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--注解驱动、静态资源过滤、扫描包、配置视图解析-->
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.roy.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
在applicationContext.xml中添加:
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
WEB-INF下添加jsp文件夹
整合完成,开始写Controller和jsp文件夹下的前端展示
1.4 Controller和jsp前端
1.4.1 简单测试
写controller.BookController.java做测试:
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired//写这个注解,可以不用写set方法就可以自动注入(详见之前的笔记)
@Qualifier(value = "BookServiceImpl")
private BookServiceImpl bookServiceImpl;
@RequestMapping("/allbook")
public String list(Model model){
List<Books> books = bookServiceImpl.queryAllBook();
model.addAttribute("books", books);
return "allBook";
}
}
index.jsp:
<a href="${pageContext.request.contextPath}/book/allbook">跳转到全部书籍页面</a>
jsp/allBook.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
过来了过来了
</body>
</html>
1.4.2 美化index.jsp
<%@ 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;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allbook">跳转到全部书籍页面</a>
<%--跳转到 /book/allbook--%>
</h3>
</body>
</html>
1.4.3 allBook.jsp
需要加入依赖:
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<%@ 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>
<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 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>
<tbody>
<%-- 从list中遍历--%>
<c:forEach var="book" items="${books}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdate?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>
1.4.4 addBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>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 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" class="form-control" id="bkname" 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="detail" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="添加">
</div>
</form>
</div>
</body>
</html>
1.4.5 updateBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>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 column">
<div class="page-header">
<h1>
<small>修改书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<%-- 缺少id号, 提交的update无法update(修改失败)--%>
<input type="hidden" name="bookID" value="${Qbooks.bookID}">
<div class="form-group">
<label for="bkname">书籍名称:</label>
<input type="text" name="bookName" class="form-control" id="bkname" value="${Qbooks.bookName}" required>
</div>
<div class="form-group">
<label>书籍数量:</label>
<input type="text" name="bookCounts" class="form-control" value="${Qbooks.bookCounts}" required>
</div>
<div class="form-group">
<label>书籍描述:</label>
<input type="text" name="detail" class="form-control" value="${Qbooks.detail}" required>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="修改">
</div>
</form>
</div>
</body>
</html>
1.4.6 BookController.java
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier(value = "BookServiceImpl")
private BookServiceImpl bookServiceImpl;
//全部书籍展示
@RequestMapping("/allbook")
public String list(Model model){
List<Books> books = bookServiceImpl.queryAllBook();
model.addAttribute("books", books);
return "allBook";
}
//添加书籍跳转
@RequestMapping("/toAddBook")
public String toAddPaper(){
return "addBook";
}
//添加书籍提交
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("addBook->"+books);
bookServiceImpl.addBook(books);
return "redirect:/book/allbook";
}
//更新书籍跳转
@RequestMapping("/toUpdate")
public String toUpdatePaper(int id, Model model){
Books books = bookServiceImpl.queryBookById(id);
model.addAttribute("Qbooks", books);
return "updateBook";
}
//更新书籍提交
@RequestMapping("/updateBook")
public String updateBook(Books books){
bookServiceImpl.updateBook(books);
return "redirect:/book/allbook";
}
//删除书籍,Restful风格
@RequestMapping("/deleteBook/{bookId}")
public String deleteBook(@PathVariable("bookId") int id){
bookServiceImpl.deleteBookById(id);
return "redirect:/book/allbook";
}
}
1.5 SSM项目配置思路总结:
1.5.1 项目建立
-
数据库建立
-
新建项目,配置
pom.xml
:maven依赖, 资源过滤关闭 -
构建基础包结构: pojo, dao, service, controller
-
resources添加: database.properties(连接数据库), mybatis-config.xml(空), applicationContext.xml(空)
-
写完dao的Mapper.xml后,去mybatis-config.xml映射
-
写service层, 组合的方式调用dao层
1.5.2 项目整合:
- mybatis(整合到spring中):
spring-dao.xml
:配置dataSource, 连接池, sqlSessionFactory, 使用MapperScanner把Mapper.xml类扫描到Spring中,不用新建.java文件 - service层整合:
spring-service.xml
: 扫描service的包, 把dao注入到service层中, 声明事务,和AOP织入 - MVC层整合1:
web.xml
: 配置DispatcherService, 配置乱码过滤, 配置session过期时间 - MVC层整合2:
spring-mvc.xml
: 配置注解驱动,静态资源过滤, 扫描包,视图解析器 - 在
application.xml
中整合spring*.xml文件进去,并将application配置到web.xml的DispatcherService中。
(controller层被spring-mvc扫描到而被spring托管)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端