Spring Boot での HTTP リクエストの操作

Mary-Kate Olsen
リリース: 2024-10-06 22:37:02
オリジナル
265 人が閲覧しました

Working with HTTP requests in Spring Boot

Hello world!
この記事の主な目的は、初心者の開発者が Spring Boot で HTTP リクエストを処理できるようにすることです。

?この例では、MVC アプリに必要なすべてのコードを取り上げているわけではなく、データ処理の違いを示すための一部のみを取り上げています。

最近、私はクラスの他の生徒たちとエンジニアリングプロジェクトに取り組んでいます。 「古い」コードベースに基づいて構築する必要があったため、新しいテクノロジー スタックが導入されました。コードベースには Java、Spring Boot、Thymeleaf が含まれていました。プロジェクトの目的は、人気のあるソーシャル ネットワークのクローンを作成することでした。
コア機能は非常に典型的なもので、ユーザーは投稿を作成でき、他のユーザーはそれらの投稿にコメントしたり、「いいね!」をしたりできます。
視覚的なダイナミズムを追加するために、Thymeleaf と JavaScript を組み合わせることにしました。こうすることで、ページに投稿が表示されているときに、ユーザーがクリックして「いいね」をクリックしたり、コメントしたりすることができ、変更はバックエンドで処理されます。この時点で、すべての標準 CRUD 操作のリクエストをサーバーに送信するための JavaScript 関数が必要でした。
問題は、POST、PUT、または DELETE メソッドを使用してサーバーにデータを適切に渡すにはどうすればよいかということでした。 GET は多かれ少なかれ明確なので、GET の例は省略します。
考えられる方法は次のとおりです。

URL パラメータ (PathVariable)

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

次の用途に適しています: 削除、挿入

ケース: バックエンドで特定のエンティティ (私の例では 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

ケース: 1 つまたは 2 つのパラメーターを持つエンティティを作成または更新しています。私の例では、投稿コンテンツ (テキスト メッセージ) です。

注釈の例:


@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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!