JSP/model 1

답글 기능을 포함한 게시판 (4) - 수정, 삭제

Kiwisae 2022. 9. 13. 14:13
  • DBCP 방식 사용,
  • 액션태그 사용 (useBean, setProperty)
  • DTO, DAO 클래스
  • 페이징 처리 (inline view)
  • 답글 처리

 

 

프로그램 구조

 

Java Resources >
src > board
DTO 클래스 BoardDataBean.java  
DAO 클래스 BoardDBBean.java  
WebContent > reboard reboard writeForm.jsp  
writePro.jsp  
list.jsp  
content.jsp  
replyForm.jsp  
replyPro.jsp  
updateForm.jsp  
updatePro.jsp  
deleteFrom.jsp  
deletePro.jsp  
META-INF context.xml 커넥션 풀 환경설정 파일
WEB-INF > lib ojdbc6.jar  
  web.xml 프로젝트 환경설정 파일

 

 

 

 

 

1. content.jsp의 [수정] 버튼을 클릭 이벤트로 updateForm.jsp와 연결한다.

 

 

 

 

get 방식으로 num값과 현재페이지 값을 저장한 nowpage값을 함께 넘긴다.

 

 

<input type="button" value="수정" 
onClick="location.href='updateForm.jsp?num=<%= num %>&page=<%=nowpage%>' ">

 

 

 

 

 

 

2. updateForm.jsp 생성

 

writeForm.jsp 파일의 내용을 복사-붙여넣기 하여 수정 폼에 맞게 고친다.

get 방식으로 num값과 page값을 잘 가지고 넘어온 모습이다.

 

 

 

 

 

3. request 객체로 num값과 nowpage 값을 넘겨받는다.

 

문서 최상단의 페이지 태그 하단에 리퀘스트 객체를 적는다.

 

<%
	int num = Integer.parseInt(request.getParameter("num"));
	String nowpage = request.getParameter("nowpage");
%>

 

 

 

 

 

4. DB 연동 - DAO 객체 생성

 

<%
	BoardDBBean dao = BoardDBBean.getInstance();
%>

 

 

 

5. num값을 매개로 getContent 메소드를 불러오는 코드를 작성

DAO 문서에 getContent 메소드를 생성한다.

이 getContent 메소드는 일전에 작성했던 updateContent를 그대로 복사-붙여넣기 하여 상세 내용을 수정한다.

 

 

<%
	BoardDataBean board = dao.getContent(num);
%>

 

 

upcateContent와 달라지는 점

-> 글 조회 시 조회수를가 1 올라가도록 되어 있는데 해당 내용을 삭제한다.

 

	public BoardDataBean getContent(int num) {
		BoardDataBean board = new BoardDataBean();
		
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
		
			String sql = "select * from board where num=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				board.setNum(rs.getInt("num"));
				board.setWriter(rs.getString("writer"));
				board.setEmail(rs.getString("email"));
				board.setSubject(rs.getString("subject"));
				board.setPasswd(rs.getNString("passwd"));
				board.setReg_date(rs.getTimestamp("reg_date"));
				board.setReadcount(rs.getInt("readcount"));
				board.setRef(rs.getInt("ref"));
				board.setRe_level(rs.getInt("re_level"));
				board.setRe_step(rs.getInt("re_step"));
				board.setContent(rs.getString("content"));
				board.setIp(rs.getString("ip"));
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rs != null) try { rs.close();} catch (Exception e) {}
			if (pstmt != null) try { pstmt.close();} catch (Exception e) {}
			if (con != null) try { con.close();} catch (Exception e) {}
		}
		
		return board;
	}

 

 

 

 

6.

이 부분은 통째로 지웠다.

 

 

 

 

7.

폼 태그의 액션 값을 writePro.jsp에서 updatePro.jsp로 수정했고, 

hidden 객체의 값들을 수정했다.

 

 

 

 

 

8.

updateForm.jsp 진입 시 글 내용의 값들을 그대로 가져와 출력되도록

각 항목마다 value 값을 추가한다.

 

그리고 하단의 [글쓰기] 버튼의 value 값도 [수정]으로 고친다.

[목록보기]를 눌렀을 때 nowpage 값을 받아서 가도록 수정한다.

 

 

 

 

 

