一. ssm整合
1.1 项目创建
1.1.1 创建Maven项目
- 创建一个普通的Maven项目名称为ssm
1.1.2 导入依赖(pom.xml)
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--数据库连接池: druid 德鲁伊-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!--Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--JSP-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<!--Jstl-->
<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.3</version>
</dependency>
<!--mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--spring-webmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<!--spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.5</version>
</dependency>
<!--lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
<!--aspectj weaver-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<!--静态资源导出问题-->
<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>
1.1.3 添加web
-
右键ssm > add Framework Support > 选择Web Application > OK
-
File > Project Structure > Artifacts > 选择我们当前项目 > 在WEB-INF下创建lib目录 > 点击+ > 选择Library Files > 添加所有的jar包 > OK
1.1.4 创建项目目录
- src/main/java下创建
- com.dz.pojo
- com.dz.dao
- com.dz.service
- com.dz.controller
- src/main/resources下创建
- jdbc.properties (数据库连接配置文件)
- log4j.properties (日志配置文件)
- mybatis-config.xml (MyBatis配置文件)
- applicationContext.xml (Spring配置文件,总)
- spring-dao.xml (Spring配置文件,子)
- spring-service.xml (Spring配置文件,子)
- spring-mvc.xml (Spring配置文件,子)
- /web/WEB-INF下
- 新建jsp目录, 里面存放.jsp文件
- 已有的web.xml也要进行配置
2.1 配置文件
2.1.1 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_db?useUnicode=true&useSSL=false&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=8031
2.1.2 log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 配置stdout输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# 配置stdout设置为自定义布局模式
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# 配置stdout日志的输出格式 2021-05-01 23:45:26,166 %p日志的优先级 %t线程名 %m日志 %n换行
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} - %5p [%t] - %m%n
2.1.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>
<!--日志-->
<!--<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>-->
<!--实体类别名-->
<typeAliases>
<package name="com.dz.pojo"/>
</typeAliases>
</configuration>
2.1.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"
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">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
2.1.5 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:jdbc.properties"/>
<!--2. 连接池
dbcp: 半自动化操作, 不能自动连接
c3p0: 自动化操作(自动化的加载配置文件, 并且可以自动设置到对象中)
druid
hikari
-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</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.dz.dao"/>
</bean>
</beans>
2.1.6 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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1. 扫描service下的包-->
<context:component-scan base-package="com.dz.service"/>
<!--2. 将我们所有的业务类,注入到Spring, 可以通过配置,或者注解实现-->
<bean id="bookServiceImpl" class="com.dz.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3. 声明式事务管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--支持注解驱动,让@Transaction事务注解生效-->
<tx:annotation-driven/>
<!--4. aop事务支持-->
<!--配置事务通知-->
<tx:advice id="txManager" transaction-manager="transactionManager">
<!--事务属性 给哪些方法配置事务-->
<!--配置事务的传播特性 propagation-->
<tx:attributes>
<!--REQUIRED 默认创建一个新的事务-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.dz.dao.*.*(..))"/>
<aop:advisor advice-ref="txManager" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
2.1.7 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:content="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">
<!--1. 注册驱动-->
<mvc:annotation-driven/>
<!--2. 静态资源过滤-->
<mvc:default-servlet-handler/>
<!--3. 扫描包: controller-->
<content:component-scan base-package="com.dz.controller"/>
<!--4. 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
2.1.8 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. 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>
<!--启动级别: 1-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!--/: 匹配所有请求(不包括.jsp) /*: 匹配所有请求-->
<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>
3.1 项目代码
3.1.1 Books.java
package com.dz.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
3.1.2 BookMapper.java
package com.dz.dao;
import com.dz.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 queryBookById(@Param("bookID") int id);
//根据书名查书
List<Books> queryBookByName(@Param("bookName") String bookName);
//查询全部的书
List<Books> queryAllBook();
}
3.1.3 BookMapper.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="com.dz.dao.BookMapper">
<sql id="query_sql">
select bookID,bookName,bookCounts,detail
from ssmbuild.books
</sql>
<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="deleteBook" parameterType="int">
delete from ssmbuild.books
where bookID=#{bookID}
</delete>
<select id="queryBookById" resultType="Books">
<include refid="query_sql"/>
where bookID=#{bookID}
</select>
<select id="queryBookByName" resultType="Books">
<include refid="query_sql"/>
where bookName like concat('%',#{bookName},'%')
</select>
<select id="queryAllBook" resultType="Books">
<include refid="query_sql"/>
</select>
</mapper>
3.1.4 BookService.java
package com.dz.service;
import com.dz.pojo.Books;
import java.util.List;
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBook(int id);
//更新一本书
int updateBook(Books books);
//根据id查询一本书
Books queryBookById(int id);
//根据书名查书(模糊查询,可能有多本)
List<Books> queryBookByName(String bookName);
//查询全部的书
List<Books> queryAllBook();
}
3.1.5 BookServiceImpl.java
package com.dz.service;
import com.dz.dao.BookMapper;
import com.dz.pojo.Books;
import java.util.List;
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 deleteBook(int id) {
return bookMapper.deleteBook(id);
}
@Override
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Books> queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
3.1.6 BookController.java
package com.dz.controller;
import com.dz.pojo.Books;
import com.dz.service.BookService;
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 javax.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
//controller层调service层
/*@Autowired
@Qualifier("BookServiceImpl")*/
@Resource(name = "bookServiceImpl")
private BookService bookService;
//查询全部的书籍, 并且返回到一个书籍展示页面
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
//跳转到新增书籍页面
@RequestMapping("/toAddBook")
public String toAddPaper() {
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Books books) {
bookService.addBook(books);
//重定向到我们的@RequestMapping("/allBook")请求
return "redirect:/book/allBook";
}
//跳转到修改页面
@RequestMapping("/toUpdateBook")
public String toUpdatePaper(int id, Model model) {
Books book = bookService.queryBookById(id);
model.addAttribute("book",book);
return "updateBook";
}
@RequestMapping("/deleteBook/{id}")
public String deleteBook(@PathVariable int id) {
bookService.deleteBook(id);
return "redirect:/book/allBook";
}
//修改书籍
@RequestMapping("/updateBook")
public String updateBook(Books books) {
bookService.updateBook(books);
return "redirect:/book/allBook";
}
//搜索框查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName, Model model) {
List<Books> list = bookService.queryBookByName(queryBookName);
model.addAttribute("list",list);
return "allBook";
}
}
3.1.7 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>
<%--BootStrap--%>
<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">
<div class="page-header">
<h1>
<small>书籍列表------显示所有书籍</small>
</h1>
</div>
</div>
<div class="col-md-4 column">
<%--toAddBook--%>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a>
</div>
<div class="col-md-8 column">
<%--搜索框查询书籍--%>
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" style="float: right" method="post">
<div class="form-group">
<label class="sr-only" for="queryBN">Query BookName</label>
<input type="text" class="form-control" id="queryBN" name="queryBookName" placeholder="请输入要查询的书籍名称">
</div>
<button type="submit" class="btn btn-primary">查询</button>
</form>
</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>
<%--书籍从数据库中拿出来, 从这个list中遍历出来: foreach--%>
<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.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
3.1.8 addBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增书籍</title>
<%--BootStrap--%>
<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">
<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 for="bkName">书籍名称: </label>
<input type="text" class="form-control" id="bkName" name="bookName" placeholder="请填写书籍名称" required>
</div>
<div class="form-group">
<label for="bkCounts">书籍数量: </label>
<input type="text" class="form-control" id="bkCounts" name="bookCounts" placeholder="请填写书籍数量" required>
</div>
<div class="form-group">
<label for="bkDetail">书籍详情: </label>
<input type="text" class="form-control" id="bkDetail" name="detail" placeholder="请填写书籍详情" required>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="提交">
</div>
</form>
</div>
</body>
</html>
3.1.9 updateBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
<%--BootStrap--%>
<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">
<div class="page-header">
<h1>
<small>修改书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<div class="form-group">
<%--隐藏域--%>
<input type="hidden" name="bookID" value="${book.bookID}">
</div>
<div class="form-group">
<label for="bkName">书籍名称: </label>
<input type="text" class="form-control" id="bkName" name="bookName" value="${book.bookName}" required>
</div>
<div class="form-group">
<label for="bkCounts">书籍数量: </label>
<input type="text" class="form-control" id="bkCounts" name="bookCounts" value="${book.bookCounts}" required>
</div>
<div class="form-group">
<label for="bkDetail">书籍详情: </label>
<input type="text" class="form-control" id="bkDetail" name="detail" value="${book.detail}" required>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="提交">
</div>
</form>
</div>
</body>
</html>