코딍코딍
코딩기록
코딍코딍
전체 방문자
오늘
어제
  • 분류 전체보기 (271)
    • 개발 (2)
    • Java (1)
    • 스프링 (28)
    • JPA (11)
    • Git (3)
    • 알고리즘 (160)
      • 백준 (132)
      • 프로그래머스 (8)
      • SWEA (20)
    • 토이 프로젝트 (14)
      • 간단한 Springboot CRUD (1)
      • 게시판 프로젝트 (13)
    • 알고리즘 개념정리 (8)
    • 오류 해결 (13)
    • 보류 (0)
    • AWS (5)
    • 트러블 슈팅 (0)
    • 회고 (3)
    • CS (4)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

최근 글

티스토리

hELLO · Designed By 정상우.
코딍코딍

코딩기록

토이 프로젝트/게시판 프로젝트

9. 게시판 프로젝트 - 게시판 뼈대, 글 등록 구현

2022. 8. 11. 20:26

현재까지 Member에 관련된 기능만 구현하였다. 이제 board에 관련된 기능도 구현하겠다.

일단 게시판의 기본 틀을 만들기 위해 Repository, Service, Controller부터 구현한 뒤에 View를 만들었다. Model은 이전에 만들어두었다.

기본 틀만 만든 것이므로 많이 부족하다.

 

BoardRepository

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

 

BoardService

@Service
@RequiredArgsConstructor
@Transactional
public class BoardService {
    private final BoardRepository boardRepository;

    public Long saveBoard(Board board) {
        return boardRepository.save(board).getId();
    }

    @Transactional(readOnly = true)
    public List<Board> findAll() {
        return boardRepository.findAll();
    }
}
  • 게시글 저장, 게시글 리스트 반환 기능

 

BoardDto

@Data
@NoArgsConstructor
public class BoardDto {
    private Long id;
    private String title;
    private String content;
    private String createdBy;
    private Long countVisit;

    @Builder
    public BoardDto(String title, String content, String createdBy, Long countVisit) {
        this.title = title;
        this.content = content;
        this.createdBy = createdBy;
        this.countVisit = countVisit;
    }
    public BoardDto(Board board) {
        id = board.getId();
        title = board.getTitle();
        content = board.getContent();
        createdBy = board.getCreatedBy();
        countVisit = board.getCountVisit();
    }
    public Board toEntitiy() {
        return Board.builder()
                .title(title)
                .content(content)
                .createdBy(createdBy)
                .countVisit(countVisit).build();
    }
}
  • 컨트롤러와 뷰가 데이터를 주고받을 때 엔티티인 Board를 넘기지 않고 BoardDto를 주고받는다.

 

BoardController

@Controller
@RequiredArgsConstructor
@RequestMapping("/board")
public class BoardController {
    private final BoardService boardService;
    private final MemberService memberService;

    @GetMapping("/create")
    public String createBoard() {
        return "board/createBoardForm";
    }

    @PostMapping("/create") //리팩터링 필요할듯
    public String create(@ModelAttribute BoardDto boardDto,
                         @SessionAttribute(name=SessionConst.LOGIN_MEMBER, required = false) MemberDto loginMemberDto) {
        Board board = boardDto.toEntitiy();
        board.setCountVisit(1L);
        board.setCreatedBy(loginMemberDto.getLoginId());

        Member findMember = memberService.findOne(loginMemberDto.getId());
        board.createBoard(findMember); //연관관계 설정

        boardService.saveBoard(board);
        memberService.updateMember(findMember);
        return "redirect:/board/boardList";
    }

    @GetMapping("/boardList")
    public String boardList(Model model) {
        model.addAttribute("boards", boardService.findAll());
        return "/board/boardList";
    }
}
  • createBoard(): 게시글을 작성하는 폼으로 이동
  • create(): 게시글 생성
    • 현재 로그인 한 사용자를 담고있는 세션의 MemberDto를 가져와 Member 엔티티를 꺼내 연관관계 설정 후 새로운 Board등록 및 Member 갱신
  • boardList() : 모든 게시글을  찾아와 모델에 저장하고 게시글 리스트로 이동.

 

