文章目录
SSM整合案例
1、软件环境要求
编辑器:IDEA
数据库选择:mysql-5.7.19
服务器选择:tomcat-9.0.24
maven选择:maven-3.6.1
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、创建项目基本环境
1. 在IDEA中创建一个简单的Maven项目ssmIntegration,右键项目添加web框架支持
2. 添加项目相关的pom.xml依赖
<dependencies>
<!--junit依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--mysql数据库驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- c3p0数据库连接池依赖 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--jsp依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!--jstl依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--mybatis-spring依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--spring-webmvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--spring-jdbc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- lombok依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
</dependencies>
3. 在pom.xml中设置Maven资源过滤
<!--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>
4. 创建基本的项目结构和配置框架
-
org.westos.controller:控制层,控制页面的跳转
-
org.westos.mapper:实体类对应的接口及实现类
-
org.westos.pojo:实体类
-
org.westos.service:调用dao层的代码
-
spring:存放spring对应的配置文件
-
jsp:存放页面
-
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总的配置文件,用来引用spring包下的其他spring配置,点击创建新的ApplicationContext
<?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>
4、MyBatis层编写
- 数据库配置文件database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
#mysql数据库账号
jdbc.username=root
#mysql数据库密码
jdbc.password=123
- 编写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>
<!--别名设置-->
<typeAliases>
<package name="org.westos.pojo"/>
</typeAliases>
<!--映射的mapper.xml配置-->
<mappers>
<mapper resource="org/westos/mapper/BookMapper.xml"/>
</mappers>
</configuration>
-
编写数据库表对应的实体类org.westos.pojo.Books
使用Lombok简化
package org.westos.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;//ID
private String bookName;//书名
private int bookCounts;//数量
private String detail;//简介
}
- 编写dao层的mapper接口
package org.westos.dao;
import org.westos.pojo.Books;
import java.util.List;
public interface BookMapper {
//增加一本书
int addBook(Books book);
//根据ID删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查询所有书籍的信息
List<Books> queryAllBook();
}
- 编写mapper接口对应的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="org.westos.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>
<!--查询全部Book-->
<select id="queryAllBook" resultType="Books">
SELECT * from ssmbuild.books
</select>
</mapper>
-
编写Service层接口及实现类
接口:org.westos.service.BookService
package org.westos.service;
import org.westos.pojo.Books;
import java.util.List;
public interface BookService {
//增加一本书
int addBook(Books book);
//根据ID删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查询所有书籍的信息
List<Books> queryAllBook();
}
实现类:org.westos.service.BookServiceImpl
package org.westos.service;
import org.westos.dao.BookMapper;
import org.westos.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
//这个mapper对象用来调用BookMapper接口中的方法
private BookMapper mapper;
//利用Spring-IOC容器给mapper属性赋值
public void setBookMapper(BookMapper mapper) {
this.mapper = mapper;
}
public int addBook(Books book) {
return mapper.addBook(book);
}
public int deleteBookById(int id) {
return mapper.deleteBookById(id);
}
public int updateBook(Books books) {
return mapper.updateBook(books);
}
public List<Books> queryAllBook() {
return mapper.queryAllBook();
}
}
到此,底层的业务需求层编写完毕,service调用dao层,dao层与数据库进行交互
5、Spring配置
-
spring整合MyBatis,配置
spring-dao.xml
数据源使用c3p0连接池
注意:第一个spring配置文件
applicationContext.xml
选择创建应用环境ApplicationContext,后面的spring配置文件都选择加入,而不是创建新的,确保一个程序中只有一个ApplicationContext
<?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、关联数据库文件database.properties-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2、数据库连接池-->
<!--数据库连接池
dbcp 半自动化操作,不能自动连接
c3p0 自动化操作(自动加载配置文件,并设置到对象里面)-->
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--配置连接池属性,从database.properties配置文件中获得-->
<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"/>
<!--关闭后不能自动提交-->
<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全局配置文件:mybatis-config.xml-->
<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="org.westos.dao"/>
</bean>
</beans>
- spring整合service层,配置
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="org.westos.service"/>
<!--将BookServiceImpl注入到IOC容器中-->
<bean id="BookServiceImpl" class="org.westos.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据库连接池-->
<property name="dataSource" ref="datasource"/>
</bean>
</beans>
6、SpringMVC层
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">
<!--DispatcherServlet配置,代替servlet-->
<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>
<!--匹配所有的servlet,不包括jsp等静态资源-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--过滤器filter-->
<filter>
<filter-name>filetr</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>filetr</filter-name>
<!--过滤所有的页面-->
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--设置session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
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页面视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<!--比如返回hello,会被解析成:/WEB-INF/jsp/hello.jsp-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--4.扫描web相关的bean-->
<context:component-scan base-package="org.westos.controller"/>
</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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--导入三个spring配置文件-->
<import resource="spring/spring-dao.xml"/>
<import resource="spring/spring-service.xml"/>
<import resource="spring/spring-mvc.xml"/>
</beans>
7、Controller和视图层编写
- BookController类编写。方法一:查询所有的书籍
package org.westos.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 org.westos.pojo.Books;
import org.westos.service.BookService;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
//类上和方法上的的RequestMapping,合起来是/book/allBook
public String list(Model model) {
List<Books> books = bookService.queryAllBook();
model.addAttribute("list", books);
//经过视图解析器解析成:/WEB-INF/jsp/allBook.jsp
//请求该路径下的jsp页面
return "allBook";
}
}
2. 编写首页index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<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>
3. 书籍列表页面allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: 北风
Date: 2020/2/27
Time: 20:38
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">
<%--引入bootstrap样式--%>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>书籍列表 —— 显示所有书籍</small>
</h1>
</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>
</body>
</html>
4. BookController类编写,方法二:添加书籍
@RequestMapping("/toAddBook")
public String toAddPaper() {
//转发到添加书籍界面
return "addBook";
}
@RequestMapping("/addBook")
public String addPaper(Books books) {
System.out.println(books);
bookService.addBook(books);
//添加书籍之后重定向到所有书籍信息界面
//重定向:redirect
//默认是请求转发
return "redirect:/book/allBook";
}
5. 添加书籍界面: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">
书籍名称:<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>
6. BookController类编写,方法三:修改书籍
@RequestMapping("/toUpdateBook")
public String yoUpdateBook(Model model, int id) {
//得到要修改书籍的信息,然后跳转到修改界面
Books book = bookService.queryBookById(id);
model.addAttribute("book", book);
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Model model, Books book) {
bookService.updateBook(book);
Books books = bookService.queryBookById(book.getBookID());
model.addAttribute("books", books);
return "redirect:/book/allBook";
}
7. 修改书籍页面,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>
8. BookController类编写,方法四:删除书籍
@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
8、配置Tomcat服务器,测试运行
1. 配置Tomcat服务器,测试运行
2. 将程序的jar包导入进lib目录
- 程序结构图
如果还想要增加新功能,按以下步骤:
改前端页面—接受前端请求(controller)—service—mapper—操作数据库