REST API

Mkim4·2024년 4월 21일

Controller 클래스

  1. restController 로 사용하겠습니다. -> @RestController
    1-1. @RequestMapping("/api-board")
  2. private final BoardService boardService; ->의존성 주입
  3. 생성자 생성
private final BoardService boardService; //의존성 주입

//생성자 생성
public BoardRestController(BoardService boardService){
	this.boardService = boardService;
}

생성자가 하나밖에 없으면 알아서 @Autowired 의존성 주입이 되기 때문에 굳이 적어주지 않아도된다.

spring에서 클래스에 대한 종속성을 자동으로 연결하는데 사용되는 주석이다.
클래스의 주입해야하는 종속성이 있는 경우 @Autowired를 사용하여 적절한 bean을 찾아 주입하도록 spring에 알릴 수 있다.

참고만 하길

위 처럼 UserService라는 클래스에 UserRepository를 주입해야할때 @Autowired를 이용하면 spring은 UserRepository 유형의 bean에 대한 application context를 검색한 다음 UserService에 주입시킨다.
즉 @AutoWired를 사용하면 자동 종속성 주입을 허용하여 코드의 양을 줄여주는 spring의 기능이다.

게시글 전체 조회

@GetMapping("/board")
public ResponseEntity<?> list(){
	List<Board> list = boardService.getBoardList(); //전체조회
	return new ResponseEntity<List<Board>>(list, HttpStatus.OK);
}

게시글 (검색) 조회

@GetMapping("/board")
public ResponseEntity<?> list(@ModelAttribute SearchCondition condition){
	List<Board> list = boardService.search(condition); //검색조회
    if(list == null || list.size() == 0){
    	return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
    }
	return new ResponseEntity<List<Board>>(list, HttpStatus.OK);
}

게시글 상세 보기

@GetMapping("/board/{id}")
public ResponseEntity<Board> detail(@PathVariable("id") int id){
	Board board = boardService.readBoard(id); //조회수도 하나 증가하더라!
    //가져왔는데 board가 null이면 예외처리를 해줘라! 404 처리
	return new ResponseEntity<Board>(board,HttpStatus.OK);
}

게시글 등록(Form 형식으로 넘어왔을 때)

@PostMapping("/board")
public ResponseEntity<?> write(@ModelAttribute Board board){
 	//등록한 게시글을 보냈는데
	boardService.writeBoard(board);
    //등록이 되어있는지 눈으로 Talend API에서 보려고 이렇게 보낸거지
    //실제로 프론트에게 보낼 때는 크게 의미는 없다.
    //ID만 보내서 디테일 쏘던지 바로 목록으로가면 필요없다!
    //insert, update, delete -> 반환값이 int형의 값이 넘어온다.(바뀐 행의 개수가 반환됨)
    return new ResponseEntity<Board>(board,HttpStatus.CREATED);
}

게시글 수정

@PutMapping("/board/{id}")
public ResponseEntity<Void> update(@PathVariable("id) int id, @RequestBody Board board){
	board.setIDd(id);
    boardService.modifyBoard(board); //id를 따로 보내왔다면 바구니(DTO)에 넣어놓고 보내자
	return new ResponseEntity<Void>(HttpStatus.OK);
}

게시글 삭제

@DeleteMapping("/board/{id}")
public ResponseEntity<Void> delete(@PathVariable("id") int id){
	//반환값에 따라서 실제로 지워졌는지 or 내가 없는 글을 지우려고 하지는 않는지...
    //등의 상황에 따라 응답코드가 바뀌면 프론트에서 처리하기가 더욱 수월해지겠다.
	boardService.removeBoard(id);
    return new ResponseEntity<Void>(HttpStatus.OK);
}
profile
귀요미 개발자

0개의 댓글