[홈페이지 제작] 익명 페이지 1 - 데이터 화면에 넣기

Feb 14, 2024
[홈페이지 제작] 익명 페이지 1 - 데이터 화면에 넣기
 

1. View 확인

 
notion image
 
상세보기는 없는 간단한 제목과 내용 작성자를 적고, 수정 삭제를 할 수 있는 페이지이다.
현재는 데이터 없이 View 화면만 있는 페이지다. 데이터를 추가해 화면에 출력하보자.
 
board/Board
package shop.mtcoding.blog.board; import jakarta.persistence.*; import lombok.Data; @Data //게터세터 @Entity // 이게 붙으면 테이블 생성됨 @Table(name="board_tb") // 테이블명 public class Board { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) //auto_increment private int id ; private String author ; private String title; private String content; }
 
테이블을 담을 클래스를 만든다. 테이블명은 board_tb 로 정했다.
이 테이블은 자동으로 증가하는 id 와 게시자 이름, 제목, 내용으로 이루어져 있다.
 
resources/data.sql
insert into board_tb(author,title,content) values ('홍길동','제목1','내용1'); insert into board_tb(author,title,content) values ('홍길동','제목2','내용2'); insert into board_tb(author,title,content) values ('홍길동','제목3','내용3'); insert into board_tb(author,title,content) values ('홍길동','제목4','내용4'); insert into board_tb(author,title,content) values ('홍길동','제목5','내용5');
 
Insert 쿼리문으로 더미데이터를 만든다.
 
application.yml
sql: init: data-locations: - classpath:db/data.sql
더미데이터 추가를 위해 yml 파일에 코드를 추가한다.
 
notion image
테이블이 완성되었다.

2. Controller

board/BoardController
@GetMapping("/") public String index(HttpServletRequest request,@RequestParam(defaultValue = "0")int page) { List<Board> boardList = boardRepository.findAll(page); return "index"; }
 
컨트롤러에서 데이터를 불러온다.
 

3. Repository

 
board/BoardRepository
public List<Board> findAll(int page) { final int COUNT = 5; int value = page * COUNT ; Query query = em.createNativeQuery("select * from board_tb order by id desc limit ?,?",Board.class); query.setParameter(1,value); query.setParameter(2,COUNT); List<Board> boardList = query.getResultList(); return boardList; }
 
테이블은 하나의 타입이 아니기 때문에 컬렉션의 형태로 데이터를 받는다.
쿼리문 뒤에 Board.class 를 붙이면 jpa 라이브러리가 파싱을 도와준다.
COUNT를 5로 설정하면 한 페이지에 5개의 글이 표시된다.
 

4. 조회한 데이터 View에 전송

 
@GetMapping("/") public String index(HttpServletRequest request,@RequestParam(defaultValue = "0")int page) { List<Board> boardList = boardRepository.findAll(page); request.setAttribute("boardList",boardList); return "index"; }
 
조회한 데이터 boardList 를 request 객체에 담는다.
 
resource/index.mustache
<table class="table table-striped"> <thead> <tr> <th>번호</th> <th>제목</th> <th>내용</th> <th>작성자</th> <th></th> </tr> </thead> <tbody> {{#boardList}} <tr> <td>{{id}}</td> <td>{{title}}</td> <td>{{content}}</td> <td>{{author}}</td> <td> <div class="d-flex"> <form action="/board/{{id}}/delete" method="post"> <button class="btn btn-danger">삭제</button> </form> <form action="/board/{{id}}/updateForm" method="post"> <button class="btn btn-warning">수정</button> </form> </div> </td> </tr> {{/boardList}} </tbody> </table>
 
💡
전달 받은 데이터가 오브젝트라면 {{#}} {{/}} 는 if문, {{^}} {{/}} 는 else 문 전달 받은 데이터가 컬렉션 형태라면 {{#}} {{/}} 는 반복문이 된다.
 
boardList 는 컬렉션 형태기 때문에 반복문이 된다.
 
notion image
 
입력받은 데이터와 동일한 화면이 출력된다.
 
Share article
RSSPowered by inblog