반응형

ajax 통신으로 파라미터를 아래과 같은 형식으로 controller에서 받아서 로직을 처리할 일이 생겼다.
(한 번에 여러건의 데이터 업데이트를 하기 위해서 한번에 파라미터를 전송해야했음)

[{key:value,  ... , key:value}, {key:value,  ... , key:value} ] 

결론부터 말하면 포기했었었었었지만 2021년 신규 posting




1. 데이터 형태
일자
시작시간
종료시간
장소(시도)
장소(군구)
2018-01-01
1:00
2:00
서울시
강남구
2018-01-02
3:00
5:00
서울시
강북구
2018-01-03
12:00
15:00
서울시
영등포구

2. 보낼데이터 만들기
var l_arr = new Array();

$("#popup_layer .table_body tr").each(function(p_index, p_item){
   if($(this).attr("data-no")){
       no           = $(this).attr("data-no");
       date         = $(this).children().children("input[name='date']");
       starttime    = $(this).children().children("input[name='starttime']");
       endtime      = $(this).children().children("input[name='endtime']");
       sidocode     = $(this).children().children().children("#sido");
       sigungucode  = $(this).children().children().children("#sigungu");
      

       l_arr.push(
            {"no"              : no,
            "date"             : date.val(),
            "starttime"        : starttime.val(),
            "endtime"          : endtime.val(),
            "sidocode"         : sidocode.val(),
            "sigungucode"      : sigungucode.val()
            }
       )
   }
});


3. 데이터 보내기 1차 시도
    javascript 소스

    $.ajax({
        url : '/test.do',
        dataType : 'text',
        type : 'POST',
        data : {'arr' : l_arr},
        success : function(l_resultvalue) {

        }
    });

    java 소스
    @RequestMapping("/test.do")
    public ModelAndView saveInfoAjax(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String param = request.getParameterValues(arr);
    }

    결과 : 파라미터를 받을 수가 없었음



4. 데이터 보내기 2차 시도 (구글 검색 후 배열을 map으로 파싱)
    @RequestMapping("/test.do")
    public ModelAndView saveInfoAjax(HttpServletRequest request, HttpServletResponse response) throws Exception {
        @SuppressWarnings("rawtypes")
        Enumeration enums = request.getParameterNames();
                  
        while(enums.hasMoreElements()){
           String paramName = (String)enums.nextElement();
           Map<String, Object> paramMap = new HashMap<String, Object>();
                  
           paramMap.put(paramName, request.getParameterValues(paramName));
                  
           String[] parameters = request.getParameterValues(paramName);
           // Parameter가 배열일 경우
           if(parameters.length > 1){
               List<Object> parmList = new ArrayList<Object>();
                   for(int i= 0; i<parameters.length;i++){
                       parmList.add(parmList.size(), parameters[i]);
                   }
                   parameterMap.put(paramName, parmList);
           }
        }
        System.out.println(parameterMap);
    }



    결과 :  데이터 형태가 이상하게 옴

    arr_appointment_info[0][no]
    arr_appointment_info[0][date]
    arr_appointment_info[0][starttime]
    arr_appointment_info[0][endtime]
    arr_appointment_info[0][sidocode]
    arr_appointment_info[0][sigungucode]
    arr_appointment_info[1][no]
    arr_appointment_info[1][date]
    arr_appointment_info[1][starttime]
    arr_appointment_info[1][endtime]
    arr_appointment_info[1][sidocode]
    arr_appointment_info[1][sigungucode]



