web developer

[java] 배열을 문자열로 변환하여 AJAX를 통해 Java로 보내는 과정 본문

Language/Java

[java] 배열을 문자열로 변환하여 AJAX를 통해 Java로 보내는 과정

trueman 2024. 6. 17. 21:23
728x90
728x90

 

1. jQuery 버전 확인


  1. Ajax에서 배열을 전송할 때, traditional: true 옵션을 사용해야 하는 경우는 jQuery 1.4 이전의 버전에서 jQuery.param() 함수를 사용할 때입니다.
  2. jQuery 1.4 이전 버전에서는 param() 함수가 기본적으로 배열을 전송할 수 있는 형태로 시리얼라이즈하지 않기 때문에, 배열을 전송할 때 traditional: true 옵션을 명시적으로 설정해야 했습니다.
  3. 하지만 jQuery 1.4 이후 버전부터는 param() 함수가 기본적으로 배열을 다룰 수 있는 방식으로 업데이트되어서, 일반적으로 traditional: true 옵션을 따로 지정하지 않아도 됩니다.

2. params 객체JSON 문자열로 직렬화하여 AJAX 요청으로 서버에 전송


배열을 문자열로 변환하여 AJAX를 통해 Java로 보내는 과정이다.

  1. JavaScript에서 AjaxArrayToJava 함수가 호출되면, params 객체가 JSON 문자열로 직렬화되어 AJAX 요청으로 서버에 전송됩니다.
  2. Spring 컨트롤러의 receiveSurveyData 메서드는 @RequestBody와 Map을 사용하여 요청 본문을 Map<String, Object> 객체로 변환합니다.
  3. 서버는 Map 객체를 처리하고, 클라이언트에게 문자열 응답을 반환합니다.

javaScript

function AjaxArrayToJava(){
    var params = {
        question : ['1. What`s the value at index?', '2. Can you explain the element at index?', '3. What does index 2 contain?', '4. Could you describe what`s in position?', '5. How about the data stored at index?', '6. Tell me about the value found at index', '7. What`s the content of index', '8. Describe what you see at index', '9. And finally, what`s stored at index'],
        answer   : ['02', '01', '01', '01', '01', '01', '01', '01', '00']
    };

    const jsonString = JSON.stringify(params);
    console.log(jsonString);
    /*
    {
     	"question":["1. What`s the value at index?","2. Can you explain the element at index?","3. What does index 2 contain?","4. Could you describe what`s in position?","5. How about the data stored at index?","6. Tell me about the value found at index","7. What`s the content of index","8. Describe what you see at index","9. And finally, what`s stored at index"],
     	"answer":["02","01","01","01","01","01","01","01","00"]
    }
    */
    
    $.ajax({
        url         :    "/AjaxArrayToJava.do",
        contentType :    "application/json",
        type        :    "post",
        data        :    jsonString,
        success     :    function(data) {
            console.log(data);
        },
        error : function(request, status, error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });
}

 

java

@RequestMapping(value = "/AjaxArrayToJava.do", method = RequestMethod.POST)
public void AjaxArrayToJava(
    HttpServletRequest request,
    HttpServletResponse response,
    HttpSession session,
    @RequestBody Map<String, Object> params
){
    try {
        // Map으로 받은 데이터 처리
        List<String> questions = (List<String>) params.get("question");
        List<String> answers = (List<String>) params.get("answer");

        // 받은 데이터 출력
        System.out.println("Questions: " + questions);
        //Questions: [1. What`s the value at index?, 2. Can you explain the element at index?, 3. What does index 2 contain?, 4. Could you describe what`s in position?, 5. How about the data stored at index?, 6. Tell me about the value found at index, 7. What`s the content of index, 8. Describe what you see at index, 9. And finally, what`s stored at index]

        System.out.println("Answers: " + answers);
        //Answers: [02, 01, 01, 01, 01, 01, 01, 01, 00]

    }catch (Exception e) {
        System.out.println("!! Exception !!");
    }
}

728x90
728x90
Comments