目录
SpringMVC执行原理
直接上图:
文字描述:
简要分析执行流程
- DispatcherServlet表示前置控制器,是整个SpringMVC的控制中心。用户发出请求,DispatcherServlet接收请求并拦截请求。
我们假设请求的url为 : http://localhost:8080/SpringMVC/hello
如上url拆分成三部分:
http://localhost:8080服务器域名
SpringMVC部署在服务器上的web站点
hello表示控制器
通过分析,如上url表示为:请求位于服务器localhost:8080上的SpringMVC站点的hello控制器。
-
HandlerMapping为处理器映射。DispatcherServlet调用HandlerMapping,HandlerMapping根据请求url查找Handler。
-
HandlerExecution表示具体的Handler,其主要作用是根据url查找控制器,如上url被查找控制器为:hello。
-
HandlerExecution将解析后的信息传递给DispatcherServlet,如解析控制器映射等。
-
HandlerAdapter表示处理器适配器,其按照特定的规则去执行Handler。
-
Handler让具体的Controller执行。
-
Controller将具体的执行信息返回给HandlerAdapter,如ModelAndView。
-
HandlerAdapter将视图逻辑名或模型传递给DispatcherServlet。
-
DispatcherServlet调用视图解析器(ViewResolver)来解析HandlerAdapter传递的逻辑视图名。
-
视图解析器将解析的逻辑视图名传给DispatcherServlet。
-
DispatcherServlet根据视图解析器解析的视图结果,调用具体的视图。
-
最终视图呈现给用户。
下面这图是MVC的架构模式:
SSM项目框架搭建
环境要求
环境:
IDEA
MySQL 5.7.19
Tomcat 9
Maven 3.6
要求:
需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单的前端知识;
数据库环境
这一步需要创建数据库,以及相关的表。
在此把基本的建库建表记录上:创建一个存放书籍数据的数据库表
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,'从进门到进牢');
基本环境搭建
新建一Maven项目,添加web的支持
右键项目名 – Add Framework Support
如下图勾选web支持 – OK
pom.xml导入依赖和资源过滤设置
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<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.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
<!-- Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
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>
建立基本结构和配置框架
Mybatis 层编写
建包、配置mybatis数据库
在src - main - java 包下新建:
- com.ma.pojo
- com.ma.dao
- com.ma.service
- com.ma.controller
在src - main - resources 包下新建
- 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>
1、 数据库配置文件 database.properties 【在src - main - resources 包下新建】
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
jdbc.username=root
jdbc.password=
2、IDEA关联数据库
3、编写mybatis的核心配置文件 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>-->
<!-- Mybatis:1.取别名 2. mapper-->
<typeAliases>
<package name="com.ma.pojo"/>
</typeAliases>
</configuration>
编写实体类、接口、接口实现类
1、编写数据库表对应的实体类com.demo.pojo.Books
注意使用lombok 插件!
package com.ma.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;
}
2、编写Dao层【Mapper层】的Mapper接口
package com.ma.dao;
import com.ma.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
//添加
int addBook(Books book);
//根据id删除一个Book
int deleteBookById(@Param("bookID") int id);
//更新Book
int UpdateBook(Books book);
//根据id查询,返回一个Book
Books queryBookById(@Param("bookID") int id);
//查询全部Book,返回List集合
List<Books> queryAllBook();
Books queryBookByName(@Param("bookName") String bookName);
}
3、编写Mapper接口对应的Mapper.xml 文件。(需要导入Mybatis包)
在这里我是将BookMapper.xml 文件是建在resources包下和src一样结构的包下的。也可以将Mapper.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.ma.dao.BookMapper">
<insert id="addBook" parameterType="books">
insert into ssmbuild.books (bookName, bookCounts, detail)
values (#{bookName}, #{bookCounts}, #{detail});
</insert>
<delete id="deleteBookById" parameterType="int">
delete
from ssmbuild.books
where bookID = #{bookID};
</delete>
<update id="UpdateBook" parameterType="Books">
update ssmbuild.books
set bookName = #{bookName}, bookCounts = #{bookCounts}, detail = #{detail}
where bookID = #{bookID};
</update>
<select id="queryBookById" resultType="Books">
select * from ssmbuild.books
where bookID = #{bookID}
</select>
<select id="queryAllBook" resultType="Books">
select * from ssmbuild.books
</select>
<select id="queryBookByName" resultType="Books">
select * from ssmbuild.books
where bookName = #{bookName}
</select>
</mapper>
写完Mapper.xml文件之后,配置Mapper.xml 一定要在mybatis-config.xml文件中注册路径,如下:
<mappers>
<!--这里可以用resource 也可以用class ,不过因为我放包的位置,所以我选用resource-->
<mapper resource="com/ma/dao/BookMapper.xml"/>
</mappers>
4、编写Service层接口
接口 :在这里单个的参数变量
package com.ma.service;
import com.ma.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookService {
//添加
int addBook(Books book);
//根据id删除一个Book
int deleteBookById(int id);
//更新Book
int UpdateBook(Books book);
//根据id查询,返回一个Book
Books queryBookById(int id);
//查询全部Book,返回List集合
List<Books> queryAllBook();
//根据名字搜索书籍
Books queryBookByName(String bookName);
}
5、编写Service层接口实现类
package com.ma.service;
import com.ma.dao.BookMapper;
import com.ma.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
//@Service
public class BookServiceImpl implements BookService{
// @Autowired
// service 调用dao层:组合Dao
private BookMapper bookMapper;
public BookServiceImpl(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books book) {
return bookMapper.addBook(book);
}
@Override
public int deleteBookById(int bookID) {
return bookMapper.deleteBookById(bookID);
}
@Override
public int UpdateBook(Books book) {
return bookMapper.UpdateBook(book);
}
@Override
public Books queryBookById(int bookID) {
return bookMapper.queryBookById(bookID);
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
@Override
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
Spring层
1、配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;
spring-dao.xml 【大多数固定】
2、我们去编写Spring整合Mybatis的相关的配置文件; 【resources包下】
<?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
http://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}"/>
<!-- 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>
<!-- 配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring 容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 要扫描的包-->
<property name="basePackage" value="com.ma.dao"/>
</bean>
</beans>
spring-service.xml 【大多数固定】
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:http="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1. 扫描service下的包相关的bean-->
<context:component-scan base-package="com.ma.service"/>
<!-- 2. 将所有的业务实现类,注入到spring中,可以通过配置 或 注解实现 :(BookServiceImpl注入到IOC容器中) -->
<bean id="BookServiceImpl" class="com.ma.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层编写
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>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 绑定配置文件 spring-mvc.xml-->
<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>DispatcherServlet</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>
<!-- 15分钟-->
<session-timeout>15</session-timeout>
</session-config>
</web-app>
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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 1. 开启SpringMVC注解驱动 -->
<mvc:annotation-driven/>
<!-- 2. 静态资源过滤 默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3. 扫描controller包-->
<context:component-scan base-package="com.ma.controller"/>
<!-- 4. 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
注意事项
配置文件一定一定要注意一点,按alt + enter 自动导入了一行,我们还要添加几行,一定要都写上才行,否则就会报错。要想下图中,两个部分都要加上,下面链接里面的我们直接复制,然后改下后面contex 或者springmvc就行
Controller 和 视图层 .jsp 编写
BookController 类编写
再次完成了部分接口的实现,详细代码可私信联系作者领取
package com.ma.controller;
import com.ma.pojo.Books;
import com.ma.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.RequestMapping;
import java.awt.print.Book;
import java.util.ArrayList;
import java.util.List;
@Controller
public class BookController {
//controller 调 service
private final BookService bookService;
public BookController(@Qualifier("BookServiceImpl") BookService bookService) {
this.bookService = bookService;
}
//查询全部的书籍,并且返回到一个书籍展示页面
@RequestMapping("/book/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
}
编写主页index.jsp
<%--
Date: 2022/3/18
Time: 21:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style type="text/css">
a {
text-decoration: none;
color: cornflowerblue;
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>
编写Controller中方法会跳转的allBook.jsp页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Date: 2022/3/19
Time: 0:08
To change this template use File | Settings | File Templates.
--%>
<%@ 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-8 column">
<a href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a>
<a href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a>
<br>
</div>
<div class="col-md-8 column">
<%--查询书籍 placeholder(搜索框内默认的字)>--%>
<form action="${pageContext.request.contextPath}/book/queryBook" method="post">
<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>
<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="${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>
</body>
</html>
其他的方法也如同上述一样先写Controller类中方法,然后编写需要的.jsp文件
配置Tomcat,进行运行测试
注意事项
1、每次实现一个方法功能时,就需要运行测试一下,要边运行测试边写码,不要写完了在测试。测试报错要好好看日志,多半是有提示的。
2、编写代码中要注意一些变量名是否一样,
- 数据库表中字段名与实体类中成员变量名是否一样,这个也可以一样,但是也要写一些附加的东西【注解或取别名】具体可以搜一下。
- 前端返回的参数名和Controller层所需要的参数的名字注意,否则测试的时候会报错找不到这个参数
3、Controller 类中方法中的跳转页面路径要记得加上斜杠 “/”,还有如果写了父路径,可以在Controller 类上 @RequestMapping添加,但是方便后期修改或维护,都尽量加在每个方法上的注解里,我在这里就是都加了 /book
项目结构图