[스프링 MVC] 클라이언트와 서버간의 AJAX를 통한 JSON 전송

LTEN·2022년 8월 28일
0

스프링 MVC

목록 보기
2/2

클라이언트와 서버와 JSON을 주고 받는 방법에 대해 정리해보겠습니다.

1. 클라이언트(JS)

JS의 Fetch API를 통해 JSON 형태로 데이터를 전달하는 방법입니다.

function duplicatedMemberCheck() {
            const data = { "userId" : document.getElementById("userId").value};

            fetch('/members/duplicatedMemberCheck',
                {
                    method : 'post',
                    headers : {
                        'Content-Type' : 'application/json'
                    },
                    body : JSON.stringify(data)
                })
            .then((response) => {
                return response.json();
             }).then((json) => {
                if(json.result == false){
                    // ...
                }
                else{
					// ...
                }
             })

        }

클라이언트에서 데이터를 JSON으로 전달하고, JSON 형태로 받아서 처리하는 예시입니다.

보내기

(1) const data = { ... }
전송할 데이터를 JS에서 직접 JSON으로 생성

(2) fetch heards, body
headers에 content-type이 JSON 임을 표시해주고, body에 JSON.stringify를 이용하여 전달

받기

response.json() 으로 JSON을 얻은 후 사용

서버(Controller)

	@ResponseBody
    @PostMapping("/members/duplicatedMemberCheck")
    public String duplicateMemberCheck(HttpServletRequest httpServletRequest) throws IOException {
        // 1. Request의 body를 읽기
        ServletInputStream inputStream = httpServletRequest.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        inputStream.close();

        // 2. ObjectMapper를 통해 JAVA 변수로 읽어오기
        Map<String, Object> json = new ObjectMapper().readValue(messageBody, HashMap.class);
        String userId = (String)json.get("userId");

        Boolean result = memberService.checkUserIdDuplication(userId);

		// 3. 다시 JSONObject를 생성한 후 전달할 값을 put
        JSONObject response = new JSONObject();
        response.put("result", result);

		// 4. JSONOBject.toString() 을 이용하여 JSON 형태의 문자열로 response 전달
        return response.toString();
    }
profile
백엔드

0개의 댓글