builder로 값 넣기
- builder().build()로 List에 값 넣기
- 이전 방식은 new 인스턴스 생성후 setter로 값 넣기였지만, builder로 값을 넣을 수 있다. (가독성 더 좋아짐)
- 클래스명 변수명 = 클래스명.builder().변수명(값).build(); 형태
- 그 이전에 먼저 해당 엔티티 클래스에는 @Builder 어노테이션을 줘야한다.
- 예시
-
@Data @Builder public class Member { private String username; private String password; private String email; private LocalDate joindate; }
- 이후 컨트롤러에서 메서드에 builder() 코드 추가
- 예시
-
Member member1 = Member.builder() .username("hong") .password("1234") .email("abc@dot.com") .joindate(LocalDate.now()) .build(); ApiController.memberList.add(member1);
Rest API
- REST (Representational State Transter)
- 자원의 표현에 의한(ex.학생 정보이면 students를 표현으로 정하는 것) 상태 전달(json 또는 xml으로 데이터 주고 받는 것)
- 컨트롤러에서 html을 return하지 않고 데이터 만을 return
- HTTP URI(Uniform Resource Identifier)를 통해 자원(Resource)을 명시하고, HTTP Method(POST, GET, PUT, DELETE 등)를 통해 해당 자원(URI)에 대한 CRUD를 적용 하는 것
- REST의 구성 요소
- 자원(Resource)
- HTTP URI
- 자원의 대한 행위(Verb)
- HTTP Method
- 자원에 대한 행위의 내용(Representations)
- HTTP Message Pay Load
- 자원(Resource)
- REST의 특징
- Server-Client (서버-클라이언트 구조)
- Stateless (무상태)
- Cacheable (캐시 처리 가능)
- Layered System (계층화)
- Uniform Interface (인터페이스 일관성)
- REST API
- REST의 원리를 따르는 API를 의미
- 설계 규칙 (URI 작성 규칙)
- URI는 명사와 소문자를 사용해야 한다.
- 마지막에 슬래시를 포함하지 않는다.
- 언더바 대신 하이폰 사용 (-)
- 파일 확장자는 URI에 포함하지 않는다.
- 행위 단어를 포함하지 않는다.
- @RestController
- @Controller와 @ResponseBody를 합친 어노테이션이며, Rest API 사용 컨트롤러에 작성
- 여기서 @ResponseBody는 json 형태의 데이터로 반환하는 어노테이션!
- 그전에 Request DTO 클래스와 Response DTO 클래스를 따로 생성한다.
- 메서드 작성할 때 매개변수로 (@RequestBody RequestDTO클래스 변수명) 으로 @RequestBody 어노테이션을 붙여서 선언한다.
- 해당 RequestDTO는 받아온 값이랑 기존 값을 확인하는 로직에 사용
- 이후 메서드 안에서 Response DTO new 인스턴스를 생성한다.
- 해당 ResponseDTO는 값을 set 하고, 해당 인스턴스를 return 한다.
- @Controller와 @ResponseBody를 합친 어노테이션이며, Rest API 사용 컨트롤러에 작성
- fetch()
- 자바스크립트에서 서버에 AJAX 통신하는 함수, axios와 달리 브라우저에 내장된 함수
- AJAX란 Asynchronous JavaScript and XML의 줄임말이며 자바스크립트를 사용하여 브라우저와 서버 간의 비동기적인 데이터 교환을 수행하는 기술!
- HTTP request(클라이언트→ 서버) 전송 기능을 제공
- 사용법
- html에서 스크립트 태그안에서 fetch() 함수 작성
- const promise = fetch(url, [, options])
- url은 HTTP 요청을 전달한 url
- options는 HTTP 요청 메서드, HTTP 요청 헤더, payload 등 옵션 객체들
- ex) {method: “POST”, headers: { "Content-Type": "application/json" }, body: JSON.stringfy( {json형태의 데이터들}
- return은 HTTP 응답을 나타내는 Response 객체를 래핑한 Promise 객체 반환
- Response 객체는 HTTP 응답상태(status), HTTP 응답헤더(headers), HTTP 응답전문(body) 등을 읽어올 수 있다.
- 예시
- fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => console.log(response))
- 자바스크립트에서 서버에 AJAX 통신하는 함수, axios와 달리 브라우저에 내장된 함수
- JSON.stringfy(배열명)
- 배열을 JSON 포맷의 문자열로 변환
- const json = JSON.stringfy(배열명);
- JSON.parse(배열명)
- JSON 포맷의 문자열을 배열로 변환
- const parsed = JSON.parse(json명);
- 타입은 객체이다.
- 역직렬화 상세 뜯어보기
- 예시 ({userId: 1, id: 1, title: ‘~~~’} 형태로 응답)
-
fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((json) => console.log(json))
- fetch 함수에서 주어진 URL에서 데이터를 가져오는 HTTP 요청을 보낸다. 네트워크 요청 수행 후 비동기로 데이터를 가져온다. (Promise 객체 반환)
- then()은 비동기 작업이 성공적으로 완료되었을 때 또는 이행(resolve)되었을 때 실행할 콜백 함수를 등록하는 데 사용한다.
- 그러므로 then() response 부분은 첫 번째 Promise가 이행됐을 때 실행(서버로부터의 응답 처리)
- response.json()은 응답 본문을 JSON 형식으로 파싱하는 데 사용한다. 이 또한 새로운 Promise를 반환
- then() json 부분은 두 번째 Promise가 이행됐을 때 실행된다. 이는 이전 단계에서 파싱된 JSON 데이터를 받아서 콘솔에 출력한다.
-
- 예시 ({userId: 1, id: 1, title: ‘~~~’} 형태로 응답)
- fetch() 이용
- GET 방식
- GET은 보낼 데이터가 없기 때문에 headers와 body 옵션이 필요 없다.
- 예시
-
// GET 예시 fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((data) => console.log(data));
- POST 방식
- fetch(url, {method, headers, body}) 형태
- method: HTTP 요청 메서드
- headers: HTTP 헤더
- “Content-Type”
- HTTP 메시지에 담겨 보내는 데이터의 형식을 알려주는 헤더이다.
- “Content-Type”: “application/json” = JSON 형태로 데이터를 보내준다
- “Content-Type”
- body: payload 작성
- payload
- 전송되는 데이터를 의미
- JSON.stringfy({키: 값,키2: 값2, …}) 의 형태로 데이터를 담는다.
- payload
- 예시
-
// POST 예시 fetch("https://jsonplaceholder.typicode.com/posts", { method: "POST", // JSON 포맷 지정 headers: { "Content-Type": "application/json", }, // body안에 payload (json의 키와 값 지정) body: JSON.stringify({ title: "Test", body: "testing check check", userId: 1, }), }) .then((response) => response.json()) .then((data) => console.log(data));
- fetch(url, {method, headers, body}) 형태
- PUT 방식
- json 값의 update (완전 교체)
- 예시
-
// PUT 예시 fetch("https://jsonplaceholder.typicode.com/posts/1", { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ title: "일부 수정", userId: 1, }), }) .then((response) => response.json()) .then((data) => console.log(data));
- PATCH 방식
- json 값의 일부 수정 (부분 교체)
- 예시
-
// PATCH 예시 fetch("https://jsonplaceholder.typicode.com/posts/1", { method: "PATCH", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ title: "변경", body: "일부 변경 됩니다." }), }) .then((response) => response.json()) .then((data) => console.log(data));
- DELETE 방식
- delete 방식은 보낼 데이터가 없기 때문에 headers와 body 옵션은 필요 없다.
- 예시
-
fetch("https://jsonplaceholder.typicode.com/posts/1", { method: "DELETE", }) .then((response) => response.json()) .then((data) => console.log(data));
- GET 방식
- 데이터 json 형식으로 받는 스크립트 코드 작성
- 예시
-
<script> function onLogin() { let inputID = document.getElementsByName("username"); let inputPW = document.getElementsByName("password"); // null check if (!inputID[0].value) { alert('아이디를 입력하세요.'); return; } // fetch(): JS6에서 서버에 AJAX 통신하는 함수 fetch("http://localhost:8080/api/v1/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ // 객체를 문자열로 만들어준다. username: inputID[0].value, password: inputPW[0].value }) }) .then((response) => { console.log(response); return response.json(); }) .then((json) => { // { status: "ok", message: "로그인되었습니다." } console.log(json); document.getElementById("result_status").innerText = json.status; document.getElementById("result_message").innerText = json.message; }) .catch((error) => { console.log(error); }) } </script>
- document.getElementById(”id명”)
- HTML에서 해당 id 명을 가진 요소를 찾는 역할
- innerText
- 해당 id 명의 텍스트 콘텐츠를 나타낸다.
- = 변경할 텍스트값 으로 해당 id 명의 텍스트 값을 변경할 때 사용
- 만약에 값이 숫자라면 innerText 대신에 value로 사용
- ex) const number1 = document.getElementById("number1").value;
- document.getElementById(”id명”)
그래서 결국 Rest API 구현 순서는?
- ViewController와 ApiController는 따로 나눠서 생성한다.
- ViewController
- 클래스에 @Controller 어노테이션을 준다.
- main 출력같이 뷰로 이동하는(return 값으로 html을 주는!) 메서드를 구성한다. (Model과 @Getmapping 사용)
- ApiController
- 클래스에 @RestController 어노테이션을 준다.
- JSON 형태의 값을 return 하는 메서드를 구성한다. (@PostMapping 사용)
- 예시로 return "{\\"count\\": " + counter.getCount() + "}"; 같이 JSON 형태로 문자열을 만들어서 return 해야한다.
- ViewController
- html에서 fetch() 함수를 작성한다.
- 위의 fetch() 작성 참고하여 작성
728x90
'Back-end > Spring Boot' 카테고리의 다른 글
[Spring DB] Repository (JPA, JPQL, Native SQL) (0) | 2024.04.06 |
---|---|
[Spring Boot] Devtools, LocaleResolver(다국어 처리) (0) | 2024.04.03 |
[Spring Boot] 데이터 전달, Param 값 받기, ArrayList (0) | 2024.03.31 |
[Spring Boot] Thymeleaf, redirect/forward (0) | 2024.03.31 |
[Spring Boot] Request Mapping의 종류, @RequestParam (0) | 2024.03.31 |