千家信息网

如何使用 Spring MVC和 Thymeleaf 开发 web 应用

发表于:2024-09-30 作者:千家信息网编辑
千家信息网最后更新 2024年09月30日,这期内容当中小编将会给大家带来有关如何使用 Spring MVC和 Thymeleaf 开发 web 应用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。Spring
千家信息网最后更新 2024年09月30日如何使用 Spring MVC和 Thymeleaf 开发 web 应用

这期内容当中小编将会给大家带来有关如何使用 Spring MVC和 Thymeleaf 开发 web 应用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。


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 引入相关依赖
        4.0.0                        org.springframework.boot                spring-boot-starter-parent                2.1.9.RELEASE                                 cn.zwqh        spring-boot-ssm-thymeleaf        0.0.1-SNAPSHOT        spring-boot-ssm-thymeleaf        spring-boot-ssm-thymeleaf                        1.8                                                        org.springframework.boot                        spring-boot-starter-web                                                        org.springframework.boot                        spring-boot-starter-test                        test                                                        org.springframework.boot                        spring-boot-starter-jdbc                                                                        org.springframework.boot                        spring-boot-devtools                        true                                                                         mysql                        mysql-connector-java                        runtime                                                                        org.mybatis.spring.boot                        mybatis-spring-boot-starter                        2.1.0                                                                        com.github.pagehelper                        pagehelper-spring-boot-starter                        1.2.12                                                                                        org.springframework.boot                        spring-boot-starter-thymeleaf                                                                                                        org.springframework.boot                                spring-boot-maven-plugin                                                
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 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 getUserList(int pageNum, int pageSize);}

UserServiceImpl

@Servicepublic class UserServiceImpl implements UserService{        @Autowired        private UserDao userDao;        @Override        public PageInfo getUserList(int pageNum, int pageSize) {                PageHelper.startPage(pageNum, pageSize);                List list=userDao.getAll();                PageInfo pageData= new PageInfo(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 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
                                                                                
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 页面
Insert title here

Thymeleaf是一个用于Web和独立环境的现代服务器端Java模板引擎。SpringBoot推荐使用Thymeleaf。

下面是表格示例:

ID 姓名 性别

上一页 下一页 总数:

上述就是小编为大家分享的如何使用 Spring MVC和 Thymeleaf 开发 web 应用了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。

0