目录
写在前面
1 整体系统构图
2 数据库的准备
3 创建maven项目
4 编写实体类(pojo)
5编写mapper层
5.1 编写mapper接口
5.2 编写mapper对应的配置文件
5.3 编写mybatis核心配置文件
5.4 编写spring-dao配置文件
6 编写service层
6.1 编写service接口
6.2 编写接口对应的实现类
6.3 编写service层的spring配置文件
7 controller层
7.1 编写controller实体类
7.2 springmvc配置文件
8 进行web.xml配置
9 前端页面的编写
写在前面
花了一段时间看完了狂神的SSM框架,最后通过一个图书系统进行了spring,springMVC和mybatis三个框架的整合,该系统主要就是实现了图书的增删改查,写此博客进行SSM的整合复习。
1 整体系统构图
整个系统采用的是经典的MVC三层架构,如下图所示,编写项目时,仍然是按照自底向上的顺序进行编写。后序过程的介绍也是这样。
2 数据库的准备
CREATE TABLE books(
bookID INT(10) PRIMARY KEY AUTO_INCREMENT,
bookName VARCHAR(36) NOT NULL,
bookCounts INT(10) NOT NULL,
detail VARCHAR(36) NOT NULL)
ENGINE=INNODB CHARSET=utf8;
3 创建maven项目
? ? ? ? 在idea中创建maven项目并配置maven依赖,一般来说我们的ssm整合项目中需要如下一些包
- junit单元测试包,在项目搭建的过程中我们应该没编写完一个层或者一个类就要对其进行简单的功能测试
- fastjson包java中将数据转换成json格式或者解析json格式数据的包,这个包在我们这个项目中并没有使用到。
- mapper层需要使用到的包:mysql驱动,c3p0数据库连接池,mybatis,mybatis-spring,spring-jdbc
- spring相关的包spring-webmvc
- 然后就是依稀与jsp相关的包
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springmvc</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>springmvc-06-ssm</module>
</modules>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.14</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
4 编写实体类(pojo)
编写我们的books列表对应的Books类,因为我们的项目是对图书进行操作,所以此处我们实体类的属性和我们books列表的列是一一对应的,这里注意字段的类型和名称要和数据库中的表一致。
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
public Books() {}
@Override
public String toString() {
return "Books{" +
"bookID=" + bookID +
", bookName='" + bookName + '\'' +
", bookCounts=" + bookCounts +
", detail='" + detail + '\'' +
'}';
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCounts() {
return bookCounts;
}
public void setBookCounts(int bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Books(int bookID, String bookName, int bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
}
5编写mapper层
5.1 编写mapper接口
public interface BookMapper {
//增加一本书
public int addBook(Books books);
//更新一本书
public int updateBook(Books books);
//删除一本书
public int deleteBookById(@Param("bookId") int id);
//查询一本书
public Books queryBookById(@Param("bookId") int id);
//查询全部书
public List<Books> queryAllBooks();
}
这里注意以下@Param()注解,一般对于基本数据类型我们都会加上这个注解,之后mapper.xml文件中就按照注解括号中的名称进行匹配。
5.2 编写mapper对应的配置文件
这里需要注意的就是命名空间一定要对应好,然后就是在编写mapper接口中方法对应的SQL语句,注意id要和方法名一一对应。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tzy.mapper.BookMapper">
<insert id="addBook" parameterType="books">
insert into ssmbuild.books(bookName, bookCounts, detail)
values(#{bookName}, #{bookCounts}, #{detail})
</insert>
<update id="updateBook" parameterType="books">
update ssmbuild.books set bookName=#{bookName}, bookCounts=#{bookCounts}, detail=#{detail}
where bookID=#{bookID}
</update>
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books where bookID=#{bookId}
</delete>
<select id="queryBookById" parameterType="int" resultType="books">
select * from books where bookID=#{bookId}
</select>
<select id="queryAllBooks" resultType="books">
select * from books
</select>
</mapper>
5.3 编写mybatis核心配置文件
由于和spring整合了,所以我们很多原先单穿mybatis的配置可以直接整合到spring的配置文件中,在mybatis核心配置文件中,我们只做两件事,一是进行了别名的设置,这样我们在编写mapper.xml文件时,其中的paramtype时就可以不用类的全限定名,而是直接用别名,默认的别名就是类名,首字母大小写均可
<?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="com.tzy.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.tzy.mapper.BookMapper"/>
</mappers>
</configuration>
5.4 编写spring-dao配置文件
在这个配置文件中,我们主要做了下列事情:
- 获取数据库的配置文件,这个根据自己情况编写对应的properties文件即可
- 进行数据库连接池的配置,这里我们用的是C3P0数据库连接池
- 进行sqlsessionfactory的配置,需要指定两个属性,一是绑定mybatis核心配置文件,二是设置数据库连接池。(这里回顾一下原来只用mybatis的配置,需要将核心配置文件传入到builder的build方法中得到我们的SqlSessionFactory,这里获取factory的操作我们交给了IOC容器)
- 配置dao接口的扫描包,这样扫描包内的mapper接口就能被动态创建得到对应的sqlsession
<?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:db.properties"/>
<!--2 数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${user}"/>
<property name="password" value="${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">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.tzy.mapper"/>
</bean>
</beans>
6 编写service层
6.1 编写service接口
public interface BookService {
//增加一本书
public int addBook(Books books);
//更新一本书
public int updateBook(Books books);
//删除一本书
public int deleteBookById(int id);
//查询一本书
public Books queryBookById(int id);
//查询全部书
public List<Books> queryAllBooks();
}
6.2 编写接口对应的实现类
这里需要注意的是咱们的service层要完成业务必然是要调用咱们的mapper层,所以要在此处设置bookmapper字段并给出我们set方法,这样才能实现bean的注入
public class BookServiceImpl implements BookService{
//service要调用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 updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Books> queryAllBooks() {
return bookMapper.queryAllBooks();
}
}
6.3 编写service层的spring配置文件
这里我们要做的就是两件事,一是将我们所有的业务层都注入到IOC容器中并配置上事务;
这里需要注意我们此时编写的是spring-service.xml需要将该配置文件与之前编写的spring-dao.xml放在同一个上下文中,这是我们可以创建一个总的spring配置文件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"
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:component-scan base-package="com.tzy.service"/>
<!--2 将我们的所有业务页,注入到Spring,可以通过配置或者注解实现-->
<bean id="BookServiceImpl" class="com.tzy.service.BookServiceImpl">
<!--咱们的bookMapper就来自前面spring-dao的配置文件中(配置dao接口扫描包)-->
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3 声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4 aop事务支持-->
</beans>
7 controller层
7.1 编写controller实体类
这一层的任务就是根据客户端的请求调用service层完成相应的任务
@Controller
@RequestMapping("/book")
public class BookController {
//以下两个注解配合实现我们的bookService字段的自动装配
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部的数据并且返回到书籍展示页面
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> books = bookService.queryAllBooks();
model.addAttribute("list", books);
return "allBook";
}
@RequestMapping("/toAddBook")
public String toaddBook() {
return "addBook";
}
@RequestMapping("/addBook")
//当传入的参数是个对象时,将会与对象的字段名进行匹配
public String addBook(Books book) {
bookService.addBook(book);
return "redirect:/book/allBook";
}
@RequestMapping("/del/{bookID}")
public String delBook(@PathVariable("bookID") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
@RequestMapping("/toUpdateBook")
public String toUpdate(Model model, int id) {
Books book = bookService.queryBookById(id);
model.addAttribute("book", book);
return "updateBook";
}
@RequestMapping("updateBook")
public String updateBook(Books books) {
bookService.updateBook(books);
return "redirect:/book/allBook";
}
}
7.2 springmvc配置文件
这个配置文件做了下列事
- 进行注解的配置
- 进行静态资源过滤(这里我去搜了一下,大概是这么个意思,我们在配置dispatcherservlet时URL处写的是"/",就是说我们所有的请求都会交给我们控制器进行处理,所以这里面就会包含静态资源的请求,这样在控制器中找不到就会报404的错误,而进行该配置后,我们dispatcherservlet在找不到请求对应的控制器映射后就会交给DefaultServletHttpRequestHandler处理,这样只有在找不到该静态资源的情况下才会报错)
- 配置视图解析器(此处我们springmvc中的处理器映射器和处理器适配器默认已经配置)
<?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
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1 注解驱动-->
<mvc:annotation-driven/>
<!--2 静态资源过滤-->
<mvc:default-servlet-handler/>
<!--3 扫描包:controll-->
<context:component-scan base-package="com.tzy.controller"/>
<!--4 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
8 进行web.xml配置
这里主要做了两件事
- dispatcherservlet的配置,这里需要注意配置的springmvc配置文件是最后总的配置文件
- 过滤器的配置,用来处理乱码
<?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>
<!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--启动级别-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--session-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
9 前端页面的编写
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>
allBook
<%@ 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>
updateBook
<%@ 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>
index
<%@ 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>
|