[Spring] REST 기초 - 3 : Ajax - post(전송)

Ajax 의 전송 방식은 다음과 같다. 

① : 전송의 경우 "POST" 로 고정 

② : 요청하거나 받은 URL

③ : 전송 데이터

※ ajax를 이용하므로, 전송 데이터를 json 형식으로 지정할 필요가 있음
- JOSON.stringify(전송에 사용될 데이터 변수 명)

④ : 전송 데이터 타입(application/json;charset=utf-8 사용)

 : 전송/수신 성공 시 수행 할 동작이나 callback 함수 사용

- function(data)의 data는 수신 받은 데이터를 저장함

 : 전송/수신 실패 시 수행 할 동작이나 callback 함수 사용(주로 오류 출력)


응답을 처리하는 경우, @RestController에서 처리함

-사용 restcontroller 일부

1
2
3
4
5
6
7
8
9
10
11
12
13
/*
     RequestMapping - consumes : ajax로 전달 받은 데이터의 형식
     @RequestBody : 전달 받은 데이터임을 명시
     ResponseEntity : 응답을 위한 반환 객체
*/
@RequestMapping(value = "/sampleInsertTest", consumes="application/json")
    public ResponseEntity<String> sampleInsert(@RequestBody BoardVO vo){
        log.info("ReplyVO : "+vo);
        int insertCount = bservice.register(vo); // 데이터입력 확인
        log.info("reply insert count : "+insertCount); // 데이터가 입력된 경우 1, 아닐 경우 0
        
        return insertCount == 1 ?new ResponseEntity<String>("success", HttpStatus.OK) : new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);    
    }
cs


※ 주의 사항

- ajax를 처리하는 controller의 @RequestMapping의 consumes와 ajax contentType 의 값은 동일해야 함



- 데이터 삽입을 위한 자바 스크립트 함수 일부
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function sampleInset(bvo, callback, error){
        $.ajax({
            type : 'post',
            url : "/board/replies/sampleInsertTest"//데이터 전송 경로
            data : JSON.stringify(bvo), // json 타입으로 변환
            contentType : "application/json; charset=utf-8"//해당 데이터의 타입 
            success : function(result, status, xhr){
                if(callback){
                callback(result);
                }
            },
            error : function(xhr, status, er){
                if(error){
                    error(er);
                }
            }
        
        })
    
cs


- 실습을 위한 jsp 파일

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--
    form 태그 사용 없이 버튼 클릭시 데이터 전송 사용
    편의를 위해 class 지정된 div 내부에 input 태그 삽입
-->
<div class="insertDiv">
title<input name="title"><br>
content<input name="content"><br>
writer<input name="writer"><br>
</div>
 
<button id="sampleInsertBtn">insert</button>
 
</body>
<script src="http://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="/resources/js/sampleTest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    //버튼 클릭시 해당 데이터 전송 동작
    $("#sampleInsertBtn").on("click",function(e){
        var insertdiv = $(".insertDiv");
        var title = insertdiv.find("input[name=title]"); //div 태그 내부의 name : title 
        var content = insertdiv.find("input[name=content]");//div 태그 내부의 name : content
        var writer = insertdiv.find("input[name=writer]");//div 태그 내부의 name : writer
        
        //각 값을 하나의 객체로 생성
        var board = {
                title : title.val(),
                content : content.val(),
                writer : writer.val()
        };
        //값         
        testService.sampleInset(board, function(result){
            console.log(result);
        })
 
    })
    
    
})
 
</script>
 
</html>
cs



댓글