티스토리 뷰

반응형

✏️ 게시물 등록 로직

  1. 게시물 등록 화면에서 게시물의 제목과 내용을 입력할 수 있고 작성자는 화면에 띄어줌
  2. 제목과 내용을 입력하면 컨트롤러가PostDTO를 통해 내용을 받아옴
  3. 컨트롤러는 로그인 상태를 확인하고 로그인이 되어있다면 BoardService를 호출하여 게시물을 db에 저장
  4. boardService는 컨트롤러로부터 받은 id가 Member DB에 있는지 검사 후 있다면 Board DB에 게시물을 저장하고 id가 Member DB에 없다면 게시글을 등록하지 않는다.
  5. 게시글을 등록할 때 좋아요 수를 0으로 초기화 해준다

✏️ Board 클래스

@Getter
@Setter
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Board {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idx", nullable = false)
    private Integer idx;

    @Column(name = "title", nullable = false)
    private String title;

    @Column(name = "content", nullable = false)
    private String content;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "memberId", nullable = false)
    private Member member;

    @Column(name = "likeCount", nullable = false)
    private Integer likeCount;
}

Board db구조와 동일하다


✏️ PostDTO 클래스

@Getter
@Setter

public class PostDTO {
    private String title;
    private String content;
}

글 쓰기 입력 창에서 입력하면 PostDTO를 통해 받아온다


✏️ post.html 생성

<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link rel="stylesheet" href="main.css">
</head>
<body>
<th:block>
    <div>
        <h2>새 글 작성</h2>
        <form method="post" action="/member/post">
            <div>
                <label for="title">제목</label>
                <input title="글제목" type="text" name="title" id="title" required/>
            </div>
            <div class="content-box">
                <label>내용</label>
                <textarea id="txtArea" class="content" name="content"
                          rows="10" cols="50" required></textarea>
            </div>
            <div>
                <label>작성자 : <span th:text="${id}"></span></label>
            </div>
            <button id="save" type="submit">저장</button>
        </form>
    </div>
</th:block>
</body>
</html>

✏️ Api Controller 클래스

@PostMapping("/post") // 글 작성하기
public String post(HttpServletRequest httpServletRequest, PostDTO postDTO) {
    HttpSession session = httpServletRequest.getSession(false);
    Optional<Object> idOptional = Optional.ofNullable(session.getAttribute("userId"));
    if (idOptional.isEmpty()) {
        log.error("로그인을 하지 않으면 글을 작성할 수 없습니다.");
        return "redirect:/login";
    }

    String id = idOptional.get().toString();
    boardService.save(postDTO, id);
    log.info("성공적으로 업로드 되었습니다. 리스트 화면으로 돌아갑니다.");
    return "redirect:/member/list";
}

로그인이 되어 있는지(세션이 있는지) 검사 후에 boardService 를 호출해 작성한 글을 저장한다.

로그인이 되어 있지 않다면 로그인 화면으로 돌려보낸다


✏️ WebController 클래스

@GetMapping("/member/post")
public String post(Model model, HttpServletRequest httpServletRequest) {
    HttpSession session = httpServletRequest.getSession(false);
    Optional<Object> idOptional = Optional.ofNullable(session.getAttribute("userId"));
    if(idOptional.isEmpty()){
        log.error("권한 없음");
        return "redirect:/login";
    }
    String id = idOptional.get().toString();
    model.addAttribute("id", id);
    return "post";
}

✏️ BoardRepository 인터페이스

@Repository
public interface BoardRepository extends JpaRepository<Board, Long> {
}

Board 의 primary key는 idx로 Long 타입이다


✏️ BoardService 인터페이스

public interface BoardService {
    void save(PostDTO postDTO,String id);
}

✏️ BoardServiceImp 클래스

@Service
@RequiredArgsConstructor
@Slf4j
public class BoardServiceImp implements BoardService {
		private final BoardRepository boardRepository;
    private final MemberRepository memberRepository;

	  @Override
    public void save(PostDTO postDTO, String id) {
        Optional<Member> member = memberRepository.findById(id); // 작성자의 id가 db에 존재하는지 검사
        if (member.isPresent()) {
            Member memberEntity = member.get();
            Board board = Board.builder()
                    .title(postDTO.getTitle())
                    .content(postDTO.getContent())
                    .member(memberEntity)
                    .likeCount(0)
                    .build();
            boardRepository.save(board);
        }
    }
}

Member에 컨트롤러부터 받은 id를 가진 유저가 있는지 검사 후 있으면 글을 저장하고 없으면 저장하지 않는다.

추가로 좋아요 기능을 위해서 좋아요 숫자를 0으로 초기화 시켜준다


반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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
글 보관함