본문 바로가기
✨ Back-end/Servlet

[Servlet / JSP] 게시판 만들기 -1 (글 쓰기R, 글 등록C) CRUD

by 환풍 2023. 2. 18.
728x90

Servlet과 JSP에 대해 어느정도 알게되었다. 이제 본격적인 프로젝트를 하나 해보려고 한다.

 

먼저, 메인 페이지를 뜻하는 index.jsp를 생성했다. 강요되는 것은 아니나 권장되는 형식이라하니 따르면 좋을 것이다.

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="boardList.do"></jsp:forward>
</body>
</html>
cs

body를 감싸는 10번째 줄에 <jsp:forward page="boardList.do"></jsp:forward> 위코드는 메인 페이지가 실행되는 즉시 Servlet으로 가서 [ 만약 커맨드로 boardList.do를 받으면 ~~ if(command.equals("/boardList.do")) ] 이라는 부분을 실행하라는 의미이다.

 

BoardController  (서블릿)

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package controller;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import dto.BoardDTO;
 
 
@WebServlet("*.do")
public class BoardController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private int boardNum= 1;
    private List<BoardDTO> boardlist;
       
   
    public BoardController() {
        super();
        boardlist = new ArrayList<>();
        // 글 등록 해줄 데이터 공간을 생성해준다.
        
    }
 
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doProcess(request, response);
    }
 
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doProcess(request, response);
    }
    
    protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
 
 
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        String command = requestURI.substring(contextPath.length());
        System.out.println("command = " + command);
        
        String page = "";
        
        
        
        if(command.equals("/boardList.do"))
        {
            
            request.setAttribute("list", boardlist);
            
            page = "boardList.jsp";
        }
        
        
        if(command.equals("/regBoardForm.do"))
        {
            page = "board_write_form.jsp";
        }
        
        if(command.equals("/regBoard.do"))
        {
            String title = request.getParameter("title");
            String writer = request.getParameter("writer");
            String createDate = request.getParameter("createDate");
            String content = request.getParameter("content");
            
            BoardDTO board = new BoardDTO(boardNum, title, content, writer, createDate);
            
            boardNum++;
            
            boardlist.add(board);
            
            page = "boardList.do";
            // boardList로 돌아가서 
            // 데이터를 적재할 request.setAtrribute("list", boardlist)를 추가해줘야한다.
            
        }
        
        RequestDispatcher dispatcher = request.getRequestDispatcher(page);
        dispatcher.forward(request, response);
        
    }
 
}
 
cs

57번째 줄에 있는 boardList.do가 있는 부문이 실행될 것이다.

request.setAttribute("list", boardlist); 이 코드는 이후에 글 등록 화면에서 쓴 데이터를 저장받아 출력하는 기능을 위한 것이다.

62번째 줄인 page = "boardList.jsp"; 코드로 인해 90번째 줄의 page가 boardList.jsp로 바뀌며 아래 jsp문이 실행된다.

 

boardList.jsp

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table{
   border: 1px solid black;
   border-collapse: collapse;
   text-align: center;
   width: 600px;
}
tr, td{
   border: 1px solid black;
}
</style>
</head>
<body>
<form action="regBoardForm.do" method="post">
<table>
   <colgroup>
      <col width="10%">
      <col width="*">
      <col width="15%">
      <col width="15%">
   </colgroup>
   <tr>
      <td>글번호</td>
      <td>제 목</td>
      <td>작성자</td>
      <td>날짜</td>
      <td>내용</td>
   </tr>
   
   <c:forEach items="${list }" var="board">
      <tr>
          <td>${board.boardNum }</td>
          <td>${board.title }</td>
          <td>${board.writer }</td>
          <td>${board.createDate }</td>
          <td>${board.content }</td>
      </tr>
      </c:forEach>
   
</table>
<input type="submit" value="글쓰기">
</form>
 
 
</body>
</html>
cs

위처럼 글 게시판이 만들어졌다. 아직 아무런 글이 생성되지 않았기에 빈 목록으로 생성되었다.

