danbibibi
article thumbnail
Published 2023. 4. 26. 15:03
REST API 실습 WEB/back-end

pom.xml

json을 사용하기 위해 다음과 같이 dependency를 추가해주었다!

<!-- json -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.0</version>
</dependency>

++ 각각의 Repo파일에 @Mapper annotation을 붙여준다!

 

CatRestController.java

RequestBody import에 주의 ...!!!!!!!!!!!! 해야 한다!! 2개다!!

import org.springframework.web.bind.annotation.RequestBody 로 import하자!!

그렇지 않으면 null 값으로 들어온다^^ 

package com.ssafy.cat.controller;

import java.sql.SQLException;
import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ssafy.cat.dto.Cat;
import com.ssafy.cat.model.service.CatService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@CrossOrigin("*")
@RestController
@RequestMapping("/api")
public class CatRestController {
    
    @Autowired
    private CatService cs;

    //  등록
    @PostMapping("/cat")
    public ResponseEntity<?> insert(@RequestBody Cat cat) throws SQLException {
        System.out.println(cat);
        int r = cs.insert(cat);
        if (r == 1) return new ResponseEntity<Integer>(r, HttpStatus.CREATED);
        return new ResponseEntity<Integer>(HttpStatus.NO_CONTENT);
    }
    //  수정
    @PutMapping("/cat")
    public ResponseEntity<?> update(@RequestBody Cat cat) throws SQLException {
        int r = cs.update(cat);
        if (r == 1) return new ResponseEntity<Integer>(r, HttpStatus.CREATED);
        return new ResponseEntity<Integer>(HttpStatus.NO_CONTENT);
    }
    
    //  전체 조회
    @GetMapping("/cat")
    public ResponseEntity<?> select() throws SQLException {
        List<Cat> cats = cs.selectAll();
        System.out.println(cats);
        if (cats != null && cats.size()>0) return new ResponseEntity<List<Cat>>(cats, HttpStatus.OK);
        return new ResponseEntity<Void> (HttpStatus.NO_CONTENT);
    }
    
    //  상세 조회
    @GetMapping("/cat/{code}")
    public ResponseEntity<?> detail(@PathVariable String code) throws SQLException {
        Cat cat = cs.select(code);
        if (cat != null) return new ResponseEntity<Cat>(cat, HttpStatus.OK);
        return new ResponseEntity<Void> (HttpStatus.NO_CONTENT);
    }
    
    //  삭제
    @DeleteMapping("/cat/{code}")
    public ResponseEntity<?> delete(@PathVariable String code) throws SQLException {
        int r = cs.delete(code);
        if (r == 1) return new ResponseEntity<Integer>(r, HttpStatus.OK);
        return new ResponseEntity<Integer>(HttpStatus.NO_CONTENT);
    }

}

 

rest.jsp

Ajax를 이용한 비동기 통신 + REST API 방식으로 동작하는 코드이다!

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="root" value="${pageContext.request.contextPath }" scope="session" />
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>캣 REST</title>
    <script>
      function formData() {
        let cat = {};
        cat.code = document.querySelector("#code").value;
        cat.nickname = document.querySelector("#nickname").value;
        cat.price = document.querySelector("#price").value;
        cat.id = document.querySelector("#id").value;
        return cat;
      }

      function show(cat) {
        document.querySelector("#code").value = cat.code;
        document.querySelector("#nickname").value = cat.nickname;
        document.querySelector("#price").value = cat.price;
        document.querySelector("#id").value = cat.id;
      }

      function print(msg) {
        document.querySelector("#result").innerHTML = msg;
      }

      function getCat() {
        fetch("${root}/api/cat/" + event.target.innerText.split(" ")[0])
          .then((response) => response.json())
          .then((cat) => {
            show(cat);
            print("조회성공");
          });
      }

      window.onload = function () {
        document.querySelector("#blst").addEventListener("click", function () {
          fetch("${root}/api/cat")
            .then((response) => response.json())
            .then((cats) => {
              console.log(cats);
              let lis = "";
              cats.forEach((cat) => {
                lis +=
                  "<li onclick='getCat()'>" + cat.code + " " + cat.nickname + " " + cat.price + " " + cat.id + "</li>";
              });
              document.querySelector("#list").innerHTML = lis;
            })
            .catch((error) => alert("요청실패"));
        });
        document.querySelector("#badd").addEventListener("click", function () {
          fetch("${root}/api/cat", {
            method: "post",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(formData()),
          })
            .then((response) => response.json())
            .then((data) => {
              console.log(data);
              document.querySelector("#blst").click();
              print("추가성공");
            })
            .catch((error) => alert("요청실패"));
        });
        document.querySelector("#bupd").addEventListener("click", function () {
          fetch("${root}/api/cat", {
            method: "put",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(formData()),
          })
            .then((response) => response.json())
            .then((data) => {
              document.querySelector("#blst").click();
              print("변경성공");
            })
            .catch((error) => alert("요청실패"));
        });
        document.querySelector("#bdel").addEventListener("click", function () {
          fetch("${root}/api/cat/" + document.querySelector("#code").value, {
            method: "delete",
            headers: {
              "Content-Type": "application/json",
            },
          })
            .then((response) => response.json())
            .then((data) => {
              document.querySelector("#blst").click();
              print("삭제성공");
            });
        });
        document.querySelector("#bcle").addEventListener("click", function () {
          show({ code: "", nickname: "", price: "", id: "" });
        });
      };
    </script>
  </head>
  <body>
    <h1>괭이 REST</h1>
    <button id="blst">목록조회</button>
    <ul id="list"></ul>
    <button id="badd">추가</button>
    <button id="bupd">수정</button>
    <button id="bdel">삭제</button>
    <button id="bcle">초기화</button>
    <br />
    <form action="">
      코드 : <input type="text" id="code" value="104" /><br />
      애칭 : <input type="text" id="nickname" value="고먐미" /><br />
      가격 : <input type="text" id="price" value="4000" /><br />
      유저 : <input type="text" id="id" value="ssafy" /><br />
    </form>
    <br />
    <div id="result"></div>
  </body>
</html>

 

동작 영상

 

'WEB > back-end' 카테고리의 다른 글

서버 클라이언트 인증 방식, Cookie/Session/Token  (0) 2023.09.13
Spring Boot  (0) 2023.04.26
REST(Representational State Transfer) API  (0) 2023.04.26
web.xml, servlet-context.xml, root-context.xml  (0) 2023.04.25
Spring-MyBatis 실습  (0) 2023.04.24
profile

danbibibi

@danbibibi

꿈을 꾸는 시간은 멈춰 있는 것이 아냐 두려워하지 마 멈추지 마 푸른 꿈속으로