[게시판]8. 글쓰기 / 게시판 기능 사진

gov's avatar
Nov 19, 2024
[게시판]8. 글쓰기 / 게시판 기능 사진
  1. cs 만들기
    1. id와 createdAt 수정 불가 설정 : readonly="true”
      {{> layout/header}} <section> <!-- name에 적어야 값이 넘어간다 --> <form action="/board/{{model.id}}/update" method="post" enctype="application/x-www-form-urlencoded"> <input type="text" value="{{model.id}}" readonly="true"><br> <input type="text" name="title" value="{{model.title}}"><br> <input type="text" name="content" value="{{model.content}}"><br> <input type="text" value="{{model.createdAt}}" readonly="true"><br> <button type="submit">글쓰기</button> </form> </section> </body> </html>
  1. 컨트롤러
    1. update: 실제 게시글을 수정하는 요청을 처리
      updateForm: 수정 화면을 사용자에게 보여주기
      @GetMapping("/board/{id}/update-form") public String updateForm(@PathVariable("id") int id, Model model) { BoardResponse.UpdateFormDTO updateFormDTO = boardService.게시글수정화면보기(id); model.addAttribute("model", updateFormDTO); return "update-form"; } @PostMapping("/board/{id}/update") public String update(@PathVariable("id") int id, BorderRequest.UpdateDTO updateDTO) { boardService.게시글수정하기(id, updateDTO); return "redirect:/board/" + id ; }
  1. DTO
    1. @Data public static class UpdateDTO { private String title; private String content; }
  1. 서비스
    1. public BoardResponse.UpdateFormDTO 게시글수정화면보기(int id) { Board board = boardRepository.findById(id); // 바로 return 불가능>DTO return new BoardResponse.UpdateFormDTO(board); }
      @Transactional // commit or rollback public void 게시글수정하기(int id, BorderRequest.UpdateDTO updateDTO) { // 서비스와 컨트롤러는 1대1 매칭 (서비스 여러개 때려도 돌아는 감) // updateDTO 에서 데이터 꺼내고 다시 적용 -객체 간 캡슐화와 무결성 지킴 boardRepository.update(id, updateDTO.getTitle(), updateDTO.getContent()); }
  1. 리포지토리
    1. public void update(int id, String title, String content) { Query q = em.createNativeQuery("update board_tb set title =?, content =? where id =?"); q.setParameter(1, title); q.setParameter(2, content); q.setParameter(3, id); q.executeUpdate(); // insert, update, delete SQL쿼리문 실행 -안적으면 수정 적용 안됨 }
 

최종 게시판 기본 구현

  • 메인
    • notion image
  • 글상세보기
    • notion image
  • 수정
    • notion image
  • 글쓰기
    • notion image
Share article

goho