首页  >  文章  >  web前端  >  在 Spring Boot 中使用 HTTP 请求

在 Spring Boot 中使用 HTTP 请求

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-06 22:37:02266浏览

Working with HTTP requests in Spring Boot

世界你好!
本文的主要目标是帮助初学者在 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");
    }


对应的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");
    }


对应的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");
    }


对应的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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn