Servlet-JSP/Servlet-JSP 답변형 게시판 만들기

Servlet/JSP 답변형 게시판 만들기 - 수정

voider 2020. 9. 11. 22:50

com.test.dao.BoardDAOTest

테스트 코드


    @Test
    public void updateTest() throws ClassNotFoundException {
        Class.forName(DRIVER);
        String sql = "UPDATE t_board " + 
                " set title = ?, content= ?" + 
                " where bno = ?";
        log.info(sql);

        try(
            Connection conn = DriverManager.getConnection(URL,USER,PW);
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ) {

            pstmt.setString(1, "update");
            pstmt.setString(2, "con...ten...t...");
            pstmt.setInt(3, 1);

            //성공하면 1
            int result = pstmt.executeUpdate();

            assertTrue(result==1);

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

com.coco.dao.BoardDAO

매개변수를 추가하고, 커넥션을 바꾼 뒤에 프로젝트에 추가한다.

    public int update(BoardVO vo) {
        String sql = "UPDATE t_board " + 
                " set title = ?, content= ?" + 
                " where bno = ?";

        log.info("vo : " + vo);

          try(
            Connection conn = ds.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ) {

            pstmt.setString(1, vo.getTitle());
            pstmt.setString(2, vo.getContent());
            pstmt.setInt(3, vo.getBno());

            return pstmt.executeUpdate();

            } catch (Exception e) {
                e.printStackTrace();
            }

        return -1;
    } //update()

com.coco.dao.service.BoardServiceImpl

package com.coco.service;

import java.util.List;

import com.coco.dao.BoardDAO;
import com.coco.vo.BoardVO;

public class BoardServiceImpl implements BoardService {

    private BoardDAO dao;

    public BoardServiceImpl() {
        //초기화
        dao = new BoardDAO();
    }

    @Override
    public List<BoardVO> getList() {
        return dao.getList();
    }

    @Override
    public int register(BoardVO vo) {
        return dao.insert(vo);
    }

    @Override
    public BoardVO getPost(int no) {
        return dao.getPost(no);
    }

    @Override
    public int modify(BoardVO vo) {
        return dao.update(vo);
    }
}

com.coco.controller.Controller

    private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BoardService boardService = new BoardServiceImpl();
        String nextPage = "";
        String action = request.getPathInfo();    //어떤 url을 요청했는가?
        List<BoardVO> list;
        log.info("action : " + action);
        ...
        ...

     else if(action.equals("/modify")) {
                 //수정한 데이터를 받는다.
            String title = request.getParameter("title");
            String content = request.getParameter("content");
            int bno = Integer.parseInt(request.getParameter("bno"));
            BoardVO vo = new BoardVO();

            //수정한 데이터로 vo초기화
            vo.setBno(bno);
            vo.setTitle(title);
            vo.setContent(content);

            log.info("VO : " + vo);

                   //수정하는 메서드 호출
            boardService.modify(vo);

                  //내가 수정한 게시물로 이동
            nextPage = "/board/post?no="+bno;
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
        dispatcher.forward(request, response);
    }

post.jsp

수정하는 페이지를 따로 만들지 않고, 자바스크립트를 이용하여 조회페이지에서 바로 수정할 수 있도록 했다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>[${post.bno}번 게시물] ${post.title }</title>
</head>
<body>
<h1>게시물 조회</h1>
<form id='action'>
    <table>
        <tr>
            <td width="20%" align="center"> 제목 </td>
            <td> <input type='text' id='title' name='title' value='${post.title }' disabled></td>
        </tr>
        <tr>
            <td width="20%" align="center"> 내용 </td>
            <td>
                <textarea rows="20" cols="60" id='content' name='content' disabled>${post.content }</textarea>
            </td>
        </tr>
        <tr>
            <td width="20%" align="center"> 작성자 </td> 
            <td><input type='text' id='id' name='id' value='${post.id }' disabled></td> 
        </tr>
        <tr id="modBtn" style='display:none;'>
            <td colspan="2"   align="center" >
            <input type=button id='mod' value="수정 완료">
             <input type=button id='back' value="취소">
               </td>   
         </tr>
        <tr id="btn">
            <td colspan="2" align="center">
            <input type='button' id='modify' value='수정'>
            <input type='button' id='remove' value='삭제'> 
            <input type='button' id='list' value='목록'>
            <input type='button' id='rePost' value='답글'></td> 
        </tr>
    </table>

    <input type='hidden' id='bno' name='bno' value='${post.bno }'>
    </form>

<script>
    window.onload = () => {
        const remove = document.getElementById('remove')
        const list = document.getElementById('list')
        const rePost = document.getElementById('rePost')
        const modify = document.getElementById('modify')
        const actionForm = document.getElementById('action')

        console.log(remove)
        console.log(list)
        console.log(rePost)

        //목록으로
        list.addEventListener("click", () => {
            location.replace('/board/list')
        })

        //수정 버튼 이벤트
        modify.addEventListener("click", ()=>{
            document.getElementById('title').disabled=false
            document.getElementById('content').disabled=false
            document.getElementById("modBtn").style.display="block"
            document.getElementById('btn').style.display="none"

        })

        //수정 완료
        document.getElementById('mod').addEventListener("click", () => {
            actionForm.action = '/board/modify'
            actionForm.method = 'post';
            actionForm.submit();
        })

        //수정 취소
        document.getElementById('back').addEventListener("click", () => {
            document.getElementById('btn').style.display="block"
            document.getElementById("modBtn").style.display="none";
            document.getElementById('content').disabled=true
            document.getElementById('title').disabled=true
        })


        //삭제
        remove.addEventListener("click", () => {
            if(!confirm("삭제하겠습니까?")) { return; }
            else{
                //....
            }
        }) 
    }
</script>
</body>
</html>