createBoardForm.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
    <title>게시판</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>

    <link href="../../static/css/bootstrap.min.css"
          th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link href="../../static/css/headers.css"
          th:href="@{/css/headers.css}" rel="stylesheet">
    <script src="../../static/js/bootstrap.min.js"
            th:src="@{/js/bootstrap.min.js}"></script>
    <style>
        .fakeimg {
            height: 200px;
            background: #aaa;
        }
    </style>
</head>
<body>

<!--<div class="jumbotron text-center" style="margin-bottom:0">-->
<!--    <h1>게시판</h1>-->
<!--</div>-->

<main>
    <header class="d-flex flex-wrap align-items-center justify-content-center justify-content-md-between py-3 mb-4 border-bottom">
        <a href="/" class="d-flex align-items-center col-md-3 mb-2 mb-md-0 text-dark text-decoration-none">
            <svg class="bi me-2" width="40" height="32" role="img" aria-label="Bootstrap"><use xlink:href="#bootstrap"></use></svg>
        </a>

        <ul class="nav col-12 col-md-auto mb-2 justify-content-center mb-md-0">
            <li><a href="/index.html" class="nav-link px-2 link-secondary">Home</a></li>
            <li><a href="#" class="nav-link px-2 link-dark">게시판</a></li>
            <li><a href="#" class="nav-link px-2 link-dark">About</a></li>
        </ul>

        <div class="col-md-3 text-end">
            <button type="button" class="btn btn-outline-primary me-2" onclick="location.href='/member/logout'">로그아웃</button>
        </div>
    </header>
</main>

<div class="container" style="margin-top:30px">
    <div class="row">
        <div class="col-sm-12">
            <h2>글쓰기</h2>
            <!--            enctype="multipart/form-data"-->
            <form action="boardForm.html" th:action method="post">
                <div class="form-group">
                    <input type="text" class="form-control" id="title" name = "title">
                </div>
                <div class="form-group">
                    <input type="file" class="form-control-file border" name="file">
                </div>
                <div class="form-group">
                    <textarea class="form-control" rows="5" id="content" name = "content"></textarea>
                </div>
                <button type="submit" class="btn btn-primary">글쓰기</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

 

boardList.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>게시판</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>

    <!-- Bootstrap core CSS -->
    <link href="../../static/css/bootstrap.min.css"
          th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link href="../../static/css/headers.css"
          th:href="@{/css/headers.css}" rel="stylesheet">
    <link href="../../static/css/bootstrap.css"
          th:href="@{/css/bootstrap.css}" rel="stylesheet">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <style>
        .bd-placeholder-img {
            font-size: 1.125rem;
            text-anchor: middle;
            -webkit-user-select: none;
            -moz-user-select: none;
            user-select: none;
        }

        @media (min-width: 768px) {
            .bd-placeholder-img-lg {
                font-size: 3.5rem;
            }
        }
    </style>
    <!-- Custom styles for this template -->

    <link href="../../static/css/headers.css"
          th:href="@{/css/headers.css}" rel="stylesheet">
    <script src="../../static/js/bootstrap.bundle.min.js"
            th:src="@{/js/bootstrap.bundle.min.js}"></script>
    <script src="../../static/js/bootstrap.bundle.js"
            th:src="@{/js/bootstrap.bundle.js}"></script>
    <script src="../../static/js/bootstrap.js"
            th:src="@{/js/bootstrap.js}"></script>
