LoginSignup
3
0

More than 1 year has passed since last update.

SpringBootを使ってBootstrapのモーダルウィンドウを表示してみる

Last updated at Posted at 2023-06-23

今回は、Java製フレームワーク「Spring Boot」を使ってフォーム画面から文字を入力して、サーバ側で処理した結果を
CSSフレームワーク「Bootstrap」を使って表示してみようと思います。

【参考にしたサイト】
ITSakura様
SpringBoot JQuery Ajaxでフォームの値を送受信する
URL:https://itsakura.com/sb-jquery-ajax

使用する環境

OS:Windows11
Javaフレームワーク:Spring Boot
CSSフレームワーク:Bootstrap

完成イメージ図

URLバーにアドレス(http://localhost:8080/test1/) を入力してクライアント画面を表示します。
名前とローマ字をそれぞれ入力して送信ボタンをクリックすると、POSTされたデータをサーバ側のControllerで値を受け取り、データ加工処理を行います。
■[名前]さん
■[ローマ字]さん

2.png

データ処理加工後の結果をモーダルウィンドウとして入力結果が表示される仕組みを作っていこうと思います。

3.png

ディレクトリ構造

1.png

SpringAjaxSample\src\main\resources\templates\test1\Index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="utf-8" />
    <title>check</title>
    <!--/*共通フレームワーク Bootstrap*/-->
    <link rel="stylesheet" th:href="@{/lib/css/bootstrap.min.css}">
    <script type="text/javascript" th:src="@{/lib/js/jquery-3.7.0.min.js}"></script>
    <script type="text/javascript" th:src="@{/lib/js/popper.js}"></script>
    <script type="text/javascript" th:src="@{/lib/js/bootstrap.min.js}"></script>
    <!--/*個別ファイル*/-->
    <script type="text/javascript" th:src="@{/js/index.js}"></script>
  </head>
  <body>
  	<div class="container">
  		<div class="row">
		    <form method="post">
		      <p><input type="text" name="name" placeholder="名前を入力してください"/></p>
		      <p><input type="text" name="romaji" placeholder="ローマ字を入力してください"/></p>
		      <p><input type="button" id="button1" value="送信"/></p>
		    </form>
	    </div>
    </div>
    <!--/*Bootstrapのモーダルウィンドウ*/-->
    <div class="modal fade" tabindex="-1" id="successMsg" aria-hidden="true">
	  <div class="modal-dialog">
	    <div class="modal-content">
	      <div class="modal-header">
	        <h5 class="modal-title">完了メッセージ</h5>
	        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
	      </div>
	      <div class="modal-body">

	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">OK</button>
	      </div>
	    </div>
	  </div>
	</div>
  </body>
</html>

画面から入力されたデータをAjax通信してControllerから返却されたデータをモーダルウィンドウに表示する処理を
コードしていきます。

SpringAjaxSample\src\main\resources\static\js\index.js
$(document).ready(function(){
	inputDataSend();
});

function inputDataSend(){
	$("#button1").click(function () {
          $.ajax({
            url: "/test1/check",
            type: "POST",
            data: $("form").serialize(),
            dataType: "json",
            timespan: 1000,
          })
            .done(function (data1, textStatus, jqXHR) {
              console.log(jqXHR.status); // 200
              console.log(textStatus); // 成功した時のコンソールログ
              console.log(data1["memo"]); // 登録しました
              console.log(data1["name"]); // name さん
              console.log(data1["romaji"]); // romaji san
              
              $(".modal-body").find("p").remove();//モダールウィンドウの表示前に<p>タグを削除する
              $(".modal-body").append("<p>"+data1["name"]+"</p>");//<p>タグの追加。
              $(".modal-body").append("<p>"+data1["romaji"]+"</p>");//<p>タグの追加
              $("#successMsg").modal('show');//もダルウィンドウを表示する
            })
            .fail(function (jqXHR, textStatus, errorThrown) {
              console.log(jqXHR.status); //例:404
              console.log(textStatus); //例:error
              console.log(errorThrown); //例:NOT FOUND
            })
            .always(function () {
              console.log("complete"); // complete
            });
     });
}

画面から入力されたデータはControllerクラスのdisp2メソッドに値が渡されて、値を加工してEntityクラスのsyainFormに格納されます。

SpringAjaxSample\src\main\java\com\example\demo\Main.java
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value="/test1")
public class Main {
	@GetMapping("/")
	public String disp1() {
		return "test1/index";
	}
	
	@PostMapping("/check")
	@ResponseBody
	public SyainForm disp2(SyainForm syainForm) {
		syainForm.setMemo("登録しました");
		syainForm.setName(syainForm.getName() + " さん");
		syainForm.setRomaji(syainForm.getRomaji() + " san");
		return syainForm;
	}
}

SpringAjaxSample\src\main\java\com\example\demo\SpringAjaxSampleApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringAjaxSampleApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringAjaxSampleApplication.class, args);
	}

}

SpringAjaxSample\src\main\java\com\example\demo\SyainForm.java
package com.example.demo;

import lombok.Data;

@Data
public class SyainForm {
	private String memo;
	
	private String name;
	
	private String romaji;
}

3
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
3
0