SSM框架最新整合保姆级教程(IDEA版)
一、环境要求
环境:
- IDEA
- MySQL 5.7.19
- Tomcat 9
- Maven 3.6
要求:
- 需要熟练掌握
MySQL数据库
,Spring
,JavaWeb
及MyBatis
知识,简单的前端知识;
完整代码:完整代码下载
二、数据库环境
创建一个存放书籍数据的数据库表
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.1 新建项目
① 新建Maven项目
② 编辑项目名称
3.2 导入相关的pom依赖
<!-- 依赖问题:junit、数据库驱动、连接池、servlet、jsp、mybatis、mybatis-spring、spring-->
<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>1.3.1</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.14.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
</dependencies>
3.3 Maven资源过滤设置(pom.xml文件中)
<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 建立基本的结构和配置框架
-
com.wang.pojo
-
com.wang.dao
-
com.wang.service
-
com.wang.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层编写
4.1 数据库配置文件database.properties
jdbc.driver=com.mysql.jdbc.Driver
#如果使用的是MySQL8.0+,还需要增加一个时区的配置;
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
4.2 IDEA关联数据库
① 输入用户名、密码,测试连接
② 选择数据库
4.3 编写mybatis核心配置文件
① 配置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>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 配置数据源,现在交给Spring去做-->
<typeAliases>
<package name="com.wang.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.wang.dao.BookMapper"/>
</mappers>
</configuration>
② 编写实体类books
package com.wang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author Wang
* @date 2021/6/2 0012 19:43
* description 实体类books
*/
@Data
@AllArgsConstructor //有参构造
@NoArgsConstructor //无参构造
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
③ 新建一个dao
接口
package com.wang.dao;import com.wang.pojo.Books;import org.apache.ibatis.annotations.Param;import org.springframework.stereotype.Repository;import java.util.List;/** * @author Wang * @date 2021/6/2 0012 19:52 * description */@Repositorypublic interface BookMapper {// 增加一本书 int addBook(Books books);// 删除一本书 int deleteBookById(@Param("bookID") int id);// 更新一本书 int updateBook(Books books);// 查询一本书 Books queryBookById(@Param("bookID") int id);// 查询全部的书 List<Books> queryAllBook(); Books queryBookByName(@Param("bookName") String bookName);}
④ 书写mapper.xml
文件
一个mapper就要有一个namespace。
<?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.wang.dao.BookMapper">
<!--增加一个Book-->
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books(bookName,bookCounts,detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert>
<!--根据id删除一个Book-->
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books where bookID=#{bookID}
</delete>
<!--更新Book-->
<update id="updateBook" parameterType="Books">
update ssmbuild.books
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<!--根据id查询,返回一个Book-->
<select id="queryBookById" resultType="Books">
select * from ssmbuild.books
where bookID = #{bookID}
</select>
<!--查询全部Book-->
<select id="queryAllBook" resultType="Books">
SELECT * from ssmbuild.books
</select>
<!-- 根据书籍名称查询一本书-->
<select id="queryBookByName" resultType="Books">
select * from ssmbuild.books
where bookName = '${bookName}'
</select>
</mapper>
⑤ 编写service
层
package com.wang.service;
import com.wang.pojo.Books;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Wang
* @date 2021/5/12 0012 20:03
* description
*/
@Service
public interface BookService {
// 增加一本书
int addBook(Books books);
// 删除一本书
int deleteBookById(int id);
// 更新一本书
int updateBook(Books books);
// 查询一本书
Books queryBookById(int id);
// 查询全部的书
List<Books> queryAllBook();
Books queryBookByName(String bookName);
}
package com.wang.service;
import com.wang.dao.BookMapper;
import com.wang.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Wang
* @date 2021/5/12 0012 20:04
* description
*/
@Service
public class BookServiceImpl implements BookService {
// service调用dao层
@Autowired
private 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();
}
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
五、整合Spring层
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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1、关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 2、连接池
dbcp:半自动化操作,不能自动连接
c3p0:自动化操作自动化的加载配置文件
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-config.xml"/>
</bean>
<!-- 4、配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包-->
<property name="basePackage" value="com.wang.dao"/>
</bean>
</beans>
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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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">
<!-- 1、扫描service下的包-->
<context:component-scan base-package="com.wang.service"/>
<!--<!– 2、将我们的所有业务类注入到Spring,可以通过配置,或者注解实现 –>-->
<!-- <bean id="BookServiceImpl" class="com.wang.service.BookServiceImpl">-->
<!-- <property name="bookMapper" ref="bookMapper"/>-->
<!-- </bean>-->
<!-- 3、声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 4、aop事务支持-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.wang.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
</beans>
六、整合SpringMVC
1、增加web依赖
右键项目名–>选择Add Frameworks Support
2、编写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">
<!-- DispatchServlet-->
<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>
</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>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>
</web-app>
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">
<!-- 配置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.wang.controller" />
</beans>
4、编写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-mvc.xml"/> <import resource="classpath:spring-service2.xml"/> <import resource="classpath:spring-dao.xml"/></beans>
七、编写功能
1、查询书籍功能
① 编写BookController
类
package com.wang.controller;
import com.wang.pojo.Books;
import com.wang.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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
/**
* @author Wang
* @date 2021/5/12 0012 21:12
* description
*/
@Controller
@RequestMapping("/book")
public class BookController {
// controller调用service层
@Autowired
private BookService bookService;
// 查询选全部的书籍,并且返回到一个书籍展示页面
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list = bookService.queryAllBook();
model.addAttribute("list",list);
return "allBook";
}
// 跳转到增加书籍页面
@RequestMapping("/toAddBookPage")
public String toAddPaper(){
return "addBook";
}
// 进行添加书籍
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("=======>"+books);
bookService.addBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
}
// 跳转到修改书籍页面
@RequestMapping("/toEditBookPage")
public String toEditBookPage(int id,Model model){
Books books = bookService.queryBookById(id);
model.addAttribute("books",books);
return "editBook";
}
@RequestMapping("/editBook")
public String editBook(Books books){
System.out.println("=======>"+books);
bookService.updateBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
}
@RequestMapping("/deleteBook/{bookId}")
public String deleteBook(@PathVariable("bookId") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
Books books = bookService.queryBookByName(queryBookName);
List<Books> list = new ArrayList<Books>();
list.add(books);
if(books==null){
list = bookService.queryAllBook();
model.addAttribute("error","未查到");
}
model.addAttribute("list",list);
return "allBook";
}
}
② 测试查询书籍功能
· 发现错误
· 修改方法,可以看到WEB-INF下面只有一个classes文件,没有lib文件夹
· 把原来的这个books:war exploded
叉掉,新建一个即可
· 又发现错误
· 检查发现少了一个依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
③ 测试成功
Preparing: SELECT * from ssmbuild.books
Parameters:
< Columns: bookID, bookName, bookCounts, detail
< Row: 1, Java, 77, 从入门到放弃
< Row: 2, MySQL, 101, 从删库到跑路
< Row: 3, Linux, 5, 从进门到进牢哈哈哈哈
< Row: 5, 数据结构, 99, C语言版
< Row: 6, C#程序设计实用教程, 88, 机械工业出版社
< Row: 7, C程序设计, 36, 清华大学出版社
< Total: 6
2、添加书籍
① 跳转到增加书籍页面
// 跳转到增加书籍页面
@RequestMapping("/toAddBookPage")
public String toAddPaper(){
return "addBook";
}
② 编写增加书籍页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/6/3 0012
Time: 23:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<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-4 column">
<div class="page-header">
<div class="alert alert-info" role="alert">
<h1>增加书籍页面</h1>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<div class="form-group">
<label>书籍名称</label>
<input type="text" class="form-control" name="bookName" required>
</div>
<div class="form-group">
<label>书籍数量</label>
<input type="text" class="form-control" name="bookCounts" required>
</div>
<div class="form-group">
<label>书籍描述</label>
<input type="text" class="form-control" name="detail" required>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="添加">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
③ 进行书籍的添加
// 进行添加书籍
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("=======>"+books);
bookService.addBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
}
3、修改书籍信息
① 跳转到修改书籍页面
// 跳转到修改书籍页面
@RequestMapping("/toEditBookPage")
public String toEditBookPage(int id,Model model){
Books books = bookService.queryBookById(id);
model.addAttribute("books",books);
return "editBook";
}
② 修改书籍页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/6/3 0012
Time: 23:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<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-4 column">
<div class="page-header">
<div class="alert alert-danger" role="alert">
<h1>修改书籍页面</h1>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/editBook" method="post">
<input type="hidden" name="bookID" value="${books.bookID}">
<div class="form-group">
<label>书籍名称</label>
<input type="text" class="form-control" name="bookName" value="${books.bookName}" required>
</div>
<div class="form-group">
<label>书籍数量</label>
<input type="text" class="form-control" name="bookCounts" value="${books.bookCounts}" required>
</div>
<div class="form-group">
<label>书籍描述</label>
<input type="text" class="form-control" name="detail" value="${books.detail}" required>
</div>
<div class="form-group">
<input type="submit" class="btn btn-danger" value="修改">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
③ 进行书籍信息修改
@RequestMapping("/editBook")
public String editBook(Books books){
System.out.println("=======>"+books);
bookService.updateBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
}
<input type="text" class="form-control" name="bookCounts" value="${books.bookCounts}" required>
</div>
<div class="form-group">
<label>书籍描述</label>
<input type="text" class="form-control" name="detail" value="${books.detail}" required>
</div>
<div class="form-group">
<input type="submit" class="btn btn-danger" value="修改">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
③ 进行书籍信息修改
@RequestMapping("/editBook")
public String editBook(Books books){
System.out.println("=======>"+books);
bookService.updateBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
}