SSM整合
数据库环境
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、新建一个空Maven项目,命名ssmbuild,添加web支持
2、在pom.xml中导入相关依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.9.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
</dependencies>
3、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、项目结构
-
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>
Mybatis层编写
1、数据库配置文件database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&useSSL=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
2、IDEA关联数据库
3、编写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="com.jian.pojo"/>
</typeAliases>
<mappers>
<package name="com.jian.dao"/>
</mappers>
</configuration>
4、编写实体类Books,使用Lombok插件
package com.jian.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;
}
5、编写Dao层的BookMapper接口
package com.jian.dao;
import com.jian.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
//新增一本书
int addBook(Books books);
//删除一本书
int deleteBook(@Param("bookId") int id);
//修改一本书
int updateBook(Books books);
//查询一本书
Books getBookById(@Param("bookId") int id);
//查询所有书
List<Books> getBooks();
//模糊查询
List<Books> getBookByName(@Param("bookName") String name);
}
6、编写BookMapper对应的BookMapper.xml文件
<?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.jian.dao.BookMapper">
<insert id="addBook" parameterType="books">
insert into books(bookName, bookCounts, detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert>
<delete id="deleteBook">
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="getBookById" parameterType="int" resultType="books">
select *
from books
where bookID = #{bookId}
</select>
<select id="getBooks" resultType="books">
select *
from books;
</select>
<select id="getBookByName" resultType="books">
select *
from books
where bookName like concat("%", #{bookName}, "%")
</select>
</mapper>
7、编写Service层接口BookService和实现类BookServiceImpl
package com.jian.service;
import com.jian.pojo.Books;
import java.util.List;
public interface BookService {
//新增一本书
int addBook(Books books);
//删除一本书
int deleteBook(int id);
//修改一本书
int updateBook(Books books);
//查询一本书
Books getBookById(int id);
//查询所有书
List<Books> getBooks();
//模糊查询
List<Books> getBookByName(String name);
}
package com.jian.service;
import com.jian.dao.BookMapper;
import com.jian.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books books) {
return bookMapper.addBook(books);
}
@Override
public int deleteBook(int id) {
return bookMapper.deleteBook(id);
}
@Override
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public Books getBookById(int id) {
return bookMapper.getBookById(id);
}
@Override
public List<Books> getBooks() {
return bookMapper.getBooks();
}
@Override
public List<Books> getBookByName(String name) {
return bookMapper.getBookByName(name);
}
}
Spring层编写
1、配置Spring整合MyBatis,这里使用C3P0连接池
2、编写Spring整合MyBatis的配置文件,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、关联数据库配置文件:database.properties-->
<context:property-placeholder location="classpath:database.properties"/>
<!--
2、连接池:
DBCP:半自动化操作,不能自动连接
C3P0:自动化操作(自动化的加载配置文件,并且可以自动设置到对象中
-->
<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="initialPoolSize" value="10"/>
<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"/>
<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.jian.dao"/>
</bean>
</beans>
3、Spring整合Service层
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--1、扫描Service下的包-->
<context:component-scan base-package="com.jian.service"/>
<!--2、将我们的所有业务类,注入到Spring中,可以通过配置或者注解实现-->
<bean id="bookService" class="com.jian.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3、声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<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>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.jian.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
</beans>
SpringMVC层
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">
<!--DispatcherServlet-->
<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>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-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
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描controller下的包-->
<context:component-scan base-package="com.jian.controller"/>
<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--视图解析器-->
<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整合所有配置文件,编写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-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:springmvc-servlet.xml"/>
</beans>
配置文件暂时结束,然后是Controller和视图的编写
1、首页index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
h3{
margin: 100px auto;
width: 180px;
height: 38px;
line-height: 38px;
background: greenyellow;
text-align: center;
border-radius: 10px;
}
a{
text-decoration: none;
color: black;
font-size: 18px;
}
</style>
</head>
<body>
<h3><a href="${pageContext.request.contextPath}/book/allBook">进入书籍展示页面</a></h3>
</body>
</html>
2、BookController类编写
package com.jian.controller;
import com.jian.pojo.Books;
import com.jian.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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("bookService")
private BookService bookService;
}
3、在BookController类下编写方法,方法一:查询所有书籍
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> books = bookService.getBooks();
model.addAttribute("list", books);
return "allBook";
}
4、书籍展示页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>
<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="column col-md-12">
<h3 class="page-header">
<small>书籍展示页面-->显示所有书籍</small>
</h3>
</div>
</div>
<div class="row">
<div class="column col-md-4">
<a href="${pageContext.request.contextPath}/book/toAddBook" class="btn btn-primary">添加书籍</a>
</div>
<div class="column col-md-8">
<form action="${pageContext.request.contextPath}/book/query" method="post" class="form-inline">
<input type="text" name="queryName" class="form-control" placeholder="请输出要查询书籍的名字">
<input type="submit" class="btn btn-primary" value="查询">
</form>
</div>
</div>
<div class="row clearfix">
<div class="column col-md-12">
<table class="table table-hover table-stripe">
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名称</th>
<th>书籍数量</th>
<th>书籍详情</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${list}">
<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.getBookID()}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.getBookID()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
5、在BookController类下编写方法,方法二:添加书籍
@RequestMapping("/toAddBook")
public String toAddBook() {
return "addBook";
}
@PostMapping("/addBook")
public String addBook(Books books) {
int i = bookService.addBook(books);
return "redirect:/book/allBook";
}
添加书籍页面addBook.jsp
<%@ 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-12 column">
<h3 class="page-header">
<small>新增书籍</small>
</h3>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
书籍名称:<input type="text" name="bookName" required><br><br><br>
书籍数量:<input type="text" name="bookCounts" required><br><br><br>
书籍详情:<input type="text" name="detail" required><br><br><br>
<input type="submit" value="添加">
</form>
</div>
</body>
</html>
6、在BookController类下编写方法,方法三:修改书籍
修改书籍页面updateBook.jsp
<%@ 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-12 column">
<h3 class="page-header">
<small>修改书籍</small>
</h3>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<input type="hidden" name="bookID" value="${book.bookID}">
书籍名称:<input type="text" name="bookName" value="${book.bookName}" required><br><br><br>
书籍数量:<input type="text" name="bookCounts" value="${book.bookCounts}" required><br><br><br>
书籍详情:<input type="text" name="detail" value="${book.detail}" required><br><br><br>
<input type="submit" value="修改">
</form>
</div>
</body>
</html>
@RequestMapping("/toUpdateBook")
public String toUpdate(int id, Model model) {
Books book = bookService.getBookById(id);
model.addAttribute("book", book);
return "updateBook";
}
@PostMapping("/updateBook")
public String updateBook(Books books) {
int i = bookService.updateBook(books);
return "redirect:/book/allBook";
}
7、在BookController类下编写方法,方法四:删除书籍
@RequestMapping("/deleteBook/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
int i = bookService.deleteBook(id);
return "redirect:/book/allBook";
}
8、在BookController类下编写方法,方法五:查询书籍
@RequestMapping("/query")
public String getBookByName(String queryName, Model model) {
List<Books> list = bookService.getBookByName(queryName);
model.addAttribute("list", list);
return "allBook";
}
配置Tomcat,启动测试