5. 데이터 보내기 3차 시도(@RequestBody로 받아보기)

    javascript 소스

    $.ajax({
        url : '/test.do',
        contentType : 'application/json',
        processData : 'false',
        dataType : 'json',
        type : 'POST',
        data : JOSN.stringify({'arr' : l_arr}),
        success : function(l_resultvalue) {

        }
    });


    java 소스
    @RequestMapping("/test.do")
    public ModelAndView saveInfoAjax(HttpServletRequest request, HttpServletResponse response, @RequestBody HashMap<String, Object > params) throws Exception {
        System.out.println(params);
    }


    결과 : java 에러 발생 파라미터 자체가 안받아짐
    java 에러 :  org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

    java 에러 해결이 안됨 
            에러 해결 시도 1 (dependency 추가) : 같은 에러 발생 실패
            <dependency>
                  <groupId>com.fasterxml.jackson.core</groupId>
                  <artifactId>jackson-core</artifactId>
                  <version>2.9.3</version>
              </dependency>
      
              <dependency>
                  <groupId>com.fasterxml.jackson.core</groupId>
                  <artifactId>jackson-annotations</artifactId>
                  <version>2.9.3</version>
              </dependency>
      
              <dependency>
                  <groupId>com.fasterxml.jackson.core</groupId>
                  <artifactId>jackson-databind</artifactId>
                  <version>2.9.3</version>
                  <exclusions>
                      <exclusion>
                          <artifactId>jackson-annotations</artifactId>
                          <groupId>com.fasterxml.jackson.core</groupId>
                      </exclusion>
                  </exclusions>
              </dependency>

            에러 해결 시도 2 (Ajax에서 옵션추가 및 변경)  :같은 에러 발생 실패
                     contentType : 'application/json',
          processData : 'false',
          url : '/test.do',
          dataType : 'json',
          data : JOSN.stringify({'arr' : l_arr}),

            에러 해결 시도 3 (@RequestParam어노테이션 사용 ) :같은 에러 발생 실패
                    java 소스
            @RequestMapping("/test.do")
            public ModelAndView saveInfoAjax(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, Object > params) throws Exception {
                System.out.println(params);
            }




6. 결국 데이터를 다른방식으로 전송
    javascript 소스
     var l_param_string = "";

    $("#popup_layer .table_body tr").each(function(p_index, p_item){
       if($(this).attr("data-no")){
           no           = $(this).attr("data-no");
           date         = $(this).children().children("input[name='date']");
           starttime    = $(this).children().children("input[name='starttime']");
           endtime      = $(this).children().children("input[name='endtime']");
           sidocode     = $(this).children().children().children("#sido");
           sigungucode  = $(this).children().children().children("#sigungu");
      
    
          // 순서 중요
          l_param_string +=
          vibmatchno+","+
          apppointmentdate.val()+","+
          appointmentstarttime.val()+","+
          appointmentendtime.val()+","+
          appointmentsidocode.val()+","+
          appointmentsigungucode.val()+","+
          appointmentaddresskr.val()+","+
          appointmentaddressen.val()+"|"
       }
    });

    $.ajax({
        url : '/test.do',
        dataType : 'text',
        type : 'POST',
        data : {'param_string' :l_param_string},
        success : function(l_resultvalue) {
            try{
                var l_result_value = eval('(' + l_resultvalue + ')');
                if(l_result_value.resultcode > 0) {
                    alert(l_result_value.resultmessage);
                }
            } catch(e) {
                alert(e);
            }
        }
    });


java 소스 
      @RequestMapping("/test.do")
    public ModelAndView saveInfoAjax(HttpServletRequest request, HttpServletResponse response) throws Exception {
                 // split 시 |, \\|로는 정상적으로 안쪼개짐 [|] 로 해야 정상적으로 쪼개짐
String value = request.getParameter(param_string).split("[|]");
        String setParamString[];
        if(paramString.length > 0){
            int updateResultCnt = 0;
            for(int i = 0 ; i < paramString.length; i++){
                setParamString = paramString[i].split(",");
                        
                paramMap.put("vno",setParamString[0]);
                paramMap.put("date",setParamString[1]);
                paramMap.put("starttime",setParamString[2]);
                paramMap.put("endtime",setParamString[3]);
                paramMap.put("sidocode",setParamString[4]);
                paramMap.put("sigungucode",setParamString[5]);                        
                        
                updateResultCnt += Service.updateTest(paramMap);
                    if(updateResultCnt < i+1){
                        mv.addObject("resultcode", -1);
                        mv.addObject("resultmessage", "Update Fail");
                        return mv;
                    }
           }
           mv.addObject("resultcode", 1);
           mv.addObject("resultmessage", "Update Success");
        }
            
        return mv;
    }

반응형

+ Recent posts