스프링

 

Web개발을 할 때 ajax를 사용해서 통신하는 경우가 매우 많다.

클라이언트에서 Spring Controller로 ajax 등의 요청을 했을 때, json형식으로 return 받기 위해서는 여러 방법이 있을 수 있다. 그 중 두 가지 방법이 주로 쓰인다.

1. Controller return type을 String으로 하고, 별도의 Json API를 사용해 parsing해서 json 형식으로 return 해준다.

2. MappingJackson2JsonView를 사용해서 ModelAndView를 json 형식으로 반환해 준다.

 

 

1번은 Gson 등 Json API들을 사용해서 적당히 Parsing하면 될 것이고, 지금 알아볼 것은 2번 방법이다.

별도의 처리 없이 컨트롤러에서 ModelAndView를 넘기면 당연히 안된다.

Spring Bean 설정 없이 구글링으로 ModelAndView mv = new ModelAndView("jsonView") 와 같은 소스를 긁어오면 아래와 같은 에러를 볼 수 있을 것이다.

Error resolving template "jsonView", template might not exist or might not be accessible by any of the configured Template Resolvers

방법은 간단하다.

 

1) MappingJackson2JsonView 형식의 jsonView를 Spring Bean으로 등록한다.

<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="contentType" value="application/json;charset=UTF-8"> </property>
</bean>

 

Spring boot를 사용하고 따로 DispatcherServlet xml을 사용해서 설정하지 않는다면, @Configuration 을 붙인 WebConfig 파일에서 Bean으로 등록

@Bean
    MappingJackson2JsonView jsonView(){
        return new MappingJackson2JsonView();
    }

 

2) Controller에서 return할 ModelAndView를 생성 할 때 View를 "jsonView"로 설정

ModelAndView mv = new ModelAndView("jsonView");
    userVO.setOrderBy(orderDir);
    userVO.setOrderId(orderColNm);
    
    List<UserVO> userList = userMgmtSvc.selectUserList(userVO);
    int totalCnt = userMgmtSvc.selectUserListCount(userVO);
    
    mv.addObject("recordsTotal", totalCnt);
    mv.addObject("recordsFiltered", totalCnt);
    mv.addObject("data", userList);
    
    return mv;

 

 

----------------------------------------------------------------------------------------------------------------------------------------------------------

1. Ajax 처리

Ajax에서는 json 타입으로 데이터를 보낸다. 그런데 Controller에서는 Map<String, Object>로 받고 싶다. 그렇다면 어떻게 해야할까? 답은 간단하다. 보낼때 Map<String,Object> 형식으로 셋팅을 해주면 된다.

 

Ajax

$('#changeSubmitBtn').click(function(e){
    var data = {}
    data["name"] = $('#name').val();
    data["tel"] = $('#tel').val();
    data["email"] = $('#email').val();
    var birth = $('#birth').val();
    data["birth"] = birth.replace(/-/g,''); // 2015-09-24 => 20150924 로 변경

    $.ajax({
        contentType:'application/json',
        dataType:'json',
        data:JSON.stringify(data),
        url:'/mypage/updateUser',
        type:'POST',
        success:function(response){
                alert(response.message);
            },
        error:function(request,status,error){
                alert(response.message);
            }
        });
});

먼저 data를 생성하여, <String,Object> 형식으로 데이터를 넣어준다.

data["name"] = $('#name').val();  이 그러한 형식이다.

나는 넣을게 별로 없어서 다 일일이 기술해주었지만,

넣을게 너무 많아 넘치게 되면 for문을 이용하는 방법도 고려할 만 하다.

 

그리고 ajax에서 보낼 때  data:JSON.stringify(data) 라고 작성한다.

우리가 선언한 var data는 javascript 변수인데, ajax에서는 json 형태로 데이터를 반환하므로,

javascript 값을 json 형태로 파싱해야 한다.

그리고 .stringify 는 Javascript 값을 json 으로 파싱해주는 메소드다.

 

 

2. Controller 처리

 

Controller

    @RequestMapping(value="/mypage/updateUser", method=RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateUserInfo(@RequestBody Map<String, Object> params){        
        Map<String, Object> resultMap = new HashMap<String,Object>();        
        try{
            userService.updateUserInfo(params);            
        }catch(Exception e){
            resultMap.put("message",e.getMessage());
            return resultMap;
        }        
        resultMap.put("message", "회원 정보가 정상적으로 변경되었습니다");
        return resultMap;
    }

Controller에서는 해당 메소드 위에 @ResponseBody 를 입력해준다. return 값을 HTTP Response Body 로 전달하라는 뜻이다. ajax 역시 HTTP Request Body 를 통해 파라미터를 전달하므로 파라미터 앞에 @RequestBody 를 명시해준다. 그리고 아래 로직은 다른 컨트롤러와 동일하다. 파라미터를 Service로 전달하고, 다시 DAO로 전달하기. 그러면 끝 :-)

 

 

--------------------------------------------------------------------------------------------------------------------------------

 

파싱

 

var base_url = 'http://people.cs.uct.ac.za/~swatermeyer/VulaMobi/';

function example()
{
    var response = "";
    var form_data = {
        username: username,
        password: password,
        is_ajax: 1
    };
    $.ajax({
        type: "POST", 
        url: base_url + "ajax.php?test/json", 
        data: form_data,
        success: function(response)
        {
            /*response = '[{"Language":"jQuery","ID":"1"},{"Language":"C#","ID":"2"},
                           {"Language":"PHP","ID":"3"},{"Language":"Java","ID":"4"},
                           {"Language":"Python","ID":"5"},{"Language":"Perl","ID":"6"},
                           {"Language":"C++","ID":"7"},{"Language":"ASP","ID":"8"},
                           {"Language":"Ruby","ID":"9"}]'*/
            console.log(response);
            
	    var json_obj = $.parseJSON(response);//parse JSON
            
            var output="<ul>";
            for (var i in json_obj) 
            {
                output+="<li>" + json_obj[i].Language + ",  " + json_obj[i].ID + "</li>";
            }
            output+="</ul>";
            
            $('span').html(output);
        },
        dataType: "json"//set to JSON    
    })    
}

 

$.ajax({
            type : "GET",
            url : "home/fetch_regions",
            dataType: 'html',
            data : {
                param : count_val,
                '_token' : $('meta[name="csrf-token"]').attr('content'),
            },
            success : function(response) {
                var jsonObject = JSON.parse(response);
                var $el = $(".regions tbody tr");
                        $el.empty(); // remove old options
                    $.each($.parseJSON(response), function(key,obj) { //$.parseJSON() method is needed unless chrome is throwing error.
                       $el.append("<td>"+ obj[key] +"</td>");
                    }); 
            }
        });

 

$("#uproducti").fileinput({
        uploadUrl: "/myupload.php",
        allowedFileExtensions: ["jpg", "png", "jpeg"],
        minImageWidth: 750,
        minImageHeight: 750,
        maxFileCount: 4,
        uploadExtraData: function() {
            return {
              userid: $("#usrid").val(),
              token: $("#tokn").val(),
              productid : $("#prglid").val()
            };
        },
        dataType: "json",  
        success: function (response) {
            console.log(response);
            var json = $.parseJSON(response);//parse JSON
            alert(json.pid);
            
            $("#prid").val(json.pid);
        }
      });`

 

 

 

about author

PHRASE

Level 60  라이트

조금 아는 바가 있다 해서 스스로 뽐내며 남을 깔본다면 장님이 촛불을 들고 걷는 것 같아 남은 비춰 주지만 자신은 밝히지 못한다. -법구경

댓글 ( 5)

댓글 남기기

작성

스프링 목록    more