비동기 데이터 전송에 적합한 JSON 포맷을 사용하고 이미 JSON 포맷을 기본으로 지원하는
스프링의 RestController를 사용하자.
- 댓글 테이블 만들기
※ Timestamp 는 자동생성이라서 CURRENT_TIMESTAMP 붙여준다.
reply_bno 는 '레시피 게시판의 번호'라서 왜래키 설정해준다.
recipe 테이블과 참조하는법
= 맨 아래 Foregin Keys 클릭하고 reply테이블의 reply_bno 열 과 recipe테이블의 id 열 과 참조한다.
테이블에서 CASCADE 설정
1. Update 업데이트할때는 같이 업데이트 해야하니까 cascade
2. Delete 삭제할때도 게시판은 삭제됐는데 댓글만 있음 안되니까 같이 삭제하도록 cascade
replyVO
테이블의 데이터를 받아 올 때 사용할 replyVO 클래스 생성
@Data
public class ReplyVO {
/* 댓글 번호 */
private int reply_no;
/* 게시글 번호 */
private int reply_bno;
/* 댓글 내용 */
private String content;
/* 댓글 작성자 */
private String writer;
/* 댓글 등록 날짜 : AJAX JSON으로 보내기 포맷 */
@JsonFormat(pattern = "yyyy-MM-dd a hh:mm:ss")
private LocalDateTime created_at;
/* 댓글 업데이트 날짜 : AJAX JSON으로 보내기 포맷 */
@JsonFormat(pattern = "yyyy-MM-dd a hh:mm:ss")
private LocalDateTime updated_at;
/* 생성자 : reply_no와 created_at,updated_at인 날짜시간은 자동생성 */
public ReplyVO(int reply_bno, String content, String writer) {
super();
this.reply_bno = reply_bno;
this.content = content;
this.writer = writer;
}
/* 전체 변수 사용 생성자 필요 */
public ReplyVO(int reply_no, int reply_bno, String content, String writer, LocalDateTime created_at,
LocalDateTime updated_at) {
this.reply_no = reply_no;
this.reply_bno = reply_bno;
this.content = content;
this.writer = writer;
this.created_at = created_at;
this.updated_at = updated_at;
}
}
@Data = @getter @setter @ToString
@JsonFormat
: 날짜를 json 포맷(문자열)으로 전달할 수 있도록 format 설정
제이쿼리를 사용하면 AJAX를 사용가능하지만
순수JS로 사용하려면 Fetch API를 사용하여 RestController 로 보내기
Fetch API 는 쉽게 GET, POST, PUT, DELETE 하는 라이브러리
1. GET
[ Fetch-API.js ] 에서 EasHTTP 객체를 만들고
class EasyHTTP {
// GET
async get(url) {
const response = await fetch(url); // ajax 통신으로 결과 받기
const resData = await response.json(); // 결과에서 제이슨 데이터를 JS 객체로 변환
return resData; // JSON 데이터 리턴
}
}
* js 는 비동기라서 기다리지않고 코드가 한줄씩 실행이 되는데 문제는 통신의 결과를 받지않고 계속 실행돼서
await 를 써서 통신의 결과를 받는다.
[ app.js ] 에서 const http = new EasHTTP() 객체 만들기
http
.get('https://jsonplaceholder.typicode.com/users', data)
.then((data) => console.log(data)) ->js객체로 변환해서 리턴해줌
.catch((err) => console.log(err));
.get 메소드를 써서 users 데이터를 json 형태로 만들어줌
.then 가져온 데이터를 콘솔에 출력하고
.catch 에러가 있을 시 에러를 출력한다.
[ index.html ]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="#" type="image/x-icon" />
<title>JS Fetch API 예제</title>
</head>
<body>
<script src="Fetch-API.js"></script>
<script src="app.js"></script>
</body>
</html>
오른쪽 마우스 클릭 후 open with live server - 빈 창이 뜨는데 F12 누른다
즉 fetch 의 내부적 내용들을 app.js의 .get메소드로 데이터를 가져와서 콘솔에 출력했다.
2. POST
[ Fetch-API.js ]
class EasyHTTP {
async post(url, data) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json', //보내는 데이터 json 타입 선언
},
body: JSON.stringify(data), //js object(객체)를 json타입으로 변환
});
const resData = await response.json();
return resData;
}
}
[ app.js ]
const data = {
name: '길동이',
username: 'gildong',
email: 'gildong@gmail.com',
};
//새 유저 생성(js객체 데이터를 입력받아 제이슨으로 변환해서 서버에 보내고
//다시 제이슨 타입으로 결과를 받아 js객체로 변환한 결과 data)
http
.post('https://jsonplaceholder.typicode.com/users', data)
.then((data) => console.log(data))
.catch((err) => console.log(err));
.post('https://jsonplaceholder.typicode.com/users', data)
: 자바스크립트 객체 데이터안의 문자열들을 .post 메소드에 받아와서 제이슨 형태로 변환 후 서버에 보내고
.then((data) => console.log(data))
.catch((err) => console.log(err));
: 결과를 js객체로 변환하고 리턴
3. UPDATE (put)
[ Fetch-API.js ]
EasyHTTP 클래스 안에 넣기
// PUT 업데이트
async put(url, data) {
const response = await fetch(url, {
method: 'PUT',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(data),
});
const resData = await response.json();
return resData;
}
[ app.js ]
const data = {
name: '길동이',
username: 'gildong',
email: 'gildong@gmail.com',
};
//업데이트;
http
.put('https://jsonplaceholder.typicode.com/users/2', data)
.then((data) => console.log(data))
.catch((err) => console.log(err));
Id 2번을 수정한다.
4. DELETE
[ Fetch-API.js ]
EasyHTTP 클래스 안에 넣기
// DELETE 삭제
async delete(url) {
const response = await fetch(url, {
method: 'DELETE',
headers: {
'Content-type': 'application/json',
},
});
const resData = await '데이터가 삭제됨...';
return resData;
}
[ app.js ]
// 삭제
http
.delete('https://jsonplaceholder.typicode.com/users/2')
.then((data) => console.log(data))
.catch((err) => console.log(err));
id 2번 삭제됨.
'Spring boot | 쇼핑몰 만들기 | 어글리 마켓 > 홈페이지 만들기 | 고객,관리자' 카테고리의 다른 글
[레시피] 댓글 달기 기능 get (0) | 2022.06.13 |
---|---|
[레시피] 댓글 달기 기능 post (0) | 2022.06.13 |
[레시피] 주제별 검색 기능 (0) | 2022.05.30 |
[레시피] 검색 기능 구현하기 (0) | 2022.05.17 |
[레시피] 게시판 페이지네이션 view (0) | 2022.05.17 |