I want to exchange JSON data (object) by Ajax between Java and JavaScript! ~ Spring edition ~

Pass JSON data from JS to Java controller

I handed over JSON when I made a simple TODO application, so a memorandum I am using Ajax communication with jQuery

todo.js


/**Add new to database. */
  function postItem(newContent) {

    let todo = {
      content: newContent
    };

    $.ajax({
      type: "post",
      url: contextPath + "/post",  //OK if it is the URL to call Controller
      data: { jsonTodo: JSON.stringify(todo) }, //JSON(Associative array)To a string
      dataType: "json"
    }).then(function (result) {
      console.log('You can write the processing at the time of success. As below.');
      let content = result.content;
    }, function () {
      console.log('You can write the processing at the time of failure');
    });

Kimo is JSON.stringify (converts the target JSON to a string)

TodoController.java


	/**
	 *Add a new TODO.
	 * @param todo New post TODO
	 * @TODO with return update reflected
	 */
	@ResponseBody //Since the annotation has a built-in JSON encoder, you can return the object directly to JS.
	@PostMapping("/post")
	public Todo post(@RequestBody Todo todo) throws JsonParseException, JsonMappingException, IOException  {
        todoRepository.saveAndFlush(todo); //db update
		return todo;
	}

Pass an object from a Java controller to JS

TodoController.java


    @ResponseBody //Automatically converts the returned object to a string that can be interpreted in JSON
	@GetMapping("/find_all_asc")
	public List<Todo> findAllOrderASC(){
		List<Todo> todos = todoRepository.findAll(new Sort(Direction.ASC, "id"));
		return todos;
	}

todo.js


  /**TODO list initialization*/
  $.getJSON(contextPath + "/find_all_asc", null,
    function (data, textStatus, jqXHR) { //JSON is stuck in data
    //You can describe the process you want to do with the acquired JSON
      data.forEach(todo => {
        console.log(todo.content);  
      });
    }
  );

Ajax Setup (includes jQuery description)

JavaScript


$(function () {
    /**
     * layout.Context path obtained from html.
     *Example)/elabel/If you want to access edit, click "contextPath"+ 'elabel/edit'Can be used as a URL.
     */
    contextPath = $('#contextPath').val();
});

/**If you want to change the setting, please describe it in the individual Ajax method. */
(function () {
    $.ajaxSetup({
        cache: false,
        /**Do not cache the response of Ajax communication used once. */
        timeout: 15000,
        /**Timeout setting (provisional)*/
        beforeSend: function (xhr, settings) {
            /**Processing just before the start of communication*/
            setCsrfTokenToAjaxHeader();
            // showKurukuru();
        },
        success: function (data, status, xhr) {
            /**Processing when communication is successful*/
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            /**Processing when communication fails*/
            console.log("ajax communication failed");
            console.log("XMLHttpRequest : " + XMLHttpRequest.status);
            console.log("textStatus     : " + textStatus);
            console.log("errorThrown    : " + errorThrown.message);
        },
        complete: function (xhr, status) {
            /**Processing when communication is completed (regardless of whether it is an error or not)*/
            //hideKurukuru();
        },
    });
})();

/**
 *Function that can embed tokens by CSRF measures of Spring Security in header of ajax communication.
 *Please use it by calling it just before the Ajax communication to be used..
 */

function setCsrfTokenToAjaxHeader() {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function (e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
}

Thymeleaf


<meta name="_csrf" th:content="${_csrf.token}" />
<meta name="_csrf_header" th:content="${_csrf.headerName}" />
<input id="contextPath" type="hidden" th:value="${#request.getContextPath()}" />

Reference article

Nifty JSON.stringify (http://www.symmetric.co.jp/blog/archives/1568) Reference article to POST from ajax to java POST from ajax to java (http://brissyu.blogspot.jp/2015/09/11spring-boot-web-ajax-csrf.html) Receive json by POST in spring3 (http://ponkotsusechan.hatenadiary.jp/entry/2016/02/01/173000_1)

Recommended Posts

I want to exchange JSON data (object) by Ajax between Java and JavaScript! ~ Spring edition ~
I want to display images with REST Controller of Java and Spring!
I want to transition screens with kotlin and java!
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...
How to use JSON data in WebSocket communication (Java, JavaScript)
Difference between Java and JavaScript (how to find the average)
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
[jackson] I want to receive JSON values "0" and "1" as boolean
Create API to send and receive Json data in Spring
I want to implement various functions with kotlin and java!
I want to return to the previous screen with kotlin and java!
[Java] I want to perform distinct with the key in the object
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
[Java Spring MVC] I want to use DI in my own class
I want to stop Java updates altogether
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
Differences between Java, C # and JavaScript (how to determine the degree of obesity)
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (black magic edition)
Run R from Java I want to run rJava
I want to send an email in Java.
I want to use java8 forEach with index
I tried to link JavaFX and Spring Framework.
I want to write quickly from java to sqlite
[Java] Difference between "final variable" and "immutable object"
Display and post multi-layered data by ancestry !! ~ Ajax ~
I want to delete files managed by Git
I tried to create a shopping site administrator function / screen with Java and Spring
I want to issue a connection when a database is created using Spring and MyBatis
I want to return an object in CSV format with multi-line header & filter in Java
# 1_JAVA I want to get the index number by specifying one character in the character string.