首頁 web前端 js教程 在 Spring Boot 中使用 HTTP 請求

在 Spring Boot 中使用 HTTP 請求

Oct 06, 2024 pm 10:37 PM

Working with HTTP requests in Spring Boot

Hello world!
The main goal of this article is to help beginner developers handle HTTP requests in Spring Boot.

?In the examples I do not cover all the code required for the MVC app, just some parts to demonstrate the difference in data processing.

Recently, I’ve been working on an engineering project with other students in my class. It introduced us to a new technology stack, as we were required to build upon an “old” codebase. The codebase included Java, Spring Boot, and Thymeleaf. The project's aim was to create a clone of a popular social network.
The core functionality was fairly typical: users can create posts, and others can comment on or like those posts.
To add some visual dynamism, we decided to combine Thymeleaf with JavaScript. This way, when a post is displayed on the page, users can click to like or comment, and the changes will be processed in the back end. At this point, we needed a JavaScript function to send requests to the server for all the standard CRUD operations.
The question was: how do we properly pass data to the server using POST, PUT, or DELETE methods? GET is more or less clear, so I skip examples with GET.
Here are the possible ways.

URL Parameters (PathVariable)

URL Example: HTTP://myapp.com/posts/1

Suitable for: DELETE, PUT

Cases: You work with a specific entity on a back end - a single post in my examples.

Annotation Example:


@DeleteMapping("/posts/{post_id}")
public ResponseEntity<String> deletePost(@PathVariable("post_id") Long post_id) {
        // Some logic here...
        return ResponseEntity.ok("Deleted successfully");
    }


Example of a corresponding JS code:


 // 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...
}


Form data (RequestParam)

URL Example: HTTP://myapp.com/posts or HTTP://myapp.com/posts/1 for editing

Suitable for: PUT, POST

Cases: You are creating or updating an entity with one or two parameters. In my example, it’s a post content (a text message).

Annotation Example:


@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");
    }


Example of a corresponding JS code:


// 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 Body (RequestBody)

Suitable for: PUT, POST

Cases: You are creating or updating a complex entity (e.g. object with 3 or more parameters).

Annotation Example:


@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");
    }


Example of a corresponding JS code:


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...
}


This is it. Hope it will be helpful.
Cheers!

以上是在 Spring Boot 中使用 HTTP 請求的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

JavaScript實現點擊圖片切換效果:專業教程 JavaScript實現點擊圖片切換效果:專業教程 Sep 18, 2025 pm 01:03 PM

本文將介紹如何使用JavaScript實現點擊圖片切換的效果。核心思路是利用HTML5的data-*屬性存儲備用圖片路徑,並通過JavaScript監聽點擊事件,動態切換src屬性,從而實現圖片切換。本文將提供詳細的代碼示例和解釋,幫助你理解和掌握這種常用的交互效果。

如何使用JavaScript中的GeOlocation API獲取用戶的位置? 如何使用JavaScript中的GeOlocation API獲取用戶的位置? Sep 21, 2025 am 06:19 AM

首先檢查瀏覽器是否支持GeolocationAPI,若支持則調用getCurrentPosition()獲取用戶當前位置坐標,並通過成功回調獲取緯度和經度值,同時提供錯誤回調處理權限被拒、位置不可用或超時等異常,還可傳入配置選項以啟用高精度、設置超時時間和緩存有效期,整個過程需用戶授權並做好相應錯誤處理。

JavaScript中DOM元素訪問的常見陷阱與解決方案 JavaScript中DOM元素訪問的常見陷阱與解決方案 Sep 15, 2025 pm 01:24 PM

本文旨在解決JavaScript中通過document.getElementById()獲取DOM元素時返回null的問題。核心在於理解腳本執行時機與DOM解析狀態。通過正確放置標籤或利用DOMContentLoaded事件,可以確保在元素可用時再嘗試訪問,從而有效避免此類錯誤。

NUXT 3組成API解釋了 NUXT 3組成API解釋了 Sep 20, 2025 am 03:00 AM

Nuxt3的CompositionAPI核心用法包括:1.definePageMeta用於定義頁面元信息,如標題、佈局和中間件,需在中直接調用,不可置於條件語句中;2.useHead用於管理頁面頭部標籤,支持靜態和響應式更新,需與definePageMeta配合實現SEO優化;3.useAsyncData用於安全地獲取異步數據,自動處理loading和error狀態,支持服務端和客戶端數據獲取控制;4.useFetch是useAsyncData與$fetch的封裝,自動推斷請求key,避免重複請

如何在JavaScript中使用setInterval創建重複間隔 如何在JavaScript中使用setInterval創建重複間隔 Sep 21, 2025 am 05:31 AM

要創建JavaScript中的重複間隔,需使用setInterval()函數,它會以指定毫秒數為間隔重複執行函數或代碼塊,例如setInterval(()=>{console.log("每2秒執行一次");},2000)會每隔2秒輸出一次消息,直到通過clearInterval(intervalId)清除,實際應用中可用於更新時鐘、輪詢服務器等場景,但需注意最小延遲限制、函數執行時間影響,並在不再需要時及時清除間隔以避免內存洩漏,特別是在組件卸載或頁面關閉前應清理,確保

如何在JavaScript中創建多行字符串? 如何在JavaScript中創建多行字符串? Sep 20, 2025 am 06:11 AM

thebestatoreateamulti-linestlinginjavascriptsisisingsistisingtemplatalalswithbacktticks,whatpreserveticks,whatpreservereakeandeexactlyaswrite。

JavaScript中數字格式化:使用toFixed()方法保留固定小數位 JavaScript中數字格式化:使用toFixed()方法保留固定小數位 Sep 16, 2025 am 11:57 AM

本教程詳細講解如何在JavaScript中將數字格式化為固定兩位小數的字符串,即使是整數也能顯示為"#.00"的形式。我們將重點介紹Number.prototype.toFixed()方法的使用,包括其語法、功能、示例代碼以及需要注意的關鍵點,如其返回類型始終為字符串。

如何將文本複製到JavaScript中的剪貼板? 如何將文本複製到JavaScript中的剪貼板? Sep 18, 2025 am 03:50 AM

使用ClipboardAPI的writeText方法可複製文本到剪貼板,需在安全上下文和用戶交互中調用,支持現代瀏覽器,舊版可用execCommand降級處理。

See all articles