世界你好!
本文的主要目标是帮助初学者在 Spring Boot 中处理 HTTP 请求。
?在示例中,我没有涵盖 MVC 应用程序所需的所有代码,仅介绍一些部分来演示数据处理方面的差异。
最近,我一直在和班上的其他学生一起做一个工程项目。它向我们介绍了一个新的技术堆栈,因为我们需要在“旧”代码库的基础上构建。代码库包括 Java、Spring Boot 和 Thymeleaf。该项目的目标是创建一个流行社交网络的克隆。
核心功能相当典型:用户可以创建帖子,其他人可以评论或喜欢这些帖子。
为了添加一些视觉活力,我们决定将 Thymeleaf 与 JavaScript 结合起来。这样,当页面上显示帖子时,用户可以点击点赞或评论,更改将在后端处理。此时,我们需要一个 JavaScript 函数来向服务器发送所有标准 CRUD 操作的请求。
问题是:我们如何使用 POST、PUT 或 DELETE 方法正确地将数据传递到服务器? GET 或多或少是清楚的,所以我跳过了 GET 的示例。
以下是可能的方法。
URL 参数(PathVariable)
网址示例: HTTP://myapp.com/posts/1
适用于:删除、放置
案例:您在后端与特定实体合作 - 我的示例中的单个帖子。
注释示例:
@DeleteMapping("/posts/{post_id}") public ResponseEntity<string> deletePost(@PathVariable("post_id") Long post_id) { // Some logic here... return ResponseEntity.ok("Deleted successfully"); } </string>
对应的JS代码示例:
// Some pre-logic here to pass postId to the function, // or you can use const deletePost = async(postId)=>{} to pass postId directly const deletePost = async () => { // Some pre-checks and error handling go here... const requestOption = { method:'DELETE', headers:{ 'Content-type':'application/json' } }; await fetch(`/posts/${postId}`, requestOptions); // Some post-checks and error handling go here... }
表单数据(RequestParam)
URL 示例: HTTP://myapp.com/posts 或 HTTP://myapp.com/posts/1 用于编辑
适合: PUT、POST
案例:您正在创建或更新具有一两个参数的实体。在我的示例中,它是帖子内容(短信)。
注释示例:
@PutMapping("/posts/{post_id}") public ResponseEntity<string> editPost(@PathVariable("post_id") Long post_id, @RequestParam("content") String content) { // Some logic goes here... return ResponseEntity.ok("Post updated successfully"); } </string>
对应的JS代码示例:
// Some pre-logic here to pass postId and content to the function, // or you can use const deletePost = async(postId, updatedContent)=>{} to pass // them directly directly const updatePost = async ()=> { // Some pre-checks and error handling go here... const formData = new FormData(); formData.append("content",updatedContent); requestOptions = { method:'PUT', body: formData }; await fetch(`/posts/${postId}`,requestOptions); // Some post-checks and error handling go here... }
JSON 正文 (RequestBody)
适合: PUT、POST
案例:您正在创建或更新一个复杂的实体(例如具有 3 个或更多参数的对象)。
注释示例:
@PutMapping("/posts/{post_id}") public ResponseEntity<string> editPost(@PathVariable("post_id") Long post_id, @RequestBody Post post) { // Some logic goes here... // It requires the whole object to be passed. // After that it's possible to access values via getters of your object's model return ResponseEntity.ok("Post updated successfully"); } </string>
对应的JS代码示例:
const updatePost = async ()=> { // Some pre-checks and error handling go here... requestOptions = { method:'PUT', headers: { 'Content-type':'application/json' }, body: JSON.stringify({'content':updatedContent}) }; await fetch(`/posts/${postId}`,requestOptions); // Some post-checks and error handling go here... }
就是这样。希望对您有帮助。
干杯!
以上是在 Spring Boot 中使用 HTTP 请求的详细内容。更多信息请关注PHP中文网其他相关文章!

javaandjavascriptaredistinctlanguages:javaisusedforenterpriseandmobileapps,while javascriptifforInteractiveWebpages.1)JavaisComcompoppored,statieldinglationallyTypted,statilly tater astrunsonjvm.2)

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3汉化版
中文版,非常好用

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)