ajaxからSpring BootのControllerへJSONを送信する方法(シンプルなモデル編)

ajaxからSpring BootのControllerへJSONを送信する方法をご紹介します。

このようなサンプルプログラムを作成しました。

ボタンをクリックするとjavascriptでjsonを生成して、Spring BootのControllerへajax処理でjsonを送信します。

最終的な開発環境のフォルダ構成です。

ソースコードです。

index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>JSON TEST</title>
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
  <form>
    <input type="button" id="test" value="test">
  </form>
</body>
</html>

ボタンがあるだけのシンプルな画面です。

script.js
$(function() {

  $("#test").on("click", function() {

    var model = {
      "no" : "1",
      "name" : "1"
    };

    console.log(model);
    console.log(JSON.stringify(model));

    $.ajax({
      url : '/',
      type : 'POST',
      data : JSON.stringify(model),
      contentType : 'application/json',
      error : function() {
        console.log("error");
      },
      success : function() {
        console.log("success");
      }
    });

  });

});

今回はサンプルなので、シンプルなjsonを作成しました。送信する際に contentType でjsonを指定することに注意です。また、JSON.stringifyで送信しないとController側で認識してくれないのでその点も注意です。

JsonController.java
package com.demo.app.controller;

import javax.servlet.http.HttpServletResponse;

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.RequestBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class JsonController {

  @GetMapping(value = "/")
  public ModelAndView index(HttpServletResponse response, ModelAndView mav) {
    mav.setViewName("index");
    return mav;
  }

  @PostMapping("/")
  public ModelAndView postIndex(HttpServletResponse response, @RequestBody JsonModel model, ModelAndView mav) {
    mav.setViewName("index");
    return mav;
  }

}

このControllerでjsonを受け付けます。@ModelAttributeでなく@RequestBodyであることが注意ポイントです。

JsonModel.java
package com.demo.app.controller;

import lombok.Data;

@Data
public class JsonModel {
  private String no;
  private String name;
}

jsonとマッピングされるモデルです。

これでボタンをクリックすると、ajaxからSpring BootのControllerへJSONが送信されます。