Spring MVC 是构建在 Servlet API 上的原生框架,并从一开始就包含在 Spring 框架中。本文主要通过简述 Spring MVC 的架构及分析,并用 Spring Boot + Spring MVC + MyBatis (SSM)+ Thymeleaf(模板引擎) 框架来简单快速构建一个 Web 项目。
MVC 三层架构如图所示,红色字体代表核心模块。其中 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 响应用户。
本段我们主要通过构建项目,实现一个分页查询。
项目结构如图所示:
<?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>
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; @Configuration public 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); } }
#thymeleaf spring.thymeleaf.cache=false #datasource spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=true spring.datasource.username=root spring.datasource.password=root #mybatis mybatis.mapper-locations=classpath:/mapper/*.xml #logging logging.path=/user/local/log logging.level.cn.zwqh=debug logging.level.org.springframework.web=info logging.level.org.mybatis=error
@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; } }
UserService
public interface UserService { PageInfo<UserEntity> getUserList(int pageNum, int pageSize); }
UserServiceImpl
@Service public 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; } }
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); } }
<?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>
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; } }
<!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
如果文章对您有帮助,请扫码关注下我的公众号,文章持续更新中...