前言
Spring MVC 是构建在 Servlet API 上的原生框架,并从一开始就包含在 Spring 框架中。本文主要通过简述 Spring MVC 的架构及分析,并用 Spring Boot + Spring MVC + MyBatis (SSM)+ Thymeleaf(模板引擎) 框架来简单快速构建一个 Web 项目。
Web MVC 架构及分析
MVC 三层架构如图所示,红色字体代表核心模块。其中 MVC 各分层分别为:
- Model (模型层)处理核心业务(数据)逻辑,模型对象负责在数据库中存取数据。这里的“数据”不仅限于数据本身,还包括处理数据的逻辑。
- View(视图层)用于展示数据,通常数据依据模型数据创建。
- Controller(控制器层)用于处理用户输入请求和响应输出,从试图读取数据,控制用户输入,并向模型发送数据。Controller 是在 Model 和 View 之间双向传递数据的中间协调者。
Spring MVC 架构及分析
Spring MVC 处理一个 HTTP 请求的流程,如图所示:
整个过程详细介绍:
1.用户发送请求至前端控制器 DispatcherServlet。
2.DispatcherServlet 收到请求调用处理器映射器 HandlerMapping。
3.处理器映射器根据请求 URL 找到具体的 Controller 处理器返回给 DispatcherServlet。
4.DispatcherServlet 通过处理器适配器 HandlerAdapter 调用 Controller 处理请求。
5.执行 Controller 处理器的方法。
6.Controller 执行完成返回 ModelAndView。
7.HandlerAdapter 将 Controller 执行结果 ModelAndView 返回给 DispatcherServlet。
8.DispatcherServlet 将 ModelAndView 的 ViewName 传给视图解析器 ViewReslover。
9.ViewReslover 解析后返回具体的视图 View。
10.DispatcherServlet 传递 Model 数据给 View,对 View 进行渲染(即将模型数据填充至视图中)。
11-12.DispatcherServlet 响应用户。
Spring Boot + Spring MVC + MyBatis + Thymeleaf
本段我们主要通过构建项目,实现一个分页查询。
1.项目构建
项目结构如图所示:
1.1 pom 引入相关依赖
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>cn.zwqh</groupId> <artifactId>spring-boot-ssm-thymeleaf</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-ssm-thymeleaf</name> <description>spring-boot-ssm-thymeleaf</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- 热部署模块 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <!-- 这个需要为 true 热部署才有效 --> </dependency> <!-- mysql 数据库驱动. --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- mybaits --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <!-- pagehelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.12</version> </dependency> <!-- thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
1.2 WebMvcConfig 配置
package cn.zwqh.springboot.config;import org.springframework.context.annotation.Configuration;import org.springframework.core.Ordered;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;@Configurationpublic class WebMvcConfig extends WebMvcConfigurationSupport { /** * 静态资源配置 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");//静态资源路径 css,js,img等 registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");//视图 registry.addResourceHandler("/mapper/**").addResourceLocations("classpath:/mapper/");//mapper.xml super.addResourceHandlers(registry); } /** * 视图控制器配置 */ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("/index");//设置默认跳转视图为 /index registry.setOrder(Ordered.HIGHEST_PRECEDENCE); super.addViewControllers(registry); } /** * 视图解析器配置 控制controller String返回的页面 视图跳转控制 */ @Override public void configureViewResolvers(ViewResolverRegistry registry) { // registry.viewResolver(new InternalResourceViewResolver("/jsp/", ".jsp")); super.configureViewResolvers(registry); } }
1.3 application.properties 配置
#thymeleafspring.thymeleaf.cache=false#datasourcespring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=truespring.datasource.username=rootspring.datasource.password=root#mybatismybatis.mapper-locations=classpath:/mapper/*.xml#logginglogging.path=/user/local/loglogging.level.cn.zwqh=debuglogging.level.org.springframework.web=infologging.level.org.mybatis=error
1.4 Controller
@Controller@RequestMapping("/user")public class UserController { @Autowired private UserService userService; @GetMapping("/list") public ModelAndView showUserList(int pageNum, int pageSize) { PageInfo<UserEntity> pageInfo = userService.getUserList(pageNum, pageSize); ModelAndView modelAndView=new ModelAndView(); modelAndView.setViewName("index"); modelAndView.addObject("pageInfo",pageInfo); return modelAndView; }}
1.5 Service 及 ServiceImpl
UserService
public interface UserService { PageInfo<UserEntity> getUserList(int pageNum, int pageSize);}
UserServiceImpl
@Servicepublic class UserServiceImpl implements UserService{ @Autowired private UserDao userDao; @Override public PageInfo<UserEntity> getUserList(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); List<UserEntity> list=userDao.getAll(); PageInfo<UserEntity> pageData= new PageInfo<UserEntity>(list); System.out.println("当前页:"+pageData.getPageNum()); System.out.println("页面大小:"+pageData.getPageSize()); System.out.println("总数:"+pageData.getTotal()); System.out.println("总页数:"+pageData.getPages()); return pageData; }}
1.6 Dao
public interface UserDao { /** * 获取所有用户 * @return */ List<UserEntity> getAll(); }
记得在启动类里加上@MapperScan
@SpringBootApplication@MapperScan("cn.zwqh.springboot.dao")public class SpringBootSsmThymeleafApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSsmThymeleafApplication.class, args); }}
1.7 Mapper.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="cn.zwqh.springboot.dao.UserDao"> <resultMap type="cn.zwqh.springboot.model.UserEntity" id="user"> <id property="id" column="id"/> <result property="userName" column="user_name"/> <result property="userSex" column="user_sex"/> </resultMap> <!-- 获取所有用户 --> <select id="getAll" resultMap="user"> select * from t_user </select></mapper>
1.8 实体 UserEntity
public class UserEntity { private Long id; private String userName; private String userSex; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } }
1.9 html 页面
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Insert title here</title></head><body><p>Thymeleaf是一个用于Web和独立环境的现代服务器端Java模板引擎。SpringBoot推荐使用Thymeleaf。</p><p>下面是表格示例:</p><table border="1"> <thead> <tr> <th width="100">ID</th> <th width="100">姓名</th> <th width="100">性别</th> </tr> </thead> <tbody> <tr th:each="user:${pageInfo.list}"> <td th:text="${user.id}"></td> <td th:text="${user.userName}"></td> <td th:text="${user.userSex}"></td> </tr> </tbody></table><p><a th:href="${'/user/list?pageNum='+(pageInfo.pageNum-1>=1?pageInfo.pageNum-1:1)+'&pageSize=10'}">上一页</a> <a th:href="${'/user/list?pageNum='+(pageInfo.pageNum+1<=pageInfo.pages?pageInfo.pageNum+1:pageInfo.pages)+'&pageSize=10'}">下一页</a> 总数:<span th:text="${pageInfo.total}"></span></p></body></html>
测试
通过浏览器访问:http://127.0.0.1:8080/user/list?pageNum=1&pageSize=10 进行测试。效果如图:
示例代码
github
码云
非特殊说明,本文版权归 朝雾轻寒 所有,转载请注明出处.
原文标题: Spring Boot 2.X(三):使用 Spring MVC + MyBatis + Thymeleaf 开发 web 应用
原文地址: https://www.zwqh.top/article/info/2
如果文章对您有帮助,请扫码关注下我的公众号,文章持续更新中...