根据狂神大佬的教学项目整理笔记:
核心架构如下图:
在这里插入图片描述
分为步骤进行整合:
1.前期准备工作。(创建maven项目,导包,创建目录,创建数据库)
-
Mybatis 整合部分
-
1.1创建项目
在这里插入图片描述 -
1.2 添加web依赖
** 加粗样式
-
1.3连接数据库,创建表和数据
在这里插入图片描述
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,'从进门到进牢');
- 1.4 添加项目依赖 pom.xml
<!--普通依赖-->
<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>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</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>
</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.5 添加artifacts 依赖,新建lib文件,
在这里插入图片描述
添加,选中全部加入
在这里插入图片描述 -
1.6 创建项目包结构和基本数据
-
com.zhy.pojo
-
com.zhy.controller
-
com.zhy.service
-
com.zhy.dao
新建 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>
</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>
新建 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
数据库mysql 8.0+ 需要注意
- 时区 :serverTimezone=Asia/Shanghai
- useSSL=false
- 1.7 编写mybatis配置
package com.zhy.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;
}
编写BookMapper 接口
package com.zhy.dao;
import com.zhy.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.awt.print.Book;
import java.util.List;
public interface BookMapper {
/***
* 新增一个books
* @param books
* @return
*/
int addBoook(Books books);
/***
* 删除一个books
* @param bookID
* @return
*/
int deleteBook(@Param("bookID") int bookID);
/***
* 更新一个books
* @param books
* @return
*/
int updateBook(Books books);
/***
* 根据id查询一个books
* @param bookID
* @return
*/
Books queryBookByID(@Param("bookID") int bookID);
/***
* 查询所有books
* @return
*/
List<Books> queryBookAll();
}
编写 BookMapper.xml
- IDEA 编写数据库 快捷 用法
- 插入 ins
- 更新 upd
- 查询 sel
经验:如果没有提示数据库名字和表名可以参考如下设置:
<?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.zhy.dao.BookMapper">
<insert id="addBoook" parameterType="Books">
insert into ssmbuild.books (bookID, bookName, bookCounts, detail)
values (#{bookID},#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBook" parameterType="int" >
delete from ssmbuild.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">
select *
from ssmbuild.books where bookID=#{bookID};
</select>
<select id="queryBookAll" resultType="Books">
select *
from ssmbuild.books;
</select>
</mapper>
别忘了在 mybatis-config.xml 配置mapper
<?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.zhy.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.zhy.dao.BookMapper"/>
</mappers>
</configuration>
创建 BooksService
package com.zhy.service;
import com.zhy.pojo.Books;
import java.util.List;
public interface BooksService {
/***
* 新增一个books
* @param books
* @return
*/
int addBoook(Books books);
/***
* 删除一个books
* @param bookID
* @return
*/
int deleteBook( int bookID);
/***
* 更新一个books
* @param books
* @return
*/
int updateBook(Books books);
/***
* 根据id查询一个books
* @param bookID
* @return
*/
Books queryBookByID( int bookID);
/***
* 查询所有books
* @return
*/
List<Books> queryBookAll();
}
创建 BooksServiceImpl 业务层实现类
package com.zhy.service;
import com.zhy.dao.BookMapper;
import com.zhy.pojo.Books;
import java.util.List;
@Service
public class BooksServiceImpl implements BooksService{
/***
* service 业务层 持有 dao层进行业务处理
* service 可以使用dao的方法
*/
private BookMapper bookMapper;
/***
* set 方法提供spring 进行ioc注入
* @param bookMapper
*/
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBoook(Books books) {
return bookMapper.addBoook(books);
}
public int deleteBook(int bookID) {
return bookMapper.deleteBook(bookID);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookByID(int bookID) {
return bookMapper.queryBookByID(bookID);
}
public List<Books> queryBookAll() {
return bookMapper.queryBookAll();
}
}
============================Mybatis 配置基本结束=================================
Spring 整合 dao(mybatis) 层
- 2.1 新建 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
http://www.springframework.org/schema/context/spring-context.xsd">
<!--1.关联db配置文件 这样就相当于让spring 扫描里面的数据-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2. 配置datasourse 连接池这边可以配置 c3p0 -->
<bean id="dataScource" 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="dataScource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4.配置动态扫描dao接口的包,实现动态注入到spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlsessionFactory"/>
<property name="basePackage" value="com.zhy.dao"
</bean>
</beans>
Spring 整合 service 层
- 2.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.zhy.service" />
<!--BookServiceImpl注入到IOC容器中-->
<bean id="BooksServiceImpl" class="com.zhy.service.BooksServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataScource" />
</bean>
</beans>
记得在 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 resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
==================Spring 整合基本结束======================
- SpringMVC层
- 3.1 web.xml
<!--DispatcherServlet-->
<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>
<!--encodingFilter-->
<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>
- 3.2 新建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">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解驱动 -->
<mvc:annotation-driven />
<!-- 2.静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示ViewResolver视图解析器 -->
<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>
<!-- 4.扫描web相关的bean -->
<context:component-scan base-package="com.zhy.controller" />
</beans>
- 3.3 最后添加配置依赖关系 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="classpath:spring-service.xml"/>
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
最后编写controler
package com.zhy.controller;
import com.zhy.pojo.Books;
import com.zhy.service.BooksService;
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 java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("BooksServiceImpl")
private BooksService bookService;
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryBookAll();
model.addAttribute("list", list);
return "allBook";
}
}
最后配置几个页面进行测试 allBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${list}
</body>
</html>
配置tomcat 进行测试
浏览器输入 http://localhost:8081/book/allBook
[图片上传失败...(image-dbbcaa-1604987605888)]
测试完成
至此简单的SSM 架构搭建完毕,后面都是页面和义务代码,我直接贴了
- 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>
<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>
<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/del/${book.getBookID()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
- BookController 类编写
package com.zhy.controller;
import com.zhy.pojo.Books;
import com.zhy.service.BookService;
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;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
public String list(Model model){
final Books books1 = bookService.queryBookById(1);
System.out.println(books1);
final List<Books> list = bookService.queryAllBook();
for (Books books : list) {
System.out.println(books);
}
model.addAttribute("list",list);
return "allBook";
}
@RequestMapping("/toAddBook")
public String toAddPaper() {
return "addBook";
}
@RequestMapping("/addBook")
public String addPaper(Books books) {
System.out.println(books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
@RequestMapping("/toUpdateBook")
public String toUpdateBook(Model model, int id) {
Books books = bookService.queryBookById(id);
System.out.println(books);
model.addAttribute("book",books );
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Model model, Books book) {
System.out.println(book);
bookService.updateBook(book);
Books books = bookService.queryBookById(book.getBookID());
model.addAttribute("books", books);
return "redirect:/book/allBook";
}
@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
}
- 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">
<!-- 引入 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/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>
至此完整的项目编写完毕。收获满满~这个项目我练习了两遍,因为狂神说这是基础入门,一定要熟练掌握基础。
这是我第一次练习的代码仅供参考,和上面截图有点不一样:
练习项目 https://gitee.com/zhyazaq/sbmbuild
想学习后台的可以 看https://www.bilibili.com/read/cv5702420 狂神教学,一起学习一起进步~撒
网友评论