9.

비밀번호가 맞을 경우에만 수정이 가능하도록 설정하기 위해

updatePro.jsp 를 생성한다.

 

가장 먼저 한글 인코딩 설정 후, usebean 액션태그와 property를 불러오는 액션태그를 작성한다.

 

DTO 클래스에 없는 ip와 page 값을 따로 가져오는 리퀘스트 객체도 작성한다.

 

DB를 연동할 수 있는 DAO 객체를 생성한 후, old 라는 이름으로 값을 받도록 설정한다.

 

<%
	request.setCharacterEncoding("UTF-8");
%>

<jsp:useBean id="board" class="reboard.BoardDataBean"></jsp:useBean>
<jsp:setProperty property="*" name="board"/>

<%
	board.setIp(request.getRemoteAddr());
	String nowpage = request.getParameter("page");
    	BoardDBBean dao = BoardDBBean.getInstance();
	BoardDataBean old = dao.getContent(board.getNum());
%>

 

 

 

 

10.  비밀번호를 비교하는 조건문 작성

 

 

	if(old.getPasswd().equals(board.getPasswd())) {	// 비번 일치 시
		
		int result = dao.update(board);				// updateSQL 문 실행
		if(result == 1) { %>
			<script>
				alert("글 수정 완료");
				location.href="list.jsp?page=<%=nowpage%>";
			</script>
		<%} 
 } else { 										// 비번 불일치 시 %>

		<script>
			alert("비밀번호가 일치하지 않습니다.");
			history.go(-1);
		</script>

<% } %>

 

 

 

11. update 메소드 생성

 

	public int update (BoardDataBean board) {
		int result = 0;
		
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			
			con = getConnection();
			
			String sql = "update board set writer=?, email=?, subject=?, content=? ";
				sql += " where num=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, board.getWriter());
			pstmt.setString(2, board.getEmail());
			pstmt.setString(3, board.getSubject());
			pstmt.setString(4, board.getContent());
			pstmt.setInt(5, board.getNum());
			
			result = pstmt.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pstmt != null) try { pstmt.close();} catch (Exception e) {}
			if (con != null) try { con.close();} catch (Exception e) {}
		}
		
		return result;
	}

 

 

 

12. deleteForm.jsp 생성

 

content.jsp에서 삭제 버튼에 클릭 이벤트로 deleteForm.jsp와 연결한다.

 

<input type="button" value="삭제"
onClick="location.href='deleteForm.jsp?num=<%= num %>&page=<%=nowpage%>' ">

 

 

updateForm.jsp의 내용을 복사-붙여넣기 하여 일부를 수정한다.

 

action값을 deletePro.jsp로 수정,

사용하지 않는 이름, 이메일, 글제목, 글내용 항목은 모두 지운다.

버튼은 [삭제]로 이름을 바꾸고 [목록보기]는 남겨둔다. [다시작성]은 지운다.

 

 

 

13. deletePro.jsp 생성

updatePro.jsp의 내용을 복사-붙여넣기 하여 수정한다.

달라지는 것은 비밀번호 일치 시 실행하는 메소드가 dao.delete(board) 인 것 뿐이다.

 

 

 

 

 

14. delete 메소드 생성

 

원글을 삭제할 때는 

list.jsp 관리자에 의해 삭제되었다는 메시지를 출력하도록 한다.

 

	public int delete(BoardDataBean board) {
		int result = 0;
		
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = "";
		
		try {
			con = getConnection();
			
			if(board.getRe_level() == 0) {	// 1. 원문 삭제일 경우
			
				sql = "update board set subject=?, content=? where num=?";
				
				pstmt = con.prepareStatement(sql);
				pstmt.setString(1, "관리자에 의해 삭제된 게시물입니다");
				pstmt.setString(2, " ");
				pstmt.setInt(3,  board.getNum());
				
			} else {						// 2. 답글 삭제일 경우
			
				sql = "delete from board where num=?";
				pstmt = con.prepareStatement(sql);
				pstmt.setInt(1,  board.getNum());
			}
			
			result = pstmt.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pstmt != null) try { pstmt.close();} catch (Exception e) {}
			if (con != null) try { con.close();} catch (Exception e) {}
		}
		
		return result;
	}