SSM整合
环境准备
- 创建数据库表
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,'从进门到进牢');
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OnFuJwwd-1692178974152)(C:\Users\Dreamy\AppData\Roaming\Typora\typora-user-images\image-20230811190725076.png)]
- 基本环境搭建
(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>org.example</groupId>
<artifactId>ssmBuild</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</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 - JSP -->
<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>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<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.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--简化实体类代码的开发-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
</dependency>
</dependencies>
<!--Maven资源过滤设置-->
<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>
</project>
(2) 建立基本结构和配置框架!
-
com.ljj.pojo
-
com.ljj.dao
-
com.ljj.service
-
com.ljj.controller
-
mybatis-config.xml (mybatis核心配置)
<?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>
-
applicationContext.xml (spring核心配置)
<?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>
Mybatis层编写
- database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
- 编写数据库的实体类 com/ljj/pojo/Books.java
使用lombok插件!
package com.ljj.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/*
* @Data get set tostring方法定义
* @NoArgsConstructor 无参构造函数
* @AllArgsConstructor 有参构造函数
* */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
private long bookID;
private String bookName;
private long bookCounts;
private String detail;
}
- 编写mybatis 配置文件
<?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>
<!--给pojo类取别名-->
<typeAliases>
<package name="com.ljj.pojo"/>
</typeAliases>
<!--加载sql的映射文件-->
<mappers>
<mapper resource="com/ljj/dao/BaoBooks.xml"/>
</mappers>
</configuration>
- 编写dao层(安装了一个MyBatisx插件,能自动跳转到BaoBooks.xml文件)
package com.ljj.dao;
import com.ljj.pojo.Books;
import java.util.List;
/**
* Created with Intellij IDEA
*
* @Auther:ljj
* @Date: 2023/08/11/19:25
* @Description:BooksDao接口,实现增删改查
*/
public interface BooksMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查看一本书详情
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBooks();
}
- 编写sql配置文件
<?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.ljj.dao.BooksMapper">
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books(bookID, bookName, bookCounts, detail) VALUES (#{bookID},#{bookName},#{bookCounts},#{detail});
</insert>
<update id="updateBook">
update ssmbuild.books
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID};
</update>
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books where bookID = #{bookID};
</delete>
<select id="queryBookById" resultType="Books">
select * from ssmbuild.books where bookID=#{bookID}
</select>
<select id="queryAllBooks" resultType="Books">
select * from ssmbuild.books
</select>
</mapper>
- 编写service层接口
package com.ljj.service;
import com.ljj.pojo.Books;
import java.util.List;
/**
* Created with Intellij IDEA
*
* @Auther:ljj
* @Date: 2023/08/11/21:31
* @Description:业务层调用dao层
*/
public interface BooksService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查看一本书详情
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBooks();
}
- 编写service层接口实现类
package com.ljj.service;
import com.ljj.dao.BooksMapper;
import com.ljj.pojo.Books;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created with Intellij IDEA
*
* @Auther:ljj
* @Date: 2023/08/11/21:32
* @Description:BooksService实现类
*/
@Service
public class BooksServiceImpl implements BooksService{
private BooksMapper booksMapper;
public BooksServiceImpl(BooksMapper booksMapper) {
this.booksMapper= booksMapper;
}
@Override
public int addBook(Books books) {
return booksMapper.addBook(books);
}
@Override
public int deleteBookById(int id) {
return booksMapper.deleteBookById(id);
}
@Override
public int updateBook(Books books) {
return booksMapper.updateBook(books);
}
@Override
public Books queryBookById(int id) {
return booksMapper.queryBookById(id);
}
@Override
public List<Books> queryAllBooks() {
return booksMapper.queryAllBooks();
}
}
Spring层编写
- 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
http://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.数据库连接池 -->
<!--数据库连接池
dbcp 半自动化操作 不能自动连接
c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
-->
<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"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.ljj.dao"/>
</bean>
</beans>
其中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=1234
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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描service相关的bean -->
<context:component-scan base-package="com.ljj.service" />
<!--BookServiceImpl注入到IOC容器中-->
<bean id="BooksServiceImpl" class="com.ljj.service.BooksServiceImpl">
<property name="booksMapper" ref="booksMapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
</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 https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.注解驱动-->
<mvc:annotation-driven/>
<!--2.静态资源过滤-->
<mvc:default-servlet-handler/>
<!--4.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--3.扫描包:controller-->
<context:component-scan base-package="com.ljj.controller"/>
</beans>
tips: jsp后要加上’/',否则controller中的方法类返回jsp页面的字符串需要加上"/"
- 整合Spring文件,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">
<import resource="spring-dao.xml"></import>
<import resource="spring-service.xml"></import>
<import resource="spring-mvc.xml"></import>
</beans>
Controller和视图层编写
1.查询所有书籍列表
Controller层
@Controller
@RequestMapping("/book")
public class BooksController {
@Autowired
@Qualifier("BooksServiceImpl")
private BooksService booksService;
//查询所有书籍列表
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list = booksService.queryAllBooks();
System.out.println(list);
model.addAttribute("list",list);
return "allBook";
}
}
}
编写首页 index.jsp
<%--
Created by IntelliJ IDEA.
User: Dreamy
Date: 2023/8/11
Time: 18:30
To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
<title>首页</title>
<style type="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>
<a href="${pageContext.request.contextPath}/book/allBook">点击进入列表页</a>
</h3>
</body>
</html>
编写allbook.jsp页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<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>
<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">
<form action="${pageContext.request.contextPath}/book/queryBookByName" method="post" style="float: right">
<input type="text" name="queryBookName" placeholder="请输入要查询的书籍名称">
<input type="submit" value="查询" class="btn btn-primary" style="height: 30px">
<span style="color: red;font-weight: bold" >${error}</span>
</form>
</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>
<c:forEach var="book" items="${requestScope.get('list')}">
<tr>
<td>${book.getBookID()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> |
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.getBookID()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
- 新增书籍
Controller层
```bash
```bash
//跳转到添加书籍页面
@RequestMapping("/toAddBook")
public String toAddPaper(){
return "addBook";
}
//添加书籍页面
@RequestMapping("/addBook")
public String addBook(Books books){
booksService.addBook(books);
//重定向到allBook请求
return "redirect:/book/allBook";
}
编写addBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<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">
<%-- required 表格不能为空--%>
书籍名称:<input type="text" name="bookName" required><br><br><br>
书籍数量:<input type="text" name="bookCounts" required><br><br><br>
书籍详情:<input type="text" name="detail" required><br><br><br>
<input type="submit" value="添加">
</form>
</div>
- 修改书籍
//跳转到修改页面
@RequestMapping("/toUpdateBook")
public String toUpdatePaper(Model model,int id){
//从前端拿到选取的id
Books book = booksService.queryBookById(id);
//给前端查到的书籍
model.addAttribute("Qbook",book);
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Books books){
booksService.updateBook(books);
return "redirect:/book/allBook";
}
编写updateBook.jsp
<%–
Created by IntelliJ IDEA.
User: Dreamy
Date: 2023/8/15
Time: 22:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>更新书籍</title>
</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">
<%-- 出现的问题:直接使用修改函数时
booksService.updateBook(books);
return "redirect:/book/allBook";
前端没有设置ID与选中的ID一致,导致默认Id=0,所以根据sql语句
update ssmbuild.books
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID}
查找不到id为0的数据,故无法修改成功
解决方法,设置一个隐藏域,确定好id的值
--%>
<input type="hidden" name="bookID" value="${Qbook.bookID}">
<%-- required 表格不能为空--%>
书籍名称:<input type="text" name="bookName" value="${Qbook.bookName}" required><br><br><br>
书籍数量:<input type="text" name="bookCounts" value="${Qbook.bookCounts}" required><br><br><br>
书籍详情:<input type="text" name="detail" value="${Qbook.detail}" required><br><br><br>
<input type="submit" value="修改">
</form>
</div>
- 删除书籍
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id){
booksService.deleteBookById(id);
return "redirect:/book/allBook";
}
- 根据书籍名字查询书籍 可模糊查询
@RequestMapping("/queryBookByName")
public String queryBookByName(String queryBookName,Model model){
List<Books> list = booksService.queryBooksByName(queryBookName);
System.out.println(list.isEmpty());
if(list.isEmpty()){
model.addAttribute("error","未查到!请重新输入");
return "redirect:/book/allBook";
}
model.addAttribute("list", list);
return "allBook";
}
BooksController.java
package com.ljj.controller;
import com.ljj.pojo.Books;
import com.ljj.service.BooksService;
import org.junit.runners.Parameterized;
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;
/**
* Created with Intellij IDEA
*
* @Auther:ljj
* @Date: 2023/08/11/21:37
* @Description:Controller层,调用service层
*/
@Controller
@RequestMapping("/book")
public class BooksController {
@Autowired
@Qualifier("BooksServiceImpl")
private BooksService booksService;
//查询所有书籍列表
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list = booksService.queryAllBooks();
System.out.println(list);
model.addAttribute("list",list);
return "allBook";
}
//跳转到添加书籍页面
@RequestMapping("/toAddBook")
public String toAddPaper(){
return "addBook";
}
//添加书籍页面
@RequestMapping("/addBook")
public String addBook(Books books){
booksService.addBook(books);
//重定向到allBook请求
return "redirect:/book/allBook";
}
//跳转到修改页面
@RequestMapping("/toUpdateBook")
public String toUpdatePaper(Model model,int id){
//从前端拿到选取的id
Books book = booksService.queryBookById(id);
//给前端查到的书籍
model.addAttribute("Qbook",book);
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Books books){
booksService.updateBook(books);
return "redirect:/book/allBook";
}
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id){
booksService.deleteBookById(id);
return "redirect:/book/allBook";
}
@RequestMapping("/queryBookByName")
public String queryBookByName(String queryBookName,Model model){
List<Books> list = booksService.queryBooksByName(queryBookName);
System.out.println(list.isEmpty());
if(list.isEmpty()){
model.addAttribute("error","未查到!请重新输入");
return "redirect:/book/allBook";
}
model.addAttribute("list", list);
return "allBook";
}
}