ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 게시판 만들기 - 8. 글 수정 & 글 삭제 구현하기
    JAVA/웹 프로그래밍 - JSP 2020. 12. 1. 18:48

    아래의 내용에 뒤를 어이 만들어 보자.

    designatedroom87.tistory.com/326?category=901206

     

    게시판 만들기 - 7. 채팅 기능 추가 하기

    index 파일을 실행하면 header에는 아래와 같이 목록이 뜬다. IOT라는 항목을 선택했을 때, 채팅 기능이 나오도록 할 것이다. 물론 로그인 상태여야 이 채팅 기능을 보여줄 것이고, 그렇지 않으면 로

    designatedroom87.tistory.com

     

    로그인을 한 상태에서 게시글을 하나 선택했을 시에, 아래와 같이 나타난다.

    구현할 내용은 위의 글 수정과 글 삭제 기능이다.

     

    1. 글 수정 구현하기

    /board/read.jsp에서 글 수정 버튼을 클릭을 시작으로 발생한다.

    글 수정 버튼이 넘겨야 할 데이터가 많음을 볼 수 있는데, 이는 나중에 객체를 이용해서 처리를 할 수 있다.

    우선은 아래와 같이 변수들을 하나씩 처리를 한다.

    게시글의 idx정보 뿐만 아니라 여러 정보도 같이 넘겨줘야 한다.

    이 정보는 나중에 update.jsp에서 받을 것이다.

    jsp와 jsp에서의 데이터는 param으로 받을 수 있다.

     

    아래의 내용이 read.jsp에서 update.jsp로 넘길 데이터들이다.

    idx=${board.idx}&

    title=${board.title}&

    write_name=${board.write_name}&

    write_day=${board.write_day}&

    readcount=${board.readcount}&

    content=${board.content}&

    requestPage=${requestPage}

     

    read.jsp

    더보기
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    
    <div class="container">
      <h2><button class="btn" onclick="location.href='/index.jsp'"><i class="fa fa-home"></i></button>글읽기</h2>
         
        <div class="form-group">
          글번호: [${board.idx}] 제목: ${board.title}<p>
          작성자: ${board.write_name} 작성일: ${board.write_day} 조회수: ${board.readcount}<p>
        </div>
     
        <div class="form-group">
          <label for="content">내용:</label>
          <textarea class="form-control" disabled id="content" name="content" cols="80%" rows="10" placeholder="글을 입력하세요">
          ${board.content}
          </textarea>
        </div>
        
        <div class="form-group">
    	<button onclick="location.href='/board/list?requestPage=${requestPage}'">목록으로</button>
    	<button onclick="location.href='/board/replyForm?idx=${board.idx}&groupid=${board.groupid}&depth=${board.depth}&re_order=${board.re_order}&title=${board.title}&requestPage=${requestPage}'">답글쓰기</button>
    	<button onclick="location.href='/board/update?idx=${board.idx}&requestPage=${requestPage}&title=${board.title}&write_name=${board.write_name}&write_day=${board.write_day}&readcount=${board.readcount}&content=${board.content}'">글 수정</button>
    	<button onclick="location.href='/board/delete.do?idx=${board.idx}'">글 삭제</button>
        </div>
     
    </div>

    그리고 글 수정 버튼을 클릭하면, /board/update로 이동한다.

    즉, board.controller 패키지의 Controller에서 처리를 한다.

    그리고 이는 Controller의 else if의 update에서 이뤄진다.

    위의 update 처리문에서는 updateForm.jsp로 이동을 해서, 수정할 폼을 보여주고

    수정할 내용을 입력 받는 작업을 처리한다.

    그리고 나서 다시 Controller로 넘어와서 DB에 수정된 정보를 반영하면 된다.

    수정한 내용의 반영은 Controller의 update.do에서 한다.

    updateForm.jsp파일은 WEB-INF/board폴더에 만든다.

    updateForm.jsp

    더보기
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    
    <script>
    function dataCheck(){
    	if(document.getElementById("title").value==""){
    		alert("제목을 입력해 주세요")
    		return;
    	}
    	if(document.getElementById("content").value==""){
    		alert("내용을 입력해 주세요")
    		return;
    	}
    	document.form.submit();
    }
    </script>
        
    <div class="container">
      <h2><button class="btn" onclick="location.href='/index.jsp'"><i class="fa fa-home"></i></button>글읽기</h2>
        
      <form name=form action="/board/update.do">
        <div class="form-group">
        
        <!-- 페이지 번호와 글번호는 숨겨서 다른 jsp파일로 전송하고 title,content는 수정 후 전송 -->
        <input type=hidden name="requestPage" value=${param.requestPage} /> 
          글번호: [${param.idx}]  <input type=hidden name="idx" value=${param.idx} />
          제목: <input type=text value=${param.title} name="title" id="title" /> <p>
          작성자: ${param.write_name} 작성일: ${param.write_day} 조회수: ${param.readcount}<p>
        </div>
     
        <div class="form-group">
          <label for="content">내용</label>
          <textarea class="form-control" id="content" name="content" cols="80%" rows="10" placeholder="글을 입력하세요">
          ${param.content}
          </textarea>
        </div>
        
        <div class="form-group">
    	<!-- <button onclick="location.href='/board/update.do?requestPage=${param.requestPage}'">글 수정하기</button> -->
    	<button onclick="dataCheck()">글 수정하기</button>
        </div>
     </form>
     
     <button onclick="location.href='/board/list?requestPage=${param.requestPage}'">취소하기</button>
    </div>

    위의 updateFrom.jsp에서 "취소하기" 버튼을 선택하면 list 페이지를 보여주기 위해, Controller의 list문으로 넘기고

    이 "취소하기" 기능 때문에 requestPage의 변수를 받아오는 것이 필요했다.

    그래야 현재 보고 있는 페이지로 이동할 수 있기 때문이다.

    그리고 "글 수정하기" 버튼을 선택하면 board.controller 패키지의 Controller의 update.do에서 처리를 하도록 한다.

    아래는 Controller의 else if 문이다.

    수정할 내용을 DB에 접속해서 변경하면 끝이다.

    업데이트가 성공했는지 실패했는지에 따라, update_success.jsp 로 이동하거나 update_fail.jsp로 이동한다.

    BoardService.java와 BoardDAO.java에 update함수를 만들자.

    BoardService.java

    더보기
    package board.service;
    
    import board.dao.BoardDAO;
    import board.model.Board;
    import board.model.PageBoard;
    
    public class BoardService {
    	private static BoardService service = new BoardService();
    	public BoardDAO dao = BoardDAO.getInstance();
    	
    	private BoardService() {}
    	
    	public static BoardService getInstance(){return service;}
    	
    	//	글 입력
    	public int insert(String title, String content, String write_name) {
    		return dao.insert(title,content,write_name);
    	}
    	
    	//	글 입력
    	public int insert(Board board) {
    		return dao.insert(board);
    	}
    
    	public PageBoard list(int requestPage) {
    		return dao.list(requestPage);
    	}
    
    	public void incrementReadCount(int idx) {
    		dao.incrementReadCount(idx);
    	}
    
    	public Board selectById(int idx) {
    		return dao.selectById(idx);
    	}
    
    	public int replyInsert(Board board) {
    		return dao.replyInsert(board);
    	}
    
    	public int update(Board board) {
    		return dao.update(board);
    	}
    
    	public int delete(Board board) {
    		return dao.delete(board);
    	}
    }

     

    BoardDAO클래스의 update함수는 단순하다.

    아래와 같다.

    BoardDAO.java

    더보기
    package board.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.sun.net.httpserver.Authenticator.Result;
    
    import board.model.Board;
    import board.model.PageBoard;
    
    public class BoardDAO {
    	private static BoardDAO dao = new BoardDAO();
    	
    	private BoardDAO() {}
    	public static BoardDAO getInstance() {
    		return dao;
    	}
    	
    	public Connection connect()
    	{
    		Connection conn = null;
    		
    		try {
    		Class.forName("oracle.jdbc.driver.OracleDriver");
    		conn=DriverManager.getConnection(
    		"jdbc:oracle:thin:@localhost:1521:xe","hr","1234");
    
    		if(conn==null) {System.out.println("DB접속에 실패");}
    		System.out.println("DB접속 성공");
    		
    		}catch(Exception e) {}
    		
    		return conn;
    	}
    	
    	public void close(Connection conn, PreparedStatement pstmt, ResultSet rs)
    	{
    		if (rs != null) 
    		{
    			try 
    			{
    				rs.close();
    			}
    			catch (SQLException e) {e.printStackTrace();}
    		}
    		this.close(conn,pstmt);
    	}
    	
    	public void close(Connection conn, PreparedStatement pstmt)
    	{
    		try {
    		pstmt.close();
    		conn.close();
    		}
    		catch (SQLException e) {e.printStackTrace();}
    	}
    	
    	//	글 입력
    	public int insert(String title, String content, String write_name) {
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		int result = 0;
    		String sql = null;
    		
    		try {
    			conn = this.connect();
    			
    			conn.setAutoCommit(false);	//	DB 트랜잭션의 시작
    			
    			sql = "insert into board values(";
    			sql += "board_idx_seq.nextval,";
    			sql += "?,?,0,";
    			sql	+=	"board_groupid_seq.nextval,0,0,";
    			sql +=	"0,";
    			sql +=	"?,?,sysdate";
    			sql +=	")";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, title);
    			pstmt.setString(2, content);
    			pstmt.setString(3, write_name);	//	id
    			pstmt.setString(4, write_name);	//	name
    			
    			result = pstmt.executeUpdate();
    			
    			if (result > 0) {
    				System.out.println("SQL 글 입력 성공");
    				conn.commit();
    			}else {
    				System.out.println("SQL 글 입력 실패");
    				conn.rollback();
    			}
    			this.close(conn, pstmt);
    		}
    		catch(Exception e) 
    		{	
    			try {
    				conn.rollback();
    			} catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return result;
    	}
    	
    	//	글 입력
    	public int insert(Board board) {
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		int result = 0;
    		String sql = null;
    		
    		try {
    			conn = this.connect();
    			
    			conn.setAutoCommit(false);	//	DB 트랜잭션의 시작
    			
    			sql = "insert into board values(";
    			sql += "board_idx_seq.nextval,";
    			sql += "?,?,0,";
    			sql	+=	"board_groupid_seq.nextval,0,0,";
    			sql +=	"0,";
    			sql +=	"?,?,sysdate";
    			sql +=	")";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, board.getTitle());
    			pstmt.setString(2, board.getContent());
    			pstmt.setString(3, board.getWrite_name());	//	id
    			pstmt.setString(4, board.getWrite_name());	//	name
    			
    			result = pstmt.executeUpdate();
    			
    			if (result > 0) {
    				System.out.println("SQL 글 입력 성공");
    				conn.commit();
    			}else {
    				System.out.println("SQL 글 입력 실패");
    				conn.rollback();
    			}
    			this.close(conn, pstmt);
    		}
    		catch(Exception e) 
    		{	
    			try {
    				conn.rollback();
    			} catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return result;
    	}
    	public PageBoard list(int requestPage) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		ResultSet rs = null;
    		String sql = null;
    		List<Board> list = new ArrayList<Board>();	//	글 번호에 대한 리스트를 담는 객체
    		PageBoard pageboard = null;					//	페이지 정보와 리스트를 담는 객체
    		
    		//	페이지 관련 정보 사항
    		//int requestPage = 0;		//	요청한 페이지
    		int totalPage = 0;			//	전체 페이지
    		int beginPage = 0;			//	시작 페이지
    		int	endPage = 0;			//	마지막 페이지
    		int firstRow = 0;			//	시작 글번호
    		int endRow = 0;				//	끝 글번호
    		int articleCount = 0;		//	글의 전체 개수
    		int countPerPage = 10;		//	페이지 당 보여줄 글의 개수
    		
    		try {
    			System.out.println("-------BoardDAO-------------");
    			conn = this.connect();					//	DB접속
    			conn.setAutoCommit(false);
    			
    			//	페이지에 대한 정보
    			//	1. 전체 게시물 수 구하기(articleCount)
    			//sql = "select count(*) from board";
    			sql = "select count(*) from board where isdel=0";
    			pstmt = conn.prepareStatement(sql);
    			rs = pstmt.executeQuery();
    			if (rs.next()) {
    				articleCount = rs.getInt(1);
    			}
    			else {
    				articleCount = 0;
    			}
    			//rs.close();
    			//	2. 전체 페이지 수를 구하기(totalPage)
    			//	예를 들어 총 게시글이 71개이면, 총 페이지는 8개가 되야 한다.
    			totalPage = articleCount / countPerPage;
    			if (articleCount % countPerPage > 0)
    				totalPage += 1;
    			
    			//	3. 요청한 페이지에 대한 시작 글번호와 끝 글번호 구하기
    			firstRow = (requestPage - 1) * countPerPage + 1;
    			endRow = firstRow + countPerPage - 1; 
    			System.out.printf("firstRow : %d, endRow : %d\n",firstRow, endRow);
    			//	4. 시작 페이지 번호, 끝 페이지 번호(beginPage, endPage)
    			if (totalPage > 0) {
    				beginPage = (requestPage - 1) / countPerPage * countPerPage + 1;
    				//	beginPage = requestPage - 2;
    				endPage = beginPage + 4;	//	4는 요청 페이지를 기준으로 보여줄 페이지의 간격
    				
    				if (endPage > totalPage)	endPage = totalPage;
    			}
    			
    			//	5. 페이지에 해당하는 리스트(firstRow, endRow)
    			/*
    			 sql = "select idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select rownum rnum, idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select * from board a order by a.groupid desc, a.depth asc, a.idx asc) where rownum <= ?";
    			sql += ") where rnum >= ?";
    			 */
    			sql = "select idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select rownum rnum, idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select * from board a order by a.groupid desc, a.depth asc, a.idx asc) where rownum <= ? and isdel=0";
    			sql += ") where rnum >= ?";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, endRow);	//	큰 수. 40이라고 가정
    			pstmt.setInt(2, firstRow);	//	작은 수. 31이라고 가정
    			rs = pstmt.executeQuery();
    			
    			//	6. DB의 리스트를 board객체에 담아 전송
    			while (rs.next()) {
    				Board board = new Board();
    				board.setIdx(rs.getInt("idx"));
    				board.setTitle(rs.getString("title"));
    				board.setContent(rs.getString("content"));
    				board.setReadcount(rs.getInt("readcount"));
    				board.setGroupid(rs.getInt("groupid"));
    				board.setDepth(rs.getInt("depth"));
    				board.setRe_order(rs.getInt("re_order"));
    				board.setIsdel(rs.getInt("isdel"));
    				board.setWrite_id(rs.getString("write_id"));
    				board.setWrite_name(rs.getString("write_name"));
    				board.setWrite_day(rs.getDate("write_day"));
    				
    				list.add(board);
    			}
    			
    			pageboard = new PageBoard(list, requestPage,totalPage,
    					beginPage, endPage, firstRow, endRow, articleCount,countPerPage
    					);
    			
    			this.close(conn, pstmt, rs);
    			conn.commit();
    		}
    		catch(Exception e) 
    		{
    			try {conn.rollback();} 
    			catch (SQLException e1) {e1.printStackTrace();} 
    			
    			e.printStackTrace();
    		}
    		System.out.println("-----end BoardDAO-------------");
    		return pageboard;
    	}
    	public void incrementReadCount(int idx) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		String sql = null;
    		
    		try {
    			conn = this.connect();
    			sql = "update board set readcount=readcount+1 where idx=?";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, idx);
    			pstmt.executeUpdate();
    			
    			this.close(conn, pstmt);
    		}catch(Exception e){}
    	}
    	public Board selectById(int idx) 
    	{
    		Board board = null;
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		ResultSet rs = null;
    		String sql = null;
    		
    		try {
    			conn = this.connect();
    			//conn.setAutoCommit(false);
    			sql = "select * from board where idx=?";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, idx);
    			rs = pstmt.executeQuery();
    			
    			if (rs.next())
    			{
    				board = new Board(
    						rs.getInt("idx"), 
    						rs.getString("title"), 
    						rs.getString("content"), 
    						rs.getInt("readcount"), 
    						rs.getInt("groupid"), 
    						rs.getInt("depth"), 
    						rs.getInt("re_order"), 
    						rs.getInt("isdel"), 
    						rs.getString("write_id"), 
    						rs.getString("write_name"), 
    						rs.getDate("write_day")
    						);
    			}	
    			//conn.commit();
    			this.close(conn, pstmt, rs);
    		}
    		catch(Exception e) 
    		{
    			try {conn.rollback();} 
    			catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return board;
    	}
    	
    	//	replyInsert함수에서 이용
    	public boolean checkParent(int idx) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		ResultSet rs = null;
    		String sql = null;
    		int result = 0;
    		
    		try {
    			conn = this.connect();
    			
    			//	isdel이 0이면 삭제가 되지 않았다는 의미
    			sql = "select count(*) from board where idx=? and isdel=0";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, idx);
    			rs = pstmt.executeQuery();
    			
    			if (rs.next()) 
    			{
    				result = rs.getInt(1);
    			}
    			if (result != 1)
    			{
    				//this.close(conn, pstmt, rs);
    				return false;
    			}
    			
    			this.close(conn, pstmt, rs);
    		}catch(Exception e) {}
    		
    		return true;
    	}
    	
    	//	replyInsert함수에서 이용
    	public void reply_before_update(int depth, int groupid) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		String sql = null;
    		
    		try {
    			conn = this.connect();
    			
    			//	isdel이 0이면 삭제가 되지 않았다는 의미
    			sql = "update board set depth=depth+1 where groupid=? and depth>?";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, groupid);
    			pstmt.setInt(2, depth);
    			
    			pstmt.executeUpdate();
    				
    			this.close(conn, pstmt);
    		}catch(Exception e) {}
    	}
    	
    	public int replyInsert(Board board) 
    	{
    		//	댓글은 
    		//		1. 부모 글이 존재하는지 여부 확인 checkParent(board.getIdx());
    		//		2. 댓글과 상관이 있는 글에 대해 groupid, depth, [re_order]값을 변경 - reply_before_update(depth,groupid);
    		//				re_order는 잘 안 바뀐다.
    		//		3. 댓글이 등록 - insert();
    		//	위의 조건에 따라 DB에 저장한다.
    		
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		String sql = null;
    		int result = 0;
    		
    		try {
    			conn = this.connect();
    			conn.setAutoCommit(false);			//	반드시 필요하다.
    			
    			//	부모 글의 존재여부 확인
    			if(!checkParent(board.getIdx())) 	//	board의 idx는 부모 idx이다.
    			{	
    				conn.rollback();
    				return 0;
    			}
    			System.out.println("부모글 확인");
    			
    			//	댓글과 관련된 글에 대해 업데이트
    			reply_before_update(board.getDepth(),board.getGroupid());
    			System.out.println("관련 댓글 입력 완료");
    			
    			//	insert 작업
    			sql = "insert into board values(";
    			sql += "board_idx_seq.nextval,";
    			sql += "?,?,0,";		//	1.title, 2.content, readcount
    			sql	+=	"?,?,?,";		//	3.groupid, 4.depth, 5.re_order
    			sql +=	"0,";			//	삭제 여부
    			sql +=	"?,?,sysdate";	//	6.write_id, 7.write_name, 8.날짜
    			sql +=	")";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, board.getTitle());
    			pstmt.setString(2, board.getContent());
    			pstmt.setInt(3, board.getGroupid());
    			pstmt.setInt(4, board.getDepth());
    			pstmt.setInt(5, board.getRe_order());
    			pstmt.setString(6, board.getWrite_id());	//	id
    			pstmt.setString(7, board.getWrite_name());	//	name
    			//pstmt.setDate(8, (java.sql.Date)board.getWrite_day());
    			
    			result = pstmt.executeUpdate();
    			
    			if (result == 0) 
    			{
    				conn.rollback();
    				return 0;
    			}
    			else {conn.commit();}
    		}
    		catch(Exception e) 
    		{
    			try {
    				conn.rollback();
    			} catch (SQLException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    		}
    		
    		return result;
    	}
    	
    	public int update(Board board) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		String sql = null;
    		int result = 0;
    		
    		try {
    			conn = this.connect();
    			conn.setAutoCommit(false);	//	반드시 필요하다.
    			
    			sql = "update board set title=?, content=? where idx=?";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, board.getTitle());
    			pstmt.setString(2, board.getContent());
    			pstmt.setInt(3, board.getIdx());
    			result = pstmt.executeUpdate();
    			
    			if (result == 1)	System.out.println("업데이트 성공");
    			else				System.out.println("업데이트 실패");
    			
    			conn.commit();
    			this.close(conn, pstmt);
    		}
    		catch(Exception e) 
    		{
    			try {conn.rollback();} 
    			catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return result;
    	}
    	
    	public int delete(Board board) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		String sql = null;
    		int result = 0;
    		
    		try {
    			conn = this.connect();
    			conn.setAutoCommit(false);	//	반드시 필요하다.
    			
    			//	1. 해당 글에 댓글이 있는지 확인한다.
    			
    			//	DB에서 실제 데이터를 삭제하지 않고 isdel을 1로 설정한다.
    			sql = "update board set isdel=1 where idx=?";
    			
    			//	조건 리스트 검색 시 조건에 isdel=0인 조건을 만족하는 리스트를 찾아라.
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, board.getIdx());
    			result = pstmt.executeUpdate();
    			
    			if (result == 1)	System.out.println("삭제 성공");
    			else				System.out.println("삭제 실패");
    			
    			conn.commit();
    			this.close(conn, pstmt);
    		}
    		catch(Exception e) 
    		{
    			try {conn.rollback();} 
    			catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return result;
    	}
    }

     

    update_success.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    update success

     

    update_fail.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    update fail

     

     

    2. 글 삭제 구현하기

    /board/read.jsp에서 글 삭제 버튼을 클릭을 시작으로 발생한다.

    "글 삭제" 버튼을 선택하면 웹 페이지에 보여줄 필요 없이 바로 DB에 접속해서 처리하면 된다.

    별 설명이 없으면 여기서의 Controller는 모두 board.controller 패키지의 컨트롤러이다.

    Controller의 delete.do에서 처리를 한다.

    BoardService.java와 BoardDAO.java에 delete함수를 만들자.

    삭제에 성공하면 delete_success.jsp로 이동하고 삭제에 실패하면 delete_fail.jsp로 이동한다.

    delete_success.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    delete success

     

    delete_fail.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    delete fail

    delete함수에서 정보를 삭제 시에 몇 가지 생각해야 할 것이 있다.

    DB에서 실제로 삭제하지 않고 isdel을 1로 설정을 하고
    출력 시에 isdel=0인 조건에 대한 리스트만 찾아내서 출력하면 된다.

    데이터를 실제로 삭제하지 않는다.

    이에 따라, 기존에 전체 데이터를 출력하는 함수인 BoardDAO클래스의 list 함수에도 수정이 발생한다.

    아래에서 전체 게시물의 개수를 찾을 때, isdel=0인 조건이 있어야 한다.

    그리고 아래의 sql에서 맨 마지막 줄에 isdel=0인 조건이 추가되어야 한다.

    이미 위의 BoardService.java 와 BoardDAO.java에는 이 내용이 이미 변경이 되었으므로

    변경할 필요 없다.

     

    board.controller패키지의 Controller.java 파일

    더보기
    package board.controller;
    
    import java.io.IOException;
    import java.util.Date;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    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 javax.servlet.http.HttpSession;
    
    import board.model.Board;
    import board.model.PageBoard;
    import board.service.BoardService;
    
    //	member로 들어오는 모든 url에 대해서 해당 컨트로럴가 이에 대한 처리를 하겠다는 의미
    @WebServlet("/board/*")
    public class Controller extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
    	public void init(ServletConfig config) 
    			throws ServletException {}
    
    	protected void service(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {
    	
    		request.setCharacterEncoding("UTF-8");		//	한글 깨짐 방지
    		//ServletContext application = request.getServletContext();	//	전역 객체
    		
    		//	페이지 페이지 마다 연결 시간 설정 가능. 전역 객체이다.
    		HttpSession session = request.getSession();					 
    		
    		//	1. 페이지를 전송하기 전에 url을 분석하고 분류해서 실행
    		String url = request.getRequestURI();
    		//System.out.println("url : " +url);
    		String contextPath = request.getContextPath();
    		//System.out.println("contextPath : " +contextPath);
    		String path = url.substring(contextPath.length());
    		//System.out.println("path : " +path);
    		String lastPath = url.substring(url.lastIndexOf('/') + 1);	//	마지막 /를 기준으로 분리
    		System.out.println("subPath : " +lastPath);
    		String command = lastPath;
    		
    		//	로그인 여부를 먼저 확인
    		if (session.getAttribute("id") != null) 
    		{
    			if (command.equals("board")) 
    			{
    				request.setAttribute("page", "list.jsp");
    			}
    			else if (command.equals("list")) 
    			{
    				//	폼에서 전송된 데이터 받기 request.getParameter()
    				String requestPage_ = request.getParameter("requestPage");
    				System.out.printf("%s\n",requestPage_);
    				int requestPage = 1;
    				if (requestPage_ != null) 
    				{
    					requestPage = Integer.parseInt(requestPage_);
    				}
    	
    				//	service-dao work
    				BoardService service = BoardService.getInstance();
    				PageBoard pageboard = new PageBoard();
    				pageboard = service.list(requestPage);
    				
    				request.setAttribute("pageboard", pageboard);
    				System.out.println(pageboard.getList().toString());
    				request.setAttribute("page", "list.jsp");
    			}
    			else if (command.equals("searchList")) 
    			{
    				String field = request.getParameter("field");
    				String search = request.getParameter("search");
    				System.out.printf("%s %s\n",field,search);
    				
    				request.setAttribute("page", "list.jsp");
    			}
    			//	글쓰기버튼이 눌리면
    			else if (command.equals("insert")) 
    			{
    				request.setAttribute("page", "writeForm.jsp");
    			}
    			else if (command.equals("insert.do")) 
    			{
    				String title = request.getParameter("title");
    				String content = request.getParameter("content");
    				String write_name = request.getParameter("write_name");
    				System.out.printf("%s %s %s\n",title,content,write_name);
    				
    				//	model을 적용하여 전송
    				Board board = new Board();
    				board.setTitle(title);
    				board.setContent(content);
    				board.setWrite_name(write_name);
    				//	model 적용 end
    				
    				BoardService service = BoardService.getInstance();
    				
    				//int result = service.insert(title,content,write_name);
    				int result = service.insert(board);
    				
    				if (result == 1)
    				{
    					System.out.println("글입력 성공");
    					
    					request.setAttribute("page", "success.jsp");
    				}
    				else 
    				{
    					System.out.println("글입력 실패");
    					
    					request.setAttribute("page", "fail.jsp");
    				}
    			}
    			else if (command.equals("read")) 
    			{
    				String idx_ = request.getParameter("idx");
    				String requestPage_ = request.getParameter("requestPage");
    				System.out.printf("%s %s\n",idx_,requestPage_);
    				
    				int requestPage = 1;
    				if (requestPage_ != null) 
    					requestPage = Integer.parseInt(requestPage_);
    				
    				int idx = 0;
    				if (idx_ != null) 
    				{
    					idx = Integer.parseInt(idx_);
    					
    					BoardService service = BoardService.getInstance();
    					//	조회수가 1증가하고 해당 글에 대해 view를 해주는 작업
    					service.incrementReadCount(idx);
    					Board board = service.selectById(idx);
    					
    					request.setAttribute("board",board);
    					request.setAttribute("requestPage",requestPage);
    					request.setAttribute("page", "read.jsp");
    				}
    				else{request.setAttribute("page", "read_fail.jsp");}
    			}			
    			else if (command.equals("replyForm")) 
    			{
    				request.setAttribute("page", "replyForm.jsp");
    			}
    			else if (command.equals("reply.do")) 
    			{	
    				String parent_idx = request.getParameter("parent_idx");
    				String groupid = request.getParameter("groupid");
    				String depth = request.getParameter("depth");
    				String re_order = request.getParameter("re_order");
    				String title = request.getParameter("title");
    				String content = request.getParameter("content");
    				String write_id = request.getParameter("write_id");
    				String write_name = request.getParameter("write_name");
    				String requestPage_ = request.getParameter("requestPage");
    				
    				System.out.printf("parent_idx : %s\n",parent_idx);
    				System.out.printf("groupid : %s\n",groupid);
    				System.out.printf("depth : %s\n",depth);
    				System.out.printf("re_order : %s\n",re_order);
    				System.out.printf("title : %s\n",title);
    				System.out.printf("content : %s\n",content);
    				System.out.printf("write_id : %s\n",write_id);
    				System.out.printf("write_name : %s\n",write_name);
    				System.out.printf("requestPage : %s\n",requestPage_);
    				
    				Board board = new Board();
    				board.setIdx(Integer.parseInt(parent_idx));	//	주의<DB에 입력 시, 사용 안함> 부모가 존재하는 여부 확인
    				board.setTitle(title);
    				board.setContent(content);
    				board.setGroupid(Integer.parseInt(groupid));
    				board.setDepth(Integer.parseInt(depth) + 1);		//	기존의 depth에 1을 추가
    				board.setRe_order(Integer.parseInt(re_order) + 1);	//	기존 re_order에 1을 추가	
    				board.setWrite_id(write_id);
    				board.setWrite_name(write_name);
    				board.setWrite_day(new Date());
    				
    				int requestPage = 1;
    				if (requestPage_ != null) 
    					requestPage = Integer.parseInt(requestPage_);
    				
    				BoardService service = BoardService.getInstance();
    				
    				//	댓글은 
    				//		1. 부모 글이 존재하는지 여부 확인
    				//		2. 댓글과 상관이 있는 글에 대해 groupid, depth, [re_order]값을 변경
    				//				re_order는 잘 안 바뀐다.
    				//		3. 댓글이 등록
    				//	위의 과정의 의해 처리한다.
    				
    				//	위의 과정은 DB에서 한 번에 처리를 한다.
    				int result = service.replyInsert(board);
    				//request.setAttribute("requestPage",requestPage);
    				
    				if (result > 0)		//	댓글 입력 성공
    				{
    					PageBoard pageboard = new PageBoard();
    					pageboard = service.list(requestPage);
    					request.setAttribute("pageboard", pageboard);
    					
    					request.setAttribute("page", "list.jsp");
    				}
    				else				//	댓글 입력 실패
    				{
    					request.setAttribute("page", "reply_fail.jsp");
    				}
    			}
    			else if (command.equals("update")) 
    			{
    				//	read.jsp에서 이미 데이터를 전달했다.
    				request.setAttribute("page", "updateForm.jsp");
    			}//	else if 추가
    			else if (command.equals("update.do")) 
    			{	
    				//	업데이트 관련 내용 전달받기(trim 함수를 사용하여 전달 문자 공백 제거)
    				String idx_ = request.getParameter("idx"); 
    				String requestPage_ = request.getParameter("requestPage");
    				String title = request.getParameter("title");
    				String content = request.getParameter("content").trim();
    				
    				System.out.printf("idx : %s, requestPage : %s, title : %s, content : %s\n",
    						idx_,requestPage_,title,content);
    				
    				int requestPage = Integer.parseInt(requestPage_);
    				int idx = Integer.parseInt(idx_);
    				
    				Board board = new Board();
    				board.setIdx(idx);
    				board.setTitle(title);
    				board.setContent(content);
    				
    				BoardService service = BoardService.getInstance();
    				
    				int result = service.update(board);
    				
    				request.setAttribute("requestPage",requestPage);	//	요청한 페이지를 저장
    				
    				if (result == 1)	//	업데이트 성공
    				{
    					request.setAttribute("page", "update_success.jsp");
    				}
    				else				//	업데이트 실패
    				{
    					request.setAttribute("page", "update_fail.jsp");
    				}
    			}//	else if 추가
    			else if (command.equals("delete.do")) 
    			{
    				//	데이터를 얻어온다.
    				String idx_ = request.getParameter("idx");
    				int idx = Integer.parseInt(idx_);
    				
    				System.out.printf("idx : %s\n", idx_);
    				
    				Board board = new Board();
    				board.setIdx(idx);
    				
    				BoardService service = BoardService.getInstance();
    				
    				int result = service.delete(board);
    					
    				if (result == 1)	//	삭제 성공
    				{
    					request.setAttribute("page", "delete_success.jsp");
    				}
    				else				//	삭제 실패
    				{
    					request.setAttribute("page", "delete_fail.jsp");
    				}
    			}//	else if 추가
    			else
    			{
    				request.setAttribute("page", "list.jsp");
    			}
    		}
    		else{	request.setAttribute("page", "fail.jsp");	}
    		
    		//	2. 분류된 url을 선택하고 전송하는 작업
    		RequestDispatcher dispatcher = request.getRequestDispatcher(
    				"/WEB-INF/board/index.jsp"
    				);
    				
    		//	3. 페이지로 밀어주는 작업
    		dispatcher.forward(request, response);
    	}
    
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {}
    }

     

     

     

    뒤이어 아래를 구현해보자.

    designatedroom87.tistory.com/331?category=901206

     

    게시판 만들기 - 9. 검색 리스트 구현하기

    아래의 내용에 이어서 계속 구현할 것이다. designatedroom87.tistory.com/329 게시판 만들기 - 8. 글 수정 & 글 삭제 구현하기 로그인을 한 상태에서 게시글을 하나 선택했을 시에, 아래와 같이 나타난다.

    designatedroom87.tistory.com

     

    댓글

Designed by Tistory.