0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

同期通信と非同期通信について、Springベースで整理する

0
Posted at

今までの実務では雰囲気で同期/非同期を実装していましたが、細かい書き方の違いが曖昧だったので、実装例を交えて違いをアウトプットします。

・同期通信...自動で画面遷移を行う。処理が終わるまで操作ができない。
・非同期通信...必要な部分だけ表示を更新する。画面遷移せず、裏で通信を行う。
:point_right: 同期通信はブラウザが、非同期通信はJSがレスポンスを解釈します。

■同期通信

画面遷移をするときはControllerを使います。
スクリーンショット 2026-01-10 164943.png

実装例① form+submit+POSTでリクエストを送る

home画面でMY PAGEボタンを押下し、mypage画面に遷移するサンプルです。

home.html
<form action="/mypage" method="post">
    <input name="loginUserName">
    <button type="submit">MY PAGE</button>
</form>
SampleController.java
@Controller
public class SampleController {
    @PostMapping("/mypage")
    public ModelAndView hello(@RequestParam String loginUserName) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("loginUserName", loginUserName);
        mav.setViewName("mypage");
        return mav;
    }
}
mypage.html
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
    <head>
        // 省略
    </head>
    <body>
        <div id="app">
            <h1>MYPAGE</h1>
            <p>ようこそ{{ name }}さん</p>
        </div>
    </body>
</html>
<script th:inline="javascript">
    new Vue({
        el: '#app',
        data: {
            name : /*[[${ userName }]]*/  名前,
        }
    })
</script>

実装例② href+GETでリクエストを送る

おしらせ画面で詳細リンクを押下し、おしらせ詳細画面に遷移するサンプルです。

notice.html
        <div id="app">
            <h1>おしらせ</h1>
            <a href="/notice/detail?id=1" target="_blank">詳細</a>
        </div>
NoticeController.java
@Controller
public class NoticeController {
    @GetMapping("/notice/detail")
    public String detail(@RequestParam int id) {
        return "noticeDetail";
    }
}
noticeDetail.html
        <div id="app">
            <h1>おしらせ詳細</h1>
            <p>おしらせ詳細画面です。</p>
        </div>

■非同期通信

データを取得するときはRestControllerを使います。
スクリーンショット 2026-01-10 165038.png

前述のRestController、後述のAjaxについては詳細を後日まとめる予定です:writing_hand_tone2:

実装例 Ajax+POSTでリクエストを送る

入力フォームに値を入力し判定ボタン押下時、サービスクラスのcheckメソッドの判定結果を返却し、判定結果欄に表示する処理のサンプルです。
※サービスクラスは省略

home.html
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
    <head>
        // 省略
    </head>
    <body>
        <div id="app">
            <h1>CHECK SAMPLE</h1>
            <input type="text" id="keyword">
            <p>判定結果:{{ checkResult }}</p>
            <button @click="execCheck">判定</button>
        </div>
    </body>
</html>
<script th:inline="javascript">
    new Vue({
        el: '#app',
        data: {
            checkResult : '',
            keyword : '',
        },
        methods: {
            execCheck() {
                var url = "/check"
                axios.post(url, {
                    keyword: document.getElementById("keyword").value
                })
                .then(
                    response => {
                        if (response.data.errorMessage) {
                            this.message = response.data.errorMessage;
                        }
                        this.checkResult = response.data;
                    }
                )
                .catch(error => {
                    // エラー
                })
            },
        }
    })
</script>
SampleRestController.java
@RestController   
public class SampleRestController {
    private final CheckService checkService;

    public SampleRestController(CheckService checkService) {
        this.checkService = checkService;
    }

    @PostMapping("/check")
    public String check(@RequestBody String keyword) {
        String result = checkService.check(keyword); // 判定処理呼び出し
        return result;
    }
}

さいごに

フリーアイコンはこちらのサイト様からお借りしました:bow_tone1:
https://sato-icons.com/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?