티스토리 뷰

재밌어서 일주일만에 진도를 정말 많이 나간 것 같다.

 

 

package com.example.firstproject.api;

import com.example.firstproject.dto.ArticleForm;
import com.example.firstproject.entity.Article;
import com.example.firstproject.repository.ArticleRepository;
import com.example.firstproject.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
public class ArticleApiController {
    @Autowired
    private ArticleService articleService; //서비스 객체 주입
//    @Autowired //의존성 주입 (게시글 리파지터리 주입)
//    private ArticleRepository articleRepository;
    //GET
    @GetMapping("/api/articles") //URL 요청 접수
    public List<Article> index(){ //index()메서드 정의
        return articleService.index();
    }

    @GetMapping("/api/articles/{id}")
    public Article show(@PathVariable Long id){
        return articleService.show(id);
    }

    //POST
    @PostMapping("/api/articles")
    public ResponseEntity<Article> create(@RequestBody ArticleForm dto){
        Article created = articleService.create(dto);
        return (created != null) ?
                ResponseEntity.status(HttpStatus.OK).body(created) :
                ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    //PATCH
    @PatchMapping("/api/articles/{id}")
    public ResponseEntity<Article> update(@PathVariable Long id,
                                          //Article을 ResponseEntity에 담아서 반환해야만 반환하는 데이터에 상태코드를 실어보낼 수 있으므로
                          @RequestBody ArticleForm dto){
        Article updated = articleService.update(id, dto); // 서비스를 통해 게시글 수정
        return (updated != null) ? //updated에 내용이 있다면
                ResponseEntity.status(HttpStatus.OK).body(updated):
                ResponseEntity.status(HttpStatus.BAD_REQUEST).build();

    }//컨트롤러는 컨트롤러의 역할만. 컨트롤러는 서비스에 무슨 지시를 하고 무슨 데이터를 받아 오는지만 알면 됨. 실제 작업은 서비스에 맡김.

    //DELETE
    @DeleteMapping("/api/articles/{id}")
    public ResponseEntity<Article> delete(@PathVariable Long id){
        Article deleted = articleService.delete(id);
        return (deleted != null) ?
                ResponseEntity.status(HttpStatus.NO_CONTENT).build() :
                ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    @PostMapping("/api/transaction-test") //여러 게시글 생성 요청 접수
    public ResponseEntity<List<Article>> transactionTest
            (@RequestBody List<ArticleForm> dtos){
        List<Article> createdList = articleService.createArticles(dtos); //서비스 호출
        return (createdList != null) ?
                ResponseEntity.status(HttpStatus.OK).body(createdList) :
                ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }
}

articleapicontroller. 그냥 컨트롤러와는 다르게 웹 뿐만 아니라 안드로이드나 등등 다른 매체에도 데이터 전달이 가능하다.

이는 웹 페이지를 전달하는 게 아니라 데이터를 전달하기 때문.

 

package com.example.firstproject.api;

import com.example.firstproject.dto.CommentDto;
import com.example.firstproject.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class CommentApiController {
    @Autowired
    private CommentService commentService;
    //1.댓글 조회
    @GetMapping("/api/articles/{articleId}/comments") //댓글 조회 요청 접수
    public ResponseEntity<List<CommentDto>> comments(@PathVariable Long articleId){ //CommentDto인 이유를 모르겠음
        //서비스에 위임
        List<CommentDto> dtos = commentService.comments(articleId); //해당 게시글의 id를 알아야 해당 게시글의 댓글을 가져올 수 있기 때문
        //결과 응답
        return ResponseEntity.status(HttpStatus.OK).body(dtos);
    }
    //2.댓글 생성
    //3.댓글 수정
    //4.댓글 삭제
}

 

 

댓글 기능도 작성중... 

comment에서 댓글 조회할 땐 왜 엔티티에서 DTO로 변환하는지... 를 잘 모르겠어서 이 부분을 더 깊이 공부해볼 생각.

 

 

 

웹 페이지를 화면에 보여주고(view)
클라이언트 요청을 받아 처리하고(Controller)
데이터를 관리하는(Model)
--> MVC 패턴

컨트롤러가 클라이언트의 요청을 받고, 뷰가 최종페이지를 만들고, 모델이 최종 페이지에 쓰일 데이터를 뷰에 전달

컨트롤러에서 폼 데이터를 받을 때 DTO에 담아 받음

jdbc:h2:mem:c1bff1c8-d4f9-4a8f-bd71-797daab7ab08

168페이지 정독하기

 

 

그리고 특히 저번 스프링 입문 강의와는 다른점이 post방식으로 받을 때 dto라는 클래스를 만들어주는데, 

package com.example.firstproject.dto; //컨트롤러에서 폼 데이터를 받을 때 DTO에 담아 받음

import com.example.firstproject.entity.Article;
import lombok.AllArgsConstructor;
import lombok.ToString;

@AllArgsConstructor
@ToString
public class ArticleForm {
    private Long id;
    private String title; //제목을 받을 필드
    private String content; //내용을 받을 필드

    //전송받은 제목과 내용을 필드에 저장하는 생성자 추가
//    public ArticleForm(String title, String content) {
//        this.title = title;
//        this.content = content;
//    }

//    //데이터를 잘 받았는지 확인할 toString()메서드 추가
//    @Override
//    public String toString() {
//        return "ArticleForm{" +
//                "title='" + title + '\'' +
//                ", content='" + content + '\'' +
//                '}';
//    }

    public Article toEntity() {
        return new Article(id, title, content);
    }
}

 

 

이게 article dto.로 //컨트롤러에서 폼 데이터를 받을 때 DTO에 담아 받음

 

 

package com.example.firstproject.dto;

import com.example.firstproject.entity.Comment;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.web.bind.annotation.GetMapping;

@AllArgsConstructor
@NoArgsConstructor
@Getter
@ToString
public class CommentDto {
    private Long id;
    private Long articleId;
    private String nickname;
    private String body;

    public static CommentDto createCommentDto(Comment comment) { //public static: 객체 생성 없이 호출 가능한 메서드 (생성 메서드)
        return new CommentDto( //메서드의 반환 값이 댓글 DTO가 되도록 CommentDto의 생성자 호출
                comment.getId(), //댓글 엔티티의 id
                comment.getArticle().getId(), //댓글 엔티티가 속한 부모 게시글의 id
                comment.getNickname(), //댓글 엔티티의 nickname
                comment.getBody() //댓글 엔티티의 body
        );
    }
}

 

 

아직 다 완성되진 않은 댓글 dto.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함