SSM简单整合(狂神版)
项目结构:
1.数据库环境
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,'从进门到进牢');
数据库的属性文件:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/smbms?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=yh789789
2.环境依赖
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">
<parent>
<artifactId>springMVC</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ssm</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!--依赖 junit 数据库 连接池 servlet jsp spring mybatis -->
<dependencies>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!--连接池 c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</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.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--spring-->
<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.2.12.RELEASE</version>
</dependency>
<!-- lomnok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</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>
</project>
3.配置文件
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>
<!-- 配置数据源交给spring完成-->
<typeAliases>
<package name="wyf.study.pojo"/>
</typeAliases>
<!-- 注册Mapper-->
<mappers>
<mapper class="wyf.study.dao.BookMapper"/>
</mappers>
</configuration>
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">
<!-- 关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 连接池
c3p0:自动化操作(自动加载配置文件,并且可以自动设置到对象中)
dbcp:半自动化操作,不能自动连接
druid
hikari
-->
<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"/>
<!--绑定Mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!--4.配置dao接口扫描包,动态的实现了dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactoryBeanName-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的dao包-->
<property name="basePackage" value="wyf.study.dao"/>
</bean>
</beans>
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"
xmlns:tx="http://www.springframework.org/schema/c"
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">
<!-- 1. 扫面service下的包-->
<context:component-scan base-package="wyf.study.services"/>
<!--2.将我们的所有业务类,注入到Spirng,可以通过配置,或者注解实现-->
<bean id="BookServiceImpl" class="wyf.study.services.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3.声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源 -->
<property name="dataSource" ref="dataSource"/>
<!--4.结合AOP实现事务切入-->
<!-- 配置事务通知-->
</bean>
</beans>
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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/c"
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
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!-- 1 注解驱动-->
<mvc:annotation-driven/>
<!-- 2 静态资源过滤-->
<mvc:default-servlet-handler/>
<!-- 3 扫描包-->
<context:component-scan base-package="wyf.study.controller"/>
<!-- 4 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
web.xml
<?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">
<!-- 1.DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--
错误出现在这里:
1.查看bean式否注入成功
2.单元测试一下
3.都没问题,问题不在底层,那就是spring出了问题
4.SpringMVC整合时候没有调用到service的bean
1.applicationContext.xml 没有注入bean
2.web.xml中绑定的配置文件有问题,当时绑定的是spring-mvc.xml
应该绑定的是applicationContext.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>
<!-- 乱码过滤-->
<filter>
<filter-name>springfilter</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>springfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Session过期时间 分钟-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
4 .建立基本结构
【wyf.study.pojo】
package wyf.study.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookid;
private String bookName;
private int bookCounts;
private String detail;
}
【wyf.study.dao】
mapper
package wyf.study.dao;
import org.apache.ibatis.annotations.Param;
import wyf.study.pojo.Books;
import java.util.List;
public interface BookMapper {
//增加
int addBook(Books books);
//删除
int delBookByID(@Param("bookid") int id);
//改
int upBook(Books books);
//根据id查
Books queryBookByID(@Param("bookid") int id);
//查全部
List<Books> qeeryBooks();
//根据名字查询书籍
Books queryBooksByName(@Param("bookName") String bookNmae);
}
mapper.xml
<?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="wyf.study.dao.BookMapper">
<insert id="addBook" parameterType="wyf.study.pojo.Books">
insert into books(bookid,bookName,bookCounts,detail) values(#{bookid},#{bookName},#{bookCounts},#{detail})
</insert>
<delete id="delBookByID" parameterType="int">
delete from books where bookid=#{bookid}
</delete>
<update id="upBook" parameterType="Books">
update books
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookid=#{bookid}
</update>
<select id="queryBookByID" resultType="wyf.study.pojo.Books">
select * from books where bookid=#{bookid}
</select>
<select id="qeeryBooks" resultType="wyf.study.pojo.Books">
select * from books
</select>
<select id="queryBooksByName" resultType="Books">
select * from books where bookName=#{bookName}
</select>
</mapper>
【wyf.study.service】
接口
package wyf.study.services;
import org.apache.ibatis.annotations.Param;
import wyf.study.pojo.Books;
import java.util.List;
public interface BookService {
//增加
int addBook(Books books);
//删除
int delBookByID( int id);
//改
int upBook(Books books);
//根据id查
Books queryBookByID( int id);
//查全部
List<Books> qeeryBooks();
//根据名字查询书籍
Books queryBooksByName(@Param("bookName") String bookNmae);
}
实现类:
package wyf.study.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wyf.study.dao.BookMapper;
import wyf.study.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService{
//service调用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 delBookByID(int id) {
return bookMapper.delBookByID(id);
}
@Override
public int upBook(Books books) {
return bookMapper.upBook(books);
}
@Override
public Books queryBookByID(int id) {
return bookMapper.queryBookByID(id);
}
@Override
public List<Books> qeeryBooks() {
return bookMapper.qeeryBooks();
}
@Override
public Books queryBooksByName(String bookNmae) {
return bookMapper.queryBooksByName(bookNmae);
}
}
【wyf.study.controller】
这里要与前端进行交互随时更新所以先把前端页面写出来
package wyf.study.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.RequestMapping;
import wyf.study.pojo.Books;
import wyf.study.services.BookService;
import javax.security.auth.login.CredentialException;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
//controller 调用service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部的书籍,并且返回一个书籍页面
@RequestMapping("/allbook")
public String list(Model model){
List<Books> list = bookService.qeeryBooks();
model.addAttribute("list",list);
return "allbook";
}
//跳转到添加书籍页面
@RequestMapping("/toaddbook")
public String toAddPaper(){
return "addbook";
}
//添加书籍的请求
@RequestMapping("/addbook")
public String addBook(Books books){
bookService.addBook(books);
return "redirect:allbook";//重定向到allbook请求
}
//跳转到修改页面
@RequestMapping("/toupbook")
public String toupbook(int id, Model model){
Books books = bookService.queryBookByID(id);
model.addAttribute("querybook",books);
return "upbook";
}
//修改书籍请求
@RequestMapping("/upbook")
public String upbook(Books books){
System.out.println(books);
bookService.upBook(books);
bookService.queryBookByID(books.getBookid());
return "redirect:allbook";
}
//删除书籍
@RequestMapping("/delboook")
public String delbook(int id){
bookService.delBookByID(id);
return "redirect:allbook";
}
//根据姓名查询书籍信息
@RequestMapping("/queryByName")
public String queryname(String queryBookName,Model model){
Books books = bookService.queryBooksByName(queryBookName);
List<Books> list = new ArrayList<>();
list.add(books);
if (books == null){
list=(bookService.qeeryBooks());
model.addAttribute("error","未找到书籍");
}
model.addAttribute("list",list);
return "allbook";
}
}
5.前端JSP页面
index.jsp
<%--
Created by IntelliJ IDEA.
User: 一台小电脑
Date: 2022/9/11
Time: 19:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<style>
a{
text-align: center;
color: bisque;
}
h1{
text-align: center;
color: black;
width: 200px;
height: 30px;
margin: 130px auto;
background: deepskyblue;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>
<a href="/book/allbook"/>跳转
</h1>
</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>
<style>
#container{
width: 1080px;
height:900px;
margin: 0 auto;
}
</style>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="container">
<div class="row_clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>书籍列表------显示所有书籍</small>
</h1>
</div>
</div>
<div class="row clearfix">
<div class="col-md-4 column">
<div class="page-header">
<h3>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toaddbook">新增书籍</a>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allbook">显示全部书籍</a>
</h3>
</div>
</div>
<div class="col-md-4 column"></div>
<div class="col-md-4 column">
<div class="page-header">
<form class="form-inline" action="/book/queryByName" method="post">
<span style="color:red;font-weight: bold">${error}
</span>
<input type="text" name="queryBookName" class="form-control"
placeholder="输入查询书名" required>
<input type="submit" value="查询" class="btn btn-primary">
</form>
</div>
</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>
<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="/book/toupbook?id=${book.bookid}">修改</a>
|
<a href="/book/delboook?id=${book.bookid}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
addbook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加书籍</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
#container{
width: 1080px;
height:900px;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>新增书籍</small>
</h1>
</div>
</div>
</div>
<form action="/book/addbook" method="post">
<div class="form-group">
<label>书籍编号</label>
<input type="text" name="bookid" class="form-control" required>
</div>
<div class="form-group">
<label>书籍名称</label>
<input type="text" name="bookName" class="form-control" 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>
upbook.jsp
<%--
Created by IntelliJ IDEA.
User: 一台小电脑
Date: 2022/9/12
Time: 18:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
#container{
width: 1080px;
height:900px;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改书籍</small>
</h1>
</div>
</div>
</div>
<form action="/book/upbook" method="post">
<input type="hidden" name="bookid" value="${querybook.bookid} ">
<div class="form-group">
<label>书籍名称</label>
<input type="text" name="bookName" class="form-control" value="${querybook.bookName}" required>
</div>
<div class="form-group">
<label>书籍数量</label>
<input type="text" name="bookCounts" class="form-control" value="${querybook.bookCounts}" required>
</div>
<div class="form-group">
<label>书籍描述</label>
<input type="text" name="detail" class="form-control" value="${querybook.detail}" required>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="修改">
</div>
</form>
</div>
</body>
</html>