Web系開発メモ

Java, C#, HTML, CSS, JavaScript のことなどを書いてます。

SpringBoot jQueryのAjaxでJSONを送受信する方法

Spring Boot の Webアプリで、jQuery を使って JSON を送受信する方法を書いていきます。

バージョン

動作確認で使用した製品のバージョンは以下の通りです。

1. 画面の作成

以下の HTML を作成します。

src/main/resources/static/index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>JSONの送受信</title>
</head>
  <body>
    <form>
      <p>名前:<input type="text" id="name"></p>
      <p>年齢:<input type="text" id="age"></p>
      <p><input type="button" id="send" value="送信"></p>
    </form>
    <div id="res" style="display:none; margin-top:60px;">
      <p>受信結果</p>
      <p id="res-id">ID:</p>
      <p id="res-name">名前:</p>
      <p id="res-age">年齢:</p>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.3.min.js"
      integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU="
      crossorigin="anonymous"></script>
    <script src="./main.js"></script>
  </body>
</html>

2. JavaScriptの作成

JSON の送信と受信を行う JavaScript を作成します。

src/main/resources/static/main.js

$(function() {
  $('#send').click(function() {
    var data = {
      name: $('#name').val(),
      age: $('#age').val()
    };
    $.ajax({
      url: '/customer',
      method: 'post',
      data: JSON.stringify(data),
      contentType: 'application/json', 
      dataType: "json",
      cache: false
    }).done(function(data, status, jqxhr) {
      $('#res-id').append(data.id);
      $('#res-name').append(data.name);
      $('#res-age').append(data.age);
      $('#res').css('display', 'block');
    }).fail(function(data, status, jqxhr) {
      alert('送信エラー');
    }); 
  });
});

3. コントローラーの作成

以下のコントローラーを作成します。

src/main/java/org/example/controller/CustomerController.java

package org.example.controller;

import org.example.model.Customer;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CustomerController {
  @PostMapping("/customer")
  public Customer create(@RequestBody Customer customer) {
    customer.setId(1);
    return customer;    
  }
}

アノテーション @RequestBody を付けると、引数のクラスに JSON の値をバインドしてくれます。

クラスに @RestController を付けると、メソッドの戻り値が JSON のレスポンスになります。

4. モデルの作成

以下のクラスを作成します。

src/main/java/org/example/model/Customer.java

package org.example.model;

import lombok.Getter;
import lombok.Setter;

@Getter @Setter
public class Customer {
  private long id;
  private String name;
  private int age;
}

Lombok を使って Getter/Setter を自動生成しています。

5. 起動クラスの作成

アプリを起動するクラスを作成します。

src/main/java/org/example/SpringApp.java

package org.example;

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

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

6. ビルドファイルの作成

Maven のビルドファイルを作成します。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.0.1</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <groupId>org.example</groupId>
  <artifactId>spring-jquery</artifactId>
  <version>1.0.0</version>

  <properties>
    <java.version>17</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

7. 動作確認

アプリを起動して以下の URL にアクセスします。

http://localhost:8080/index.html

名前と年齢を入力して「送信」を押すと、JSON の送受信を行います。受信した JSON は画面に表示されます。