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

[Servlet / JSP] 게시판 만들기 등록, 쓰기, 수정, 삭제 CRUD (최종)

by 환풍 2023. 2. 18.
728x90
반응형

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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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;
    private List<BoardDTO> boardList;
    
    
    
    public BoardController() {
        super();
        boardNum = 1;
        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);
    }
 
    public 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 = "";
        // 맨 밑 페이지 이동시 쓰는거.
        boolean isRedirect = false;
        
        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 content = request.getParameter("content");
            String writer = request.getParameter("writer");
            String createDate = request.getParameter("createDate");
            
            //위에서 전달받은 데이터를 갖는 게시글 생성
            BoardDTO board = new BoardDTO(boardNum, title, content, writer, createDate);
            // BoardDTO의 첫번쨰 boardNum = 글번호
            boardNum++;
            
            
            
            boardList.add(board);
            
            //page="boardList.jsp";
            page ="boardList.do";
            // 맨 밑 페이지 이동시 쓰는거. 일단 page이동 do로 끝내는것만. 기억하자.
            isRedirect = true;
        }
        
        //게시글 상세보기
        if(command.equals("/boardDetail.do"))
        {
            int num = Integer.parseInt(request.getParameter("boardNum"));
            
            //게시글 목록에서 넘겨온 글번호와 같은 게시글 찾기.
            // boardList로 반복할거다. 반복해서 뽑으면 그게 BoardDTO.
            for(BoardDTO board: boardList) {
                if(board.getBoardNum() == num) {
                    request.setAttribute("board", board );
                }
            }
            
            page="boardDetail.jsp";
        }
        
        //게시글 삭제하기
        if(command.equals("/delete.do"))
        {
            //boardNum이라는 문자열을 받아온다. int형 변환을 함께해준다.
            int num = Integer.parseInt(request.getParameter("boardNum"));
            
            for(int i =0; i<boardList.size(); i++)
            {
                //리스트 뒤에 get은 순번. 
                if(boardList.get(i).getBoardNum() == num )
                {
                    boardList.remove(i);
                    
                }
            }
            
            
            
            //page="boarList.jsp"; 이렇게 들고가면 데이터 안가져가준다. 화며네 암것도안봉미.
            page="boarList.do";
        }
        
        //게시글 수정 페이지로 이동
        if(command.equals("/updateBoardForm.do"))
        {
            int num = Integer.parseInt(request.getParameter("boardNum"));
            
            for(BoardDTO board : boardList) {
                if(board.getBoardNum() == num) {
                    request.setAttribute("board", board);
                }
            }
            //수정하고자 하는 게시글의 정보를 jsp에 보내줘야함.
            page = "update_board_form.jsp";
        }
        
        //글 수정
        if(command.equals("/updateBoard.do"))
        {
            String title = request.getParameter("title");
            String writer = request.getParameter("writer");
            String createDate = request.getParameter("createDate");
            String content = request.getParameter("content");
            int num = Integer.parseInt(request.getParameter("boardNum"));
            
            for(BoardDTO board : boardList) {
                if(board.getBoardNum()==num)
                {
                    board.setTitle(title);
                    board.setWriter(writer);
                    board.setContent(content);
                    board.setCreateDate(createDate);
                }
            }
            
            page="boarList.do";
            //page = "boardDetail.do?boardNum=" + num; 왜 이거지?
        }
        
        // 페이지 이동.
        if(isRedirect) {
            response.sendRedirect(page);
        }
        else {
            RequestDispatcher dispatcher = request.getRequestDispatcher(page);
            dispatcher.forward(request, response);
        }
                
        
        
        
    }
    
}
 
cs

BoardDTO

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
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

board_write_form

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>
<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

boardDetail

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ 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>
</head>
<body>
 
글번호 : ${board.boardNum }<br>
제목 : ${board.title } <br>
내용 : ${board.content }<br>
작성자 : ${board.writer }<br>
작성일 : ${board.createDate }<br>
 
<input type="button" value="삭제하기" onclick="location.href='delete.do?boardNum=${board.boardNum }';">
<!-- 어떤걸 삭제할건지 보드 번호를 가져가야해서 ?뒤에 문장이나옴. -->
<input type="button" value="수정" onclick="location.href='updateBoardForm.do?boardNum=${board.boardNum }';">
<!-- 상세보기 페이지로 넘어갈때도 글번호 데이터를 넘겨서 가져가야해서 ?뒤에 문장을쓴다. -->
</body>
</html>
cs

boardList

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
<%@ 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>
<table>
   <colgroup>
      <col width="10%">
      <col width="*">
      <col width="15%">
      <col width="15%">
   </colgroup>
   <tr>
      <td>글번호</td>
      <td>제 목</td>
      <td>작성자</td>
      <td>작성일</td>
   </tr>
   
   <!-- a태그에서 데이터를 넘길때에는 ? 를 쓴다. 
       boardNum이라는 글번호를 가지고 가겠다. -->
      <!-- 게시글 개수만큼 만들어줘야한다.taglib만들어주고. -->
      <c:forEach items="${list }" var="board">
      <tr>
          <td>${board.boardNum }</td>
          <td><a href="boardDetail.do?boardNum=${board.boardNum }">${board.title }</a></td>
          <td>${board.writer }</td>
          <td>${board.createDate }</td>
      </tr>
      </c:forEach>
         
   
</table>
<input type="button" value="글쓰기" onclick="location.href='regBoardForm.do';">
</body>
</html>
 
cs

index

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ 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

update_board_form

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
<%@ 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>
<form action="updateBoard.do" method="post">
<input type="hidden" name="boardNum" value="${board.boardNum }">
<table>
    <tr>
        <td>제목</td>
        <td><input type="text" name="title" value="${board.title }"></td>
    </tr>
    <tr>
        <td>작성자</td>
        <td><input type="text" name="writer" value="${board.writer }"></td>
    </tr>
    <tr>
        <td>작성일</td>
        <!-- read온리는 수정은 안되지만, 데이터가 넘어간다. -->
        <td><input type="text" name="createDate" value="${board.createDate }" readonly></td>
    </tr>
    <tr>
        <td>내용</td> <!--textarea는 value가 없다. 여는태그, 닫는태그 사이에 넣어준다.  -->
        <td><textarea rows="5" cols="50">${board.content }</textarea></td>
    </tr>
</table>
<input type="submit" value="글수정">
</form>
</body>
</html>
cs

 


결과화면

 

삭제를 누른후

 

728x90
반응형

댓글