如何在 Spring Boot 中使用 WebMvc

news/2024/10/17 21:09:10/

如何在 Spring Boot 中使用 WebMvc

引言

Spring Boot 是一个快速、简单的开发框架,可以帮助我们快速地搭建一个基于 Spring 的 Web 应用程序。在 Spring Boot 中,我们可以使用 WebMvc 来构建 Web 应用程序。WebMvc 是 Spring 框架中的一个模块,它提供了 MVC 模式的支持,包括控制器、视图解析器、拦截器等功能。在本文中,我们将介绍如何在 Spring Boot 中使用 WebMvc。

在这里插入图片描述

创建 Spring Boot Web 应用程序

首先,我们需要创建一个 Spring Boot Web 应用程序。可以使用 Spring Initializr 来快速创建一个 Spring Boot 项目。在创建项目时,选择 Web 依赖,如下图所示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b4qGdlb6-1687746462750)(null)]

创建项目后,我们可以在 pom.xml 文件中看到 Spring Boot 的 Web 依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

创建控制器

在 Spring Boot 中,我们可以使用 @Controller 注解来创建控制器。控制器是处理请求和响应的核心组件。以下是一个简单的控制器:

@Controller
public class HelloController {@RequestMapping("/hello")@ResponseBodypublic String hello() {return "Hello, world!";}
}

在上面的代码中,我们使用 @Controller 注解来标识这个类是一个控制器。使用 @RequestMapping 注解来指定处理的请求路径和请求方法。使用 @ResponseBody 注解来指定返回的内容类型。

视图解析器

在 Spring Boot 中,我们可以使用视图解析器来解析视图。视图解析器将逻辑视图名称解析为实际视图的 URL。Spring Boot 默认使用 Thymeleaf 作为视图解析器。以下是一个简单的 Thymeleaf 模板:

<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Example</title>
</head>
<body><h1 th:text="${message}"></h1>
</body>
</html>

在上面的代码中,我们使用 Thymeleaf 的语法来设置视图内容。使用 th:text 属性来设置文本内容。在控制器中,我们可以使用 ModelAndView 来设置模型数据和视图名称:

@Controller
public class HelloController {@RequestMapping("/hello")public ModelAndView hello() {ModelAndView modelAndView = new ModelAndView("hello");modelAndView.addObject("message", "Hello, world!");return modelAndView;}
}

在上面的代码中,我们使用 ModelAndView 来设置模型数据和视图名称。视图名称是 “hello”,对应了上面的 Thymeleaf 模板。

拦截器

在 Spring Boot 中,我们可以使用拦截器来拦截请求并进行处理。拦截器可以用于实现日志记录、安全认证、性能监控等功能。以下是一个简单的拦截器:

@Component
public class LoggerInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("Request URL: " + request.getRequestURL());return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("Response Status: " + response.getStatus());}
}

在上面的代码中,我们创建了一个 LoggerInterceptor 类,并实现了 HandlerInterceptor 接口。在 preHandle 方法中,我们打印了请求的 URL。在 postHandle 方法中,我们打印了响应的状态码。

在 Spring Boot 中,我们需要将拦截器注册到 WebMvcConfigurer 中:

@Configuration
public class WebConfig implements WebMvcConfigurer {@Autowiredprivate LoggerInterceptor loggerInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loggerInterceptor);}
}

在上面的代码中,我们创建了一个 WebConfig 类,并实现了 WebMvcConfigurer 接口。在 addInterceptors 方法中,我们将 LoggerInterceptor 注册到了拦截器列表中。

总结

在本文中,我们介绍了如何在 Spring Boot 中使用 WebMvc。我们创建了一个控制器来处理请求和响应,使用了视图解析器来解析视图,使用了拦截器来拦截请求并进行处理。Spring Boot 的 WebMvc 模块为我们提供了方便的 MVC 模式的支持,使得我们可以快速地构建 Web 应用程序。


http://www.ppmy.cn/news/581922.html

相关文章

datetime日,周,月,季

import datatime date datetime.datetime.now() 当天&#xff1a; newdate datetime.datetime.now() condtions {datadate: newdate} 昨天&#xff1a; newdate date datetime.timedelta(days-1) condtions {datadate: newdate} 本周初&#xff1a; newdate now - …

【Java】JVM(五)

垃圾回收机制 判断对象的存活 在堆里面存放着几乎所有的对象实例&#xff0c;垃圾回收器在对对进行回收前&#xff0c;要做的事情就是确定这些对象中哪些还是“存活”着&#xff0c;哪些已经“死去”&#xff08;死去代表着不可能再被任何途径使用得对象了&#xff09; 可达…

前端开发常用命令npm\git

1、查看npm源 npm config get registry 2、设置npm源 npm config set registryhttps://registry.taobao.npm.org/ 3、清除缓存 npm cache clean --fore npm clean varify

移动开发十年

内容简介 2017&#xff0c;顶着刘海的 iPhone X 带着“史上升级变动最大”的 iOS 11&#xff0c;依然碎片化严重的 Android 带着“更快、更强大、更安全” 的8.0来到我们面前。回首过去十年&#xff0c;从诺记的 Symbian、摩托罗拉的 Linux、苹果的 iOS、微软的 Windows Phone…

Motorola、Intel CAN 解析【结构体位域法】

Motorola、Intel CAN 解析【结构体位域法】 嵌入式软件开发中大多都与CAN打交道&#xff0c;但是不同项目CAN协议以及格式均会有一定的差异&#xff0c;软件如何处理才会更加便捷&#xff0c;更加模块化呢&#xff1f;本文主要是小端格式CAN软件解析 “负负得正&#xff0c;将…

S19文件解析实现代码

介绍&#xff1a; 为了在不同的计算机平台之间传输程序代码和数据&#xff0c;摩托罗拉将程序和数据文件以一种可打印的格式(ASCII格式)编码成s格式文件。s格式文件是Freescale推荐使用的标准文件传送格式。编译完成之后&#xff0c;Freescale CodeWarrior编译器将在bin文件夹…

Motorola和Intel格式报文解析的区别

结论&#xff1a;无论用的Motorola&#xff0c;还是Intel格式&#xff0c;只在单个信号跨字节时解析才有区别。 先看下Vector的CANoe中dbc编辑器是如何呈现报文的&#xff1a; 图1 CAN报文中byte与bit顺序 从图中可以看出&#xff0c;每行表示一个字节的8个位&#xff0c;从右…

matlab的dbc解析,解析.DBC文件, 读懂CAN通信矩阵,实现车内信号仿真

通常我们拿到某个ECU的通信矩阵数据库文件,.dbc后缀名的文件。 直接使用CANdb++ Editor打开,可以很直观的读懂信号矩阵的信息,例如下图: 现在要把上图呈现的信号从.dbc文件中解析出来,供实现自动化仿真总线信号使用,比如使用python+支持can收发的硬件即可替代canoe实现信…