1、环境要求
环境:
开发工具:IDEA
数据库:MySQL 8
服务器:Tomcat 9
Maven 3.6
要求: 需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单的前端知识;
2、数据库环境
创建一个存放书籍数据的数据库表
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,'从进门到进牢');
3、基本环境搭建
3.1 创建项目
- 打开idea,创建新项目。
新建一Maven项目 项目名字叫ssm 创建完成以后,maven目录结构如下:
3.2 Maven项目添加web支持
右键项目添加web支持 选择添加web框架,注意版本,点击OK! 添加后,idea会自动生成web目录
3.3 配置pom.xml文件
在pom.xml文件中导入相关的pom依赖,设置静态资源过滤!
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</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.3.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>compile</scope>
</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>
3.4 建立框架的基本结构和配置文件
3.4.1 创建包
- com.ssm.pojo
- com.ssm.dao
- com.ssm.service
- com.ssm.controller
- com.ssm.service.Impl
创建后,如下图:
3.4.2 添加配置文件
在resources文件夹下创建以下几个配置文件
- mybatis-config.xml
- applicationContext.xml
- database.properties
- spring-dao.xml
- spring-service.xml
- spring-mvc.xml
添加完成,如下图:
3.4.3 database.properties文件
jdbc.Driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/2022?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username = root
jdbc.password = 123456
3.4.4 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>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.ming.pojo"/>
</typeAliases>
<mappers>
<mapper resource="com/ssm/dao/BookMapper.xml"/>
</mappers>
</configuration>
3.4.5 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:content="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">
<import resource="spring-dao.xml"/>
<import resource="spring-mvc.xml"/>
<import resource="spring-service.xml"/>
</beans>
3.4.6 spring-dao.xml 文件
配置Spring整合MyBatis,我们这里数据源使用c3p0连接池:
<?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:content="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">
<content:property-placeholder location="classpath*:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.Driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.ming.dao"/>
</bean>
</beans>
3.4.7 spring-service.xml文件
Spring整合service层
<?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:content="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<import resource="spring-dao.xml"/>
<content:component-scan base-package="com.ssm.service"/>
<bean id="BookServiceImpl" class="com.ssm.service.Impl.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.ssm.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
</aop:config>
</beans>
3.4.8 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: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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<context:component-scan base-package="com.ssm.controller"/>
</beans>
3.5 框架配置 web.xml文件
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">
<servlet>
<servlet-name>DispatcherServlet</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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</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-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
4、案例
目录结构如下:
4.1 创建实体类Books
package com.ssm.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;
}
4.2 编写Mapper接口
package com.ssm.dao;
import com.ssm.pojo.Books;
import java.util.List;
public interface BookMapper {
int addBook(Books book);
int deleteBookById(int id);
int updateBook(Books book);
Books queryBookById(int id);
List<Books> queryAllBooks();
List<Books> queryBookByName(String bookName);
}
4.3 编写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="com.ssm.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into books
values(#{bookID},#{bookName},#{bookCounts},#{detail})
</insert>
<delete id="deleteBookById" parameterType="int">
delete
from books
where bookID = #{id}
</delete>
<update id="updateBook" parameterType="Books">
update books
set bookName= #{bookName}, bookCounts= #{bookCounts},detail= #{detail}
where bookID = #{bookID}
</update>
<select id="queryBookById" parameterType="int" resultType="Books">
select *
from books
where bookID= #{id}
</select>
<select id="queryAllBooks" resultType="Books">
select *
from books
</select>
<select id="queryBookByName" parameterType="string" resultType="Books">
select *
from books
where bookName = #{bookName}
</select>
</mapper>
4.4 编写业务层接口BookService
package com.ssm.service;
import com.ssm.pojo.Books;
import java.util.List;
public interface BookService {
int addBook(Books book);
int deleteBookById(int id);
int updateBook(Books book);
Books queryBookById(int id);
List<Books> queryAllBooks();
List<Books> queryBookByName(String bookName);
}
4.5 编写业务层接口BookService 实现类BookServiceImpl
package com.ming.service.Impl;
import com.ming.dao.BookMapper;
import com.ming.pojo.Books;
import com.ming.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books book) {
return bookMapper.addBook(book);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books book) {
return bookMapper.updateBook(book);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBooks() {
return bookMapper.queryAllBooks();
}
public List<Books> queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
4.6 编写控制层BooksController
package com.ssm.controller;
import com.ssm.pojo.Books;
import com.ssm.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BooksController {
@Autowired
private BookService bookService;
@GetMapping("/queryAllBooks")
public String queryAllBooks(Model model) {
List<Books> books = bookService.queryAllBooks();
System.out.println(books.toString());
model.addAttribute("books", books);
return "allBook";
}
@RequestMapping("/toAddBook")
public String toAddPaper() {
return "addBook";
}
@PostMapping("/addBook")
public String addBook(Books books, Model model) {
System.out.println(books);
int i = bookService.addBook(books);
if (i == 1) {
model.addAttribute("msg", "添加成功!");
return "redirect:/book/queryAllBooks";
} else {
model.addAttribute("msg", "添加失败!");
return "redirect:/book/queryAllBooks";
}
}
@PostMapping("/updateBook")
public String updateBook(Books book,Model model){
System.out.println(book);
int i = bookService.updateBook(book);
if (i == 1) {
model.addAttribute("msg", "修改成功!");
return "redirect:/book/queryAllBooks";
} else {
model.addAttribute("msg", "修改失败!");
return "redirect:/book/queryAllBooks";
}
}
@GetMapping("/toUpdateBook")
public String toUpdateBook(int id,Model model){
Books books = bookService.queryBookById(id);
model.addAttribute("book",books);
return "updateBook";
}
@RequestMapping("/del/{bookID}")
public String deleteBookById(@PathVariable("bookID") int id,Model model){
System.out.println("---------------------");
System.out.println(id);
int i = bookService.deleteBookById(id);
if (i == 1) {
return "redirect:/book/queryAllBooks";
} else{
return "index";
}
}
@PostMapping("/queryBookByName")
public String queryBookByName(String queryBookName , Model model){
System.out.println("搜索!!!");
List<Books> books = bookService.queryBookByName(queryBookName);
if (books==null){
books = bookService.queryAllBooks();
model.addAttribute("books",books);
}else{
model.addAttribute("books",books);
}
return "allBook";
}
}
4.7 前端页面
4.7.1 index.jsp页面
<%@ 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>
<h1 style="color: red">${msg}</h1>
<h3>
<a href="${pageContext.request.contextPath}/book/queryAllBooks">点击进入列表页</a>
</h3>
</body>
</html>
4.7.2 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">
<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>
<c:if test="${msg}!=null">
<h2><small>${msg}</small></h2>
</c:if>
</div>
</div>
<div class="col-md-4 column"></div>
<div class="col-md-4 column">
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBookByName" method="post" style="float: right">
<input type="text" name="queryBookName" class="form-control" placeholder="输入查询书名" required>
<input type="submit" value="查询" class="btn btn-primary"></form>
</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 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('books')}">
<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/del/${book.getBookID()}"> 删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
4.7.3 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">
<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">
书籍名称:<input type="text" name="bookName"><br><br><br>
书籍数量:<input type="text" name="bookCounts"><br><br><br>
书籍详情:<input type="text" name="detail"><br><br><br>
<input type="submit" value="添加"></form>
</div>
4.7.4 updateBook.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">
<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/updateBook" method="post">
<input type="hidden" name="bookID" value="${book.getBookID()}"/>
书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"/>
书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/>
书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/>
<input type="submit" value="提交"/></form>
</div>
4.7.5 运行展示图:
查询所有图书: 添加图书: 更新图书:
结束!!!
|