</head>
<body>
<main>
    <header class="d-flex flex-wrap align-items-center justify-content-center justify-content-md-between py-3 mb-4 border-bottom">
        <a href="/" class="d-flex align-items-center col-md-3 mb-2 mb-md-0 text-dark text-decoration-none">
            <svg class="bi me-2" width="40" height="32" role="img" aria-label="Bootstrap"><use xlink:href="#bootstrap"></use></svg>
        </a>

        <ul class="nav col-12 col-md-auto mb-2 justify-content-center mb-md-0">
            <li><a href="/index.html" class="nav-link px-2 link-secondary">Home</a></li>
            <li><a href="#" class="nav-link px-2 link-dark">게시판</a></li>
            <li><a href="#" class="nav-link px-2 link-dark">About</a></li>
        </ul>

        <div class="col-md-3 text-end">
            <button type="button" class="btn btn-outline-primary me-2" onclick="location.href='/member/logout'">로그아웃</button>
        </div>
    </header>
</main>

<div class="container">
    <table class="table table-hover">
        <h3>게시판</h3>
        <!--th:value="${param.searchText}"-->
        <form class="form-inline d-flex justify-content-end" method="GET", th:action="@{/board/boardList}" >
            <div class="form-group mx-sm-3 mb-2 pull-right">
                <label for="searchText" class="sr-only">검색</label>
                <input type="text" class="form-control" id="searchText" name="searchText">
                <button type="submit" class="btn btn-primary mb-2">검색 </button>
            </div>
        </form>
        <thead>
        <tr>
            <th>번호</th>
            <th>제목</th>
            <th>작성자</th>
            <th>날짜</th>
            <th>조회수</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="board : ${boards}">
            <td><a th:href="@{'/board/boardContent/' + ${board.id}}"><span th:text="${board.id}"></span></a></td>
            <td th:text="${board.title}"></td>
            <td th:text="${board.createdBy}"></td>
            <td th:text="${board.createdDate}"></td>
            <td th:text="${board.countVisit}"></td>
        </tr>
        </tbody>
    </table>

    <hr/>
    <button type="button" class="btn btn-default pull-right" onclick="location.href='/board/create'">글쓰기</button>

    <!--<div class="center text-center">
        <nav aria-label="Page navigation example">
            <ul class="pagination justifiy-content-center" th:if="${totalPage != 0}">
                <li class="page-item"><a class="page-link" th:href="@{/board/boardList(page=${boards.pageable.pageNumber - 1}, searchText=${param.searchText})}">Previous</a></li>
                <li class="" th:classappend="${page == boards.pageable.pageNumber + 1} ? 'disabled'" th:each="page : ${#numbers.sequence(startPage, endPage)}">
                    <a th:href="@{/board/boardList(page=${page - 1}, searchText=${param.searchText})}" th:text="${page}"></a>
                </li>
                <li class="page-item"><a class="page-link" th:href="@{/board/boardList(page=${boards.pageable.pageNumber + 1}, searchText=${param.searchText})}">Next</a></li>
            </ul>
        </nav>
    </div>-->

</div>
<div  class="text-center">
    <ul class="pagination">

    </ul>
</div>
</body>
</html>

 

 

boardList.html
createBoardForm.html

 

'토이 프로젝트 > 게시판 프로젝트' 카테고리의 다른 글

11. 게시판 프로젝트 - 댓글 작성  (0) 2022.08.14
10. 게시판 프로젝트 - 글 조회, 조회수, 글 수정, welcomePage  (0) 2022.08.12
8. 게시판 프로젝트 - 로그아웃, 회원 정보 수정  (0) 2022.08.11
7. 게시판 프로젝트 - BaseTimeEntity, MemberDto  (0) 2022.08.11
6. 게시판 프로젝트 - 인터셉터 등록, 회원가입 폼 중복 ID 검증  (0) 2022.08.10
    '토이 프로젝트/게시판 프로젝트' 카테고리의 다른 글
    • 11. 게시판 프로젝트 - 댓글 작성
    • 10. 게시판 프로젝트 - 글 조회, 조회수, 글 수정, welcomePage
    • 8. 게시판 프로젝트 - 로그아웃, 회원 정보 수정
    • 7. 게시판 프로젝트 - BaseTimeEntity, MemberDto
    코딍코딍
    코딍코딍
    ㅎ2

    티스토리툴바