[Practice] 공지사항 게시판 목록에 대한 요청 API 만들기 (13)
2021. 4. 12. 16:30ㆍSpring/Practice
1. 문제
- REST API 형식으로 구현
- HTTP METHOD는 PUT
- 요청 주소는 "/api/notice/1" (1은 공지사항의 글ID로 동적으로 변함)
- 전달되는 값은 application/json 형식의 공지사항 글ID, 제목, 내용을 입력받음
- 공지사항 수정일은 현재시간을 저장, 공지사항 조회수와 좋아요수는 변하지 않음
- 데이터를 수정한 경우에는 Data 매핑에 대한 Entity로 필요없는 항목까지 받지 않고 필요한 데이터만 입력받도록 작성
- 공지사항의 글이 존재하지 않을 경우 예외사항을 발생
- 예외처리는 ExceptionHandler를 통해 구현하고, 발생하는 예외에 대해서는 400, 예외 메시지를 리턴
2. 풀이
- NoticeNotFoundException.java
package com.example.jpa.sample.notice.exception;
public class NoticeNotFoundException extends RuntimeException {
public NoticeNotFoundException(String message) {
super(message);
}
}
- ApiNoticeControlelr.java
package com.example.jpa.sample.notice.controller;
import com.example.jpa.sample.notice.entity.Notice;
import com.example.jpa.sample.notice.exception.NoticeNotFoundException;
import com.example.jpa.sample.notice.model.NoticeInput;
import com.example.jpa.sample.notice.repository.NoticeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.swing.text.html.Option;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@RequiredArgsConstructor
@RestController
public class ApiNoticeController {
private final NoticeRepository noticeRepository;
/*
// 문제 6
@GetMapping("/api/notice")
public String noticeString() {
return "공지사항입니다.";
}
*/
/*
// 문제 7
@GetMapping("/api/notice")
public NoticeModel notice() {
LocalDateTime regDate = LocalDateTime.of(2021, 1, 1, 0, 0);
NoticeModel notice = new NoticeModel();
notice.setId(1);;
notice.setTitle("공지사항입니다.");
notice.setContents("공지사항 내용입니다.");
notice.setRegDate(regDate);
return notice;
}
*/
/*
// 문제 8
@GetMapping("/api/notice")
public List<NoticeModel> notice() {
List<NoticeModel> noticeList = new ArrayList<>();
noticeList.add(NoticeModel.builder()
.id(1)
.title("공지사항입니다.")
.contents("공지사항 내용입니다.")
.regDate(LocalDateTime.of(2021, 1, 1, 0, 0))
.build()
);
noticeList.add(NoticeModel.builder()
.id(2)
.title("두번째 공지사항입니다.")
.contents("두번째 공지사항 내용입니다.")
.regDate(LocalDateTime.of(2021, 1, 2, 0, 0))
.build()
);
return noticeList;
}
*/
// 문제 9
@GetMapping("/api/notice")
public List<NoticeInput> notice() {
List<NoticeInput> noticeList = new ArrayList<>();
// return null;
return noticeList;
}
// 문제 10
@GetMapping("/api/notice/count")
public int noticeCount() {
// return "10";
return 10;
}
/*
// 문제 11
@PostMapping("/api/notice")
public NoticeModel addNotice(@RequestParam String title, @RequestParam String contents) {
NoticeModel notice = NoticeModel.builder()
.id(1)
.title(title)
.contents(contents)
.regDate(LocalDateTime.now())
.build();
return notice;
}
*/
/*
// 문제 12
@PostMapping("/api/notice")
public NoticeModel addNotice(NoticeModel noticeModel) {
noticeModel.setId(2);
noticeModel.setRegDate(LocalDateTime.now());
return noticeModel;
}
*/
/*
// 문제 13
@PostMapping("/api/notice")
public NoticeModel addNotice(@RequestBody NoticeModel noticeModel) {
noticeModel.setId(3);
noticeModel.setRegDate(LocalDateTime.now());
return noticeModel;
}
*/
/*
// 문제 14
@PostMapping("/api/notice")
public Notice addNotice(@RequestBody NoticeInput noticeInput) {
Notice notice = Notice.builder()
.title(noticeInput.getTitle())
.contents(noticeInput.getContents())
.regDate(LocalDateTime.now())
.build();
return noticeRepository.save(notice);
}
*/
// 문제 15
@PostMapping("/api/notice")
public Notice addNotice(@RequestBody NoticeInput noticeInput) {
Notice notice = Notice.builder()
.title(noticeInput.getTitle())
.contents(noticeInput.getContents())
.regDate(LocalDateTime.now())
.hits(0)
.likes(0)
.build();
return noticeRepository.save(notice);
}
// 문제 16
@GetMapping("/api/notice/{id}")
public Notice getNotice(@PathVariable long id) {
return noticeRepository.findById(id).orElseThrow(null);
}
/*
// 문제 17
@PutMapping("/api/notice/{id}")
public void updateNotice(@PathVariable long id, @RequestBody NoticeInput noticeInput) {
Optional<Notice> notice = noticeRepository.findById(id);
if(notice.isPresent()) {
notice.get().setTitle(noticeInput.getTitle());
notice.get().setContents(noticeInput.getContents());
notice.get().setUpdateDate(LocalDateTime.now());
noticeRepository.save(notice.get());
}
}
*/
@ExceptionHandler(NoticeNotFoundException.class)
public ResponseEntity<String> handlerNoticeNotFoundException(NoticeNotFoundException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
// 문제 18
@PutMapping("/api/notice/{id}")
public void updateNotice(@PathVariable long id, @RequestBody NoticeInput noticeInput) {
Optional<Notice> notice = noticeRepository.findById(id);
if(!notice.isPresent()) {
throw new NoticeNotFoundException("공지사항의 글이 존재하지 않습니다.");
}
notice.get().setTitle(noticeInput.getTitle());
notice.get().setContents(noticeInput.getContents());
notice.get().setUpdateDate(LocalDateTime.now());
noticeRepository.save(notice.get());
}
}
- 응용
@RequiredArgsConstructor
@RestController
public class ApiNoticeController {
private final NoticeRepository noticeRepository;
...
@ExceptionHandler(NoticeNotFoundException.class)
public ResponseEntity<String> handlerNoticeNotFoundException(NoticeNotFoundException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
// 문제 18
@PutMapping("/api/notice/{id}")
public void updateNotice(@PathVariable long id, @RequestBody NoticeInput noticeInput) {
Notice notice = noticeRepository.findById(id).orElseThrow(() -> new NoticeNotFoundException("공지사항의 글이 존재하지 않습니다."));
notice.setTitle(noticeInput.getTitle());
notice.setContents(noticeInput.getContents());
notice.setUpdateDate(LocalDateTime.now());
noticeRepository.save(notice);
}
}
728x90
'Spring > Practice' 카테고리의 다른 글
[Practice] 공지사항 게시판 목록에 대한 요청 API 만들기 (15) (0) | 2021.04.12 |
---|---|
[Practice] 공지사항 게시판 목록에 대한 요청 API 만들기 (14) (0) | 2021.04.12 |
[Practice] 공지사항 게시판 목록에 대한 요청 API 만들기 (12) (0) | 2021.04.12 |
[Practice] 공지사항 게시판 목록에 대한 요청 API 만들기 (11) (0) | 2021.04.12 |