SpringMVC:整合SSM
要求:需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单的前端知识
一、数据库环境
创建一个存放书籍数据的数据库表
create database `ssmbuild`;
use `ssmbuild`;
create table `book`(
`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 `book`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
二、基本环境搭建
1、导入依赖
<!--依赖:junit,数据库驱动,链接池,servlet,jsp,mybatis,mybatis-spring,spring-->
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</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/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</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-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
2、静态资源导出问题
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
3、在IDEA中连接数据库
4、建包
pojo、dao(mapper)、service、controller
5、resource文件
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核心配置文件)
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
database.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
6、实体类pojo
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
三、Mybatis层
1、dao
- BookMapper
public interface BookMapper {
//增加一本书
int addBook(Book book);
//删除一本书
int deleteBookById(@Param("bookId") int id);
//更新一本书
int updateBook(Book book);
//查询一本书
Book queryBookById(@Param("bookId") int id);
//查询全部书
List<Book> queryAllBook();
}
- 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.aurora.dao.BookMapper">
<insert id="addBook" parameterType="Book">
insert into ssmbuild.book(bookName,bookCounts,detail)values (#{bookName},#{bookCounts},#{detail})
</insert>
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.book where bookID=#{bookId}
</delete>
<update id="updateBook" parameterType="Book">
update ssmbuild.book set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID}
</update>
<select id="queryBookById" resultType="Book">
select * from ssmbuild.book where bookID=#{bookId}
</select>
<select id="queryAllBook" resultType="Book">
select * from ssmbuild.book
</select>
</mapper>
- 在mybatis-config.xml中注册
<mappers>
<mapper class="com.aurora.dao.BookMapper"/>
</mappers>
2、service
- BookService
public interface BookService {
//增加一本书
int addBook(Book book);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Book book);
//查询一本书
Book queryBookById(int id);
//查询全部书
List<Book> queryAllBook();
}
- BookServiceImpl
public class BookServiceImpl implements BookService{
//业务层调dao层,组合dao
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Book book) {
return bookMapper.addBook(book);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
public int updateBook(Book book) {
return bookMapper.updateBook(book);
}
@Override
public Book queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Book> queryAllBook() {
return bookMapper.queryAllBook();
}
}
四、Spring层
1、整合dao
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
https://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:database.properties"/>
<!--2、连接池:
dbcp:半自动化操作,不能自动连接\
c3p0:自动化操作(自动化加载配置文件,并且可以自动设置到对象中)\
druid\
hikari-->
<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}"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定Mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--通过反射,配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的dao包-->
<property name="basePackage" value="com.aurora.dao"/>
</bean>
</beans>
2、整合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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1、扫描service下的包-->
<context:component-scan base-package="com.aurora.service"/>
<!--2、将我们所有业务类注入到Spring,可以通过配置或者注解实现(@Service、@Autowired)-->
<bean id="BookServiceImpl" class="com.aurora.service.BookServiceImpl">
<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>
五、SpringMVC层
1、增加web支持
2、在web.xml中添加
<!--DispatchServlet-->
<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:spring-mvc.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>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Session-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
3、配置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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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、扫描包:controller-->
<context:component-scan base-package="com.aurora.controller"/>
<!--4、视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
六、添加查询书籍功能
1、controller层
@Controller
@RequestMapping("/book")
public class BookController {
//controller调service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部书籍,并且返回到一个书籍展示页面
@RequestMapping("/allBook")
public String list(Model model){
List<Book> list = bookService.queryAllBook();
model.addAttribute("list",list);
return "allBook";
}
}
2、添加查询页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍展示</title>
</head>
<body>
<h1>书籍展示</h1>
<h2>${list}</h2>
</body>
</html>
问题:
- 没有给lib下添加依赖包,导致浏览器打不开
- web.xml中绑定配置文件出了问题
3、美化界面
- 首页
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
a{
text-decoration: none;
color: black;
font-size: 18px;
}
h3{
width: 180px;
height: 30px;
margin: 100px auto;
text-align: center;
line-height: 30px;
background: aqua;
border-radius: 5px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
</h3>
</body>
</html>
- 书籍展示页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍展示</title>
<%--BootSrap美化界面--%>
<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>
<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>
<%--书籍从数据库中查询出来,从这个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>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
问题:如果显示不出书籍在lib中添加jstl支持
七、添加书籍功能
1、跳转新增书籍页面
<div class="row">
<div class="col-md-4 colum">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddPaper">新增书籍</a>
</div>
</div>
2、在控制层响应跳转页面
//跳转到增加书籍页面
@RequestMapping("/toAddPaper")
public String toAddPaper(){
return "addBook";
}
3、新建跳转页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<%--BootSrap美化界面--%>
<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>书籍名称:</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="添加" required>
</div>
</form>
</div>
</body>
</html>
4、在控制层添加书籍新增请求
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Book book){
System.out.println("addBook"+book);
bookService.addBook(book);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping
}
八、更新书籍功能
1、添加修改界面
<c:forEach var="book" items="${requestScope.get('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/toUpdatePaper?id=${book.bookID}">修改</a>
|
<a href="">删除</a>
</td>
</tr>
</c:forEach>
2、controller层跳转页面
//跳转到修改页面
@RequestMapping("/toUpdatePaper")
public String toUpdatePaper(int id,Model model){
Book book = bookService.queryBookById(id);
model.addAttribute("Qbook",book);
return "updateBook";
}
3、添加更新页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
<%--BootSrap美化界面--%>
<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">
<input type="hidden" name="bookID" class="form-control" value="${Qbook.bookID}">
<div class="form-group">
<label>书籍名称:</label>
<input type="text" name="bookName" class="form-control" value="${Qbook.bookName}" required>
</div>
<div class="form-group">
<label>书籍数量:</label>
<input type="text" name="bookCounts" class="form-control" value="${Qbook.bookCounts}" required>
</div>
<div class="form-group">
<label>书籍描述:</label>
<input type="text" name="detail" class="form-control" value="${Qbook.detail}" required>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="修改" required>
</div>
</form>
</div>
</body>
</html>
4、在controller层添加修改请求
//修改书籍
@RequestMapping("/updateBook")
public String updateBook(Book book){
System.out.println("updateBook=="+book);
bookService.updateBook(book);
return "redirect:/book/allBook";
}
九、删除书籍功能
1、添加删除页面
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
基于RESTFUL是一种网络应用程序的设计风格和开发方式
2、在controller层添加删除请求
//删除书籍
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
十、根据书名查询书籍功能
1、添加查询页面
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>书籍列表————显示所有书籍</small>
</h1>
</div>
</div>
<div class="row">
<div class="col-md-4 colum">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddPaper">新增书籍</a>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a>
</div>
<div class="col-md-8 colum">
<%--查询书籍--%>
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
<span style="color: red;font-weight: bold">${error}</span>
<input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的书籍名称">
<input type="submit" value="查询" class="btn btn-primary">
</form>
</div>
</div>
</div>
2、在dao层添加查询方法
//根据书名查询书籍
Book queryBookByName(@Param("bookName") String bookName);
3、在mapper中添加查询SQL
<select id="queryBookByName" resultType="Book">
select * from ssmbuild.book where bookName=#{bookName}
</select>
4、在service层添加查询方法及实现类
//根据书名查询书籍
Book queryBookByName(String bookName);
@Override
public Book queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
5、在控制层添加请求
//查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
Book book = bookService.queryBookByName(queryBookName);
List<Book> list = new ArrayList<>();
list.add(book);
if (book==null){
list=bookService.queryAllBook();
model.addAttribute("error","未查到");
}
model.addAttribute("list",list);
return "allBook";
}