2020년 5월 15일 금요일

[Spring] Using @RequestBody, @ResponseBody

Get JSON Data with @RequestBody

Enter the jackson library into pom.xml to convert JSON-type information into Map and Command objects.
pom.xml
<!--JSON-->
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.9.3</version>
</dependency>

Ajax
var obj = {"name": "kim", "age": 30};

$.ajax({
    url: "/test",
    type: "post",
    data: JSON.stringify(obj),
    contentType: "application/json",
    success: function(data) {
        alert("성공");
    },
    error: function(errorThrown) {
        alert(errorThrown.statusText);
    }
});
 Ajax function to send requests to the controller. The two important points here are to send data using the JSON.stringify function and to set the contentType to "application/json". Otherwise, you will not be able to receive information with @RequestBody.


Convert JSON to Map Form
@Controller
public class MainController {
 
    @ResponseBody
    @RequestMapping("/test")
    public void init(@RequestBody HashMap<String, Object> map) {
    
     System.out.println(map);
     // {name=kim, age=30} 출력
    }
}
 Ajax function to send requests to the controller. The two important points here are to send data using the JSON.stringify function and to set the contentType to "application/json". Otherwise, you will not be able to receive information with @RequestBody.


Convert JSON to Object Form
@Controller
public class MainController {
 
    @ResponseBody
    @RequestMapping("/test")
    public void init(@RequestBody UserVO userVO) {
        
     userVO.getName(); // "kim"
        userVO.getAge(); // 30
    }
}
 At this time, the Property of the UserVO class must match the transmitted JSON object with the Property name and must have a getter, setter.


Foward JSON Data to @ResponseBody


To send Map Data
@Controller
public class MainController {
 
    @ResponseBody
    @RequestMapping("/test")
    public HashMap<String, Object> init(@RequestBody HashMap<String, Object> map) {
     
        map.put("phone", "0000-0000");
     return map;
        // {"name": "kim", "age": 30, "phone": "0000-0000"}가 data로 바인딩
    }
}
 When you return Map from a method with @ResponseBody, Map information is automatically converted and sent to JSON objects.

To send object Data
@Controller
public class MainController {
 
    @ResponseBody
    @RequestMapping("/test")
    public HashMap<String, Object> init(@RequestBody UserVO userVO) {
        
     HashMap<String, Object> map = HashMap<String, Object>();
        map.put("userVO", userVO);
        
        return map;
        // {"userVO": {name: "kim", age: 30}}가 data로 바인딩
    }
}
 Because object information is complicated to send as it is, it is made into a map shape and then returned and sent.

댓글 없음:

댓글 쓰기