39번째 줄인

<c:forEach items="${list }" var="board">

<tr>

<td>${board.boardNum }</td>

<td>${board.title }</td>

<td>${board.writer }</td>

<td>${board.createDate }</td>

<td>${board.content }</td>

</tr>

</c:forEach>

위 부분은 나중에 다시 설명하고자 한다.

글쓰기 버튼을 눌러 다시 서블릿의 "regBoardForm.do" 을 읽으러 가보자.

 

다시 BoardController 서블릿으로 돌아와서 if(command.equals("/regBoardForm.do")) 이 실행되며

page = "board_write_form.jsp"; 로인해 게시글 쓰기 폼으로 이동한다.

 

board_write_form.jsp

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
32
33
34
35
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<body>
<form action="regBoard.do" method="post">
   <table>
      <tr>
         <td>제목</td>
         <td><input type="text" name="title"></td>
      </tr>
      <tr>
         <td>작성자</td>
         <td><input type="text" name="writer"></td>
      </tr>
      <tr>
         <td>작성일</td>
         <td><input type="date" name="createDate"></td>
      </tr>
      <tr>
         <td>내용</td>
         <td>
            <textarea rows="5" cols="50" name="content"></textarea>
         </td>
      </tr>
   </table>
   <input type="submit" value="글등록">
</form>
</body>
</html>
cs

이곳에서 각 input 박스에 맞는 name 값들을 채워 넣어준다. 이후 다시 <form action="regBoard.do" method="post"> 을 이용해 서블릿 71번째 줄의 if(command.equals("/regBoard.do")) 을 실행하며 name 값에서 받아온 데이터들을

String title = request.getParameter("title"); 을 사용해 다시 한번 서블릿에 저장한다.  

저장한 객체들을 모아서 뿌려야 하는데, 이때 클래스를 만들어주었다.

 

BoardDTO.java  (클래스)

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package dto;
 
public class BoardDTO {
    private int boardNum;
    private String title;
    private String content;
    private String writer;
    private String createDate;
    
    public BoardDTO(int boardNum, String title, String content, String writer, String createDate) {
        super();
        this.boardNum = boardNum;
        this.title = title;
        this.content = content;
        this.writer = writer;
        this.createDate = createDate;
    }
 
    public int getBoardNum() {
        return boardNum;
    }
 
    public void setBoardNum(int boardNum) {
        this.boardNum = boardNum;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
 
    public String getWriter() {
        return writer;
    }
 
    public void setWriter(String writer) {
        this.writer = writer;
    }
 
    public String getCreateDate() {
        return createDate;
    }
 
    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }
    
}
 
cs

 글번호, 제목, 내용, 작성자, 날짜를 각각 변수로 설정해 생성자와 게터와 세터를 만들었고,

서블릿 78번째 줄에 있는 BoardDTO board = new BoardDTO(boardNum, title, content, writer, createDate); 을 이용해 클래스를 만들어 객체를 저장해주었다. 이때 서블릿 21번째 줄과 22번째 줄에서 boardNum과 List로 BoardDTO를 선언해주었고, 서블릿 기본 생성자에 boardList를 생성해주었다.

 

이후 다시 regBoard.do로 돌아와 boardlist.add(board); 를 통해 board 값들을 boardlist에 모두 넣어주었고, 페이지를

"boardList.do"; 로 주어 첫 페이지인 boardList로 돌아가게 만들었다.

이때 request.setAttribute("list", boardlist);가 바로 regBoard.do에서 저장한 데이터를 넘겨받는 역할을 하는 것이다.

여기 있는 "list" 는 바로 아까 위에서 말했던 boardList.jsp의 39번째 줄에 있는 ${list } 이다. 

forEach문을 이용해 각각 board 값들을 클래스에 저장하여 넘겨준다.

 

그리하여  글등록 버튼을 누르게 되면 boardList.jsp에서 만들었던 리스트에 목록이 추가되어 나타나는 것을 볼 수있다.

 

반응형

댓글