Spring SpringMVC Mybatis整合
基础环境搭建
- 1.创建maven工程,添加web支持
创建普通maven项目,
右击项目-->Add Frameworks Support
勾选java web
我这里的项目名:ssmbuild
- 2.引入依赖(jar包)
<!--导入依赖-->
<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.6</version>
</dependency>
<!--数据库连接池驱动-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</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>
<!--servlet程序-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--mybatis-spring mybatis整合spring适配包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<!--Spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<!--AOP织入包-->
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
</dependencies>
<!--maven资源导出问题-->
<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>
SSM整合配置
创建好基本结构和配置框架
注意:这里的框架结构可以分开来写,也可以在一个总的配置文件来写,如果分开写,就要在总的配置文件中import导入其他配置文件
1.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">
<!--1.启动Spring容器(项目启动就会扫描spring上下文)-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--2.SpringMVC的前端控制器 用来拦截所有请求-->
<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>
<!--3.字符编码过滤器-->
<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>
<!--rest风格 将页面的普通请求转换为我们指定的delete 或 put 请求-->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Session生命周期-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
2.springmvc-servlet.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
https://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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--SpringMVC的配置文件,包含网站跳转逻辑的控制,配置-->
<!--1.扫描所有的包 控制器包-->
<context:component-scan base-package="com.it.controller"/>
<!--2.配置mvc不处理静态资源-->
<mvc:default-servlet-handler/>
<!--3.MVC注解支持-->
<mvc:annotation-driven/>
<!--4.配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.spring-dao.xml配置
spring-dao.xml中导入外部配置文件 dbconfig.xml配置如下
jdbc.driver=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&characterEncoding=UTF-8
jdbc.user=root
jdbc.password=001129
<?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
https://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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--引入dbconfig.properties 配置文件-->
<context:property-placeholder location="classpath:dbconfig.properties"/>
<!--数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
<property name="user" value="${jdbc.user}"/>
<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>
<!--和mybatis整合-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--关联Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--指定数据源-->
<property name="dataSource" ref="dataSource"/>
<!--
指定mapper文件的位置
<property name="mapperLocations" value="classpath:"/>
-->
</bean>
<!--配置扫描器,将mybatis接口的实现加入到ioc容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sql'SessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--扫描dao包下的所有-->
<property name="basePackage" value="com.it.dao"/>
</bean>
</beans>
4.mybatis-config.xml配置
<?xml version="1.0" encoding="utf8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--设置-->
<!--别名-->
<typeAliases>
<package name="com.it.pojo"/>
</typeAliases>
<!--配置数据源 DataSource 交给spring去做-->
<mappers>
<mapper class="com.it.dao.BookMapper"/>
</mappers>
</configuration>
5.spring-service.xml配置
<?xml version="1.0" encoding="utf8"?>
<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
https://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.it.service"/>
<!--2.将所有业务类注入到spring,可以使用注解或配置-->
<!--注解-->
<!-- <context:annotation-config/> -->
<!--配置-->
<bean id="bookServiceImpl" class="com.it.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3.声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给那些方法配置事务-->
<!--配置事务的传播特性 propagation-->
<tx:attributes>
<!--propagation="required" 表示 支持当前事务,如果没有事务创建一个事务-->
<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>
<!--配置事务切入-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="txPointCut" expression="execution(* com.it.dao.*.*(..))"/>
<!--将通知切入到切入点中-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
6.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--Spring主配置文件 引入其他配置文件-->
<import resource="springmvc-servlet.xml"/>
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
</beans>
项目编写
1. 编写Dao层 BookMapper.java
package com.it.dao;
import com.it.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author shkstart
* @create 2020-04-21 15:20
*/
public interface BookMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(@Param("bookId") int id);
//修改一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(@Param("bookId") int id);
//查询全部图书
List<Books> queryBooks();
//根据书名查询图书
Books queryBookByName(@Param("bookName") String name);
}
2. 编写mapper实现的xml配置文件
<?xml version="1.0" encoding="utf8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.it.dao.BookMapper">
<insert id="addBook" parameterType="books">
insert into books (`bookName`,`bookCounts`,`detail`)
values(#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBookById" parameterType="int">
delete from books where `bookID` = #{bookId};
</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`=#{bookId};
</select>
<select id="queryBooks" parameterType="books" resultType="books">
select * from books;
</select>
<select id="queryBookByName" resultType="books">
select * from books where `bookName` = #{bookName};
</select>
</mapper>
3. 测试 Dao层的方法
4. 编写service层 BookService.java
package com.it.service;
import com.it.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author shkstart
* @create 2020-04-21 15:41
*/
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//修改一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int id);
//查询全部图书
List<Books> queryBooks();
//根据书名查询图书
Books queryBookByName(String bookName);
}
5. 编写service的实现类 BookServiceImpl.java
package com.it.service;
import com.it.dao.BookMapper;
import com.it.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author shkstart
* @create 2020-04-21 15:42
*/
public class BookServiceImpl implements BookService {
//service 调用 dao层
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.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> queryBooks() {
return bookMapper.queryBooks();
}
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
6. 测试service层方法
7. 编写index.jsp 页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍</title>
<style>
a{
width: 30px;
height: 20px;
color: black;
/*取消a标签下划线*/
text-decoration: none;
}
h3{
width: 180px;
height: 38px;
/*外边距*/
margin: 100px auto;
/*居中显示*/
text-align: center;
/* 行高*/
line-height: 38px;
background: aqua;
/*圆形边框*/
border-radius: 5px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">进入书籍</a>
</h3>
</body>
</html>
8. 编写WEB-INF/jsp/allBook.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<!--引入在线bootStrap-->
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<title>书籍展示</title>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 colum">
<div class="page-header">
<h1>
<small>书籍列表————显示所有书籍</small>
</h1>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a href="${pageContext.request.contextPath}/book/toAddBook">添加书籍</a>
<a href="${pageContext.request.contextPath}/book/allBook">显示所有书籍</a>
</div>
<div class="col-md-4 column">
<form action="${pageContext.request.contextPath}/book/queryBook" method="post">
<span style="color: red">${error}</span>
<input type="text" name="bookName" class="from-control" placeholder="请输入要查询的书籍名称">
<input type="submit" value="查询">
</form>
</div>
</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>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${books}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.bookID}">修改</a> |
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
9. 编写WEB-INF/jsp/addBook.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<title>Title</title>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 colum">
<div class="page-header">
<h1>
<small>添加书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<div class="form-group">
<label>书籍名称:</label>
<input type="text" name="bookName" class="form-control" required>
</div>
<div class="form-group">
<label>书籍数量:</label>
<input type="text" name="bookCounts" class="form-control" required>
</div>
<div class="form-group">
<label>书籍描述:</label>
<input type="text" name="detail" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" class="form-control"value="添加">
</div>
</form>
</div>
</body>
</html>
10. 编写WEB-INF/jsp/updateBook.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<title>Title</title>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 colum">
<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="${QBook.bookID}">
<div class="form-group">
<label>书籍名称:</label>
<input type="text" name="bookName" class="form-control" required value="${QBook.bookName}">
</div>
<div class="form-group">
<label>书籍数量:</label>
<input type="text" name="bookCounts" class="form-control" required value="${QBook.bookCounts}">
</div>
<div class="form-group">
<label>书籍描述:</label>
<input type="text" name="detail" class="form-control" required value="${QBook.detail}">
</div>
<div class="form-group">
<input type="submit" class="form-control"value="添加">
</div>
</form>
</div>
</body>
</html>
11. 编写Controller层 BookController.java
package com.it.controller;
import com.it.pojo.Books;
import com.it.service.BookService;
import com.it.service.BookServiceImpl;
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 org.springframework.web.bind.annotation.RequestParam;
import java.awt.print.Book;
import java.util.ArrayList;
import java.util.List;
/**
* @author shkstart
* @create 2020-04-21 16:44
*/
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("bookServiceImpl")
private BookService bookService = new BookServiceImpl();
//查询全部书籍 返回一个书籍展示页面
@RequestMapping("/allBook")
public String allBook(Model model){
List<Books> books = bookService.queryBooks();
model.addAttribute("books",books);
return "allBook";
}
//跳转到新增书籍页面
@RequestMapping("/toAddBook")
public String addPages(){
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("books==>" + books);
bookService.addBook(books);
//请求重定向回首页
return "redirect:/book/allBook";
}
//跳转到修改书籍页面
@RequestMapping("/toUpdateBook")
public String updatePages(int id,Model model){
Books books = bookService.queryBookById(id);
model.addAttribute("QBook",books);
return "updateBook";
}
//修改书籍请求
@RequestMapping("/updateBook")
public String updateBook(Books books){
System.out.println("updateBook==>" + books);
bookService.updateBook(books);
return "redirect:/book/allBook";
}
//删除书籍请求
@RequestMapping("deleteBook/{bookId}")
public String deleteBook(@PathVariable("bookId") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
//根据名字查询图书请求
@RequestMapping("/queryBook")
public String queryBook(@RequestParam("bookName")String name, Model model){
Books books = bookService.queryBookByName(name);
System.out.println(books);
List<Books> list = new ArrayList<Books>();
list.add(books);
if(books == null){
list = bookService.queryBooks();
model.addAttribute("error","未查到有关书籍");
}
model.addAttribute("books",list);
return "allBook";
}
}
12. 测试