게시글 상세보기 페이지 처리

command.properties

1
/board/view.do=board.controller.BoardViewAction
cs

 

[Controller] BoardViewAction

[경로: src/main/java/board.controller/BoardViewAction.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
public class BoardViewAction extends AbstractAction {
 
    @Override
    public void execute(HttpServletRequest req, HttpServletResponse res) throws Exception {
        /*list.jsp
         * <a href="view.do?num=${board.num}">${board.title}</a>
         * */
        String numStr = req.getParameter("num");
        if(numStr==null) {
            this.setRedirect(true); //redirect방식으로 이동
            this.setViewName("list.do");
            return;
        }
        int num = Integer.parseInt(numStr.trim());
        BoardDAO dao = new BoardDAO();
        //1. 조회수 증가
        dao.updateReadnum(num);
        
        //2. 해당 글 가져오기
        BoardVO vo = dao.getBoard(num);
        
        //반환되는 BoardVO 객체를 req에 저장
        req.setAttribute("vo", vo);
        
        //뷰페이지 지정
        this.setViewName("/board/view.jsp");
        //이동방식 지정(forward)
        this.setRedirect(false);
    }
 
}
cs

 

[Model] BoardDAO

[경로: src/main/java/board.model/BoardDAO.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
/**조회수 증가*/
    public void updateReadnum(int num) throws SQLException{
        try {
            con = ds.getConnection();
            StringBuffer buf = new StringBuffer("UPDATE mvc_board SET")
                    .append(" readnum = readnum + 1 WHERE num = ?");
            String sql = buf.toString();
            ps = con.prepareStatement(sql);
            ps.setInt(1, num);
            ps.executeUpdate();
        } finally {
            close();
        }
    }
 
/**글번호(PK)로 글 내용 보기*/
    public BoardVO getBoard(int num) throws SQLException{
        try {
            con = ds.getConnection();
            String sql = "SELECT * FROM mvc_board WHERE num = ?";
            ps = con.prepareStatement(sql);
            ps.setInt(1, num);
            rs = ps.executeQuery();
            List<BoardVO> arr = makeList(rs);
            if(arr==null || arr.size()==0) {
                return null;
            }
            BoardVO vo = arr.get(0); //하나만 반환하므로
            return vo;
        } finally {
            close();
        }
    }
/**BoardVO의 객체를 ArrayList에 담기*/
    public List<BoardVO> makeList(ResultSet rs) throws SQLException{
        List<BoardVO> arr = new ArrayList<>();
        while(rs.next()) {
            int num = rs.getInt("num");
            String name = rs.getString("name");
            String passwd = rs.getString("passwd");
            String title = rs.getString("title");
            String content = rs.getString("content");
            java.sql.Date wdate = rs.getDate("wdate");
            int readnum = rs.getInt("readnum");
            String fileName = rs.getString("fileName");
            long fileSize = rs.getLong("fileSize");
            BoardVO record = new BoardVO(num, name, passwd, title, content, wdate, readnum, fileName, fileSize);
            arr.add(record);
        }
        
        return arr;
    }
cs

 

[View] view.jsp

[경로: src/main/webapp/board/view.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<div class="container">
<h1>MVC Board</h1>
<br><br>
<c:if test="${vo eq null}"> <%-- vo==null --%>
    <script>
        alert('해당 글은 존재하지 않습니다');
        history.back();
    </script>
</c:if>
<c:if test="${vo ne null}"> <%-- vo!=null --%>
    <table border="1">
        <tr>
            <td width="20%" class="m1"><b>글번호</b></td>
            <td width="30%">${vo.num}</td>
            <td width="20%" class="m1"><b>작성일</b></td>
            <td width="30%">${vo.wdate}</td>
        </tr>
        <tr>
            <td width="20%" class="m1"><b>글쓴이</b></td>
            <td width="30%">${vo.name}</td>
            <td width="20%" class="m1"><b>조회수</b></td>
            <td width="30%">${vo.readnum}</td>
        </tr>
        <tr>
            <td width="20%" class="m1"><b>첨부파일</b></td>
            <td colspan="3" class="text-left">&nbsp; 
            <!-- 첨부파일이 있다면 --> 
            <c:if test="${vo.fileName ne null}">
            <a href="${pageContext.request.contextPath}/upload/${vo.fileName}" download>${vo.fileName}</a> 
            <%-- request.getContextPath()와 동일 
            ${pageContext.request.contextPath}: MyMVC 반환
            --%>
            [ ${vo.fileSize} ]bytes
            </c:if>
            </td>
        </tr>
        <tr>
            <td width="20%" class="m1"><b>제목</b></td>
            <td colspan="3">${vo.title}</td>
        </tr>
        <tr>
            <td width="20%" class="m1"><b>글내용</b></td>
            <td colspan="3" style="height:180px">
            <!-- <pre>태그로 감싸기: 엔터값 나오게 -->
            <pre>${vo.content}</pre>
            </td>
        </tr>
   </table>
</c:if>
cs

실행 결과

 


글삭제 처리

command.properties

1
/board/delete.do=board.controller.BoardDeleteAction
cs

 

[View] view.jsp 수정

[경로: src/main/webapp/board/view.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
<c:if test="${vo ne null}"> <%-- vo!=null --%>
<table>
    <tr>
        <td colspan="4" class="text-center">
          <a href="list.do">글목록</a>          
        <a href="#" onclick="goEdit()">글수정</a>|
        <a href="#" onclick="goDel()">글삭제</a>
        </td>
    </tr>
</table>
</c:if>
 
<br><br>
    <div id="divPasswd" style="display:none">
        <!--  수정 또는 삭제시 사용할 form -------------------- -->
        <form id="frm" method="post">
            <input type="hidden" name="num" value="${vo.num}">
                <!-- 수정 또는 삭제할 글번호롤 hidden으로 넘기자 -->
            <label for="passwd">비밀번호</label>
            <input type="password" name="passwd" id="passwd"
            placeholder="글비밀번호" required style="width:25%">
            <button class="btn" id="btn"></button>
        </form>
    </div>
<script>
let obj = document.querySelector('#divPasswd');
let btn1 = document.querySelector('#btn');
let frm = document.querySelector('#frm');
    
    const goDel = function(){
        obj.style.display = 'block'/* display:none에서 block으로 바꿈 */
        btn1.innerText = '글삭제';
        frm.action = 'delete.do';
    }
    const goEdit = function(){
        obj.style.display = 'block';
        btn1.innerText = '글수정';
        frm.action = 'update.do';
    }
</script>
cs

{"originWidth":1402,"originHeight":662,"style":"alignCenter","caption":"실행 결과: 하단의 글목록

 

[Controller] BoardDeleteAction

[경로: src/main/java/board.controller/BoardDeleteAction.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
public class BoardDeleteAction extends AbstractAction {
 
    @Override
    public void execute(HttpServletRequest req, HttpServletResponse res) throws Exception {
        //1. 글번호(hidden num), 비밀번호 값 받기
        String numStr = req.getParameter("num");
        String passwd = req.getParameter("passwd");
        //2. 유효성 체크 list.do로 이동(redirect)
        if(numStr==null || passwd==null || 
                numStr.trim().isBlank() || passwd.trim().isEmpty()) {
            this.setRedirect(true); //redirect이동
            this.setViewName("list.do");//list.do로 redirect이동
            return;
        }
        int num = Integer.parseInt(numStr.trim());
        //3. 글번호로 해당 글을 DB에서 가져오기(getBoard)
        BoardDAO dao = new BoardDAO();
        BoardVO tmp = dao.getBoard(num);
        
        //4. 해당 글의 비밀번호와 사용자가
        //[1] 입력한 비밀번호가 일치하면 삭제 처리 => BoardDAO의 deleteBoard(num) => msg, loc처리
        //[2] 일치하지 않으면 "비밀번호가 틀려요", history.back()
        String msg = "", loc = "";
        if(!passwd.equals(tmp.getPasswd())) {
            msg = "비밀번호가 일치하지 않아요";
            loc = "javascript:history.back()";
        }else {
            int n = dao.deleteBoard(num);
            msg = (n>0)? "삭제 성공":"삭제 실패";
            loc = (n>0)? "list.do":"javascript:history.back()";
        }
        
        req.setAttribute("msg", msg);
        req.setAttribute("loc", loc);
        this.setViewName("/board/message.jsp");
        this.setRedirect(false); //forward이동
    }
 
}
cs

 

[Model] BoardDAO

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
/**글번호(PK)로 글 내용 보기*/
    public BoardVO getBoard(int num) throws SQLException{
        try {
            con = ds.getConnection();
            String sql = "SELECT * FROM mvc_board WHERE num = ?";
            ps = con.prepareStatement(sql);
            ps.setInt(1, num);
            rs = ps.executeQuery();
            List<BoardVO> arr = makeList(rs);
            if(arr==null || arr.size()==0) {
                return null;
            }
            BoardVO vo = arr.get(0); //하나만 반환하므로
            return vo;
        } finally {
            close();
        }
    }
 
public int deleteBoard(int num) throws SQLException {
        try {
            con = ds.getConnection();
            String sql = "DELETE FROM mvc_board WHERE num = ?";
            ps = con.prepareStatement(sql);
            ps.setInt(1, num);
            return ps.executeUpdate();
        } finally {
            close();
        }
    }
cs

 

[View] message.jsp

[경로: src/main/webapp/board/message.jsp]

1
2
3
4
5
6
7
8
9
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<script type="text/javascript">
    alert('${msg}');
    location.href = '${loc}';
</script>
cs

 


글수정 처리

command.properties

1
2
/board/update.do=board.controller.BoardUpdateFormAction
/board/updateEnd.do=board.controller.BoardUpdateAction
cs

 

[Controller] BoardUpdateFormAction

[경로: src/main/java/board.controller/BoardUpdateFormAction.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
public class BoardUpdateFormAction extends AbstractAction {
 
    @Override
    public void execute(HttpServletRequest req, HttpServletResponse res) throws Exception {
        //1. 글번호, 비밀번호 받기
        String numStr = req.getParameter("num");
        String passwd = req.getParameter("passwd");
        //2. 유효성 체크
        if(numStr==null || passwd==null || 
                numStr.trim().isBlank() || passwd.trim().isEmpty()) {
            this.setRedirect(true); //redirect이동
            this.setViewName("list.do");//list.do로 redirect이동
            return;
        }
        int num = Integer.parseInt(numStr.trim());
        //3. DB에서 해당 글 가져오기
        BoardDAO dao = new BoardDAO();
        BoardVO tmp = dao.getBoard(num);
        
        //4. 비밀번호 일치 여부 체크
        //비밀번호 일치하면 3번에서 가져온 vo객체 req에 저장
        if(tmp.getPasswd().equals(passwd)) {//비밀번호 일치
            req.setAttribute("board", tmp);
            this.setViewName("/board/edit.jsp");//뷰페이지 지정
            this.setRedirect(false);//이동방식 설정(forward)
        }else {//비밀번호 일치하지 않으면
            req.setAttribute("msg""비밀번호가 일치하지 않아요");
            req.setAttribute("loc""javascript:history.back()");
            this.setViewName("/board/message.jsp");
            this.setRedirect(false);
        }    
        
    }
 
}
cs

 

[View] edit.jsp (비밀번호 일치하면 이동하는 화면)

[경로: src/main/webapp/board/edit.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!-- bbs관련 js 파일 참조 ------------- -->
 
<!-- ------------------------------ -->
<!-- content -->
<div class="container">
    <h1>MVC Board 글수정</h1>
    <br><br>
<c:choose>
    <c:when test="${board eq null}">
        <script>
            alert('해당 글은 존재하지 않습니다');
            history.back();
        </script>
    </c:when>
    <c:otherwise>
    <!-- 파일 업로드: post, enctype="multipart/form-data" -->
    <form name="bbsF" method="post" action="updateEnd.do" enctype="multipart/form-data">
    <!-- hidden field 글번호 ------------- -->
    <input type="hidden" name="num" value="${board.num}">
    <!-- ------------------------------- -->
        <table border="1">
            <tr>
                <th width="20%">글제목</th>
                <td width="80%">
                    <input type="text" name="title" value="${board.title}"
                    id="title" placeholder="Title" required>
                </td>
            </tr>
            <tr>
                <th>작성자</th>
                <td>
                    <input type="text" name="name" value="${board.name}"  
                    id="name" placeholder="Name" required>
                </td>
            </tr>
            <tr>
                <th>글내용</th>
                <td>
                    <textarea name="content" id="content" placeholder="Content"
                    rows="7" cols="60">${board.content}</textarea>
                </td>
            </tr>
            <tr>
                <th>비밀번호</th>
                <td>
                    <input type="password" name="passwd" id="passwd" placeholder="Password" required>
                </td>
            </tr>
            <tr>
                <th>첨부파일</th>
                <td>
                    <c:if test="${board.fileName ne null}">
                    ${board.fileName} [${board.fileSize} bytes]
                    <br>
                    </c:if>
                    <!-- 옛 첨부파일을 hidden으로 넘기자 ------------------- -->
                    <input type="hidden" name="old_fileName" value="${board.fileName}">
                    <!-- -------------------------------------------- -->
                    <input type="file" name="fileName" id="fileName">
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align:center">
                    <button>글수정</button>
                    <button type="reset">다시쓰기</button>
                </td>
            </tr>
        </table>
    </form>
    </c:otherwise>
</c:choose>
</div>
cs

edit.jsp 화면

 


글수정 확정 처리

[Controller] BoardUpdateAction

[경로: src/main/java/board.controller/BoardUpdateAction.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
public class BoardUpdateAction extends AbstractAction {
 
    @Override
    public void execute(HttpServletRequest req, HttpServletResponse res) throws Exception {
        //1. 글번호, 제목, 작성자, 내용, 비밀번호, 첨부파일 받기
        String numStr = mreq.getParameter("num");
        String title = mreq.getParameter("title");
        String name = mreq.getParameter("name");
        String content = mreq.getParameter("content");
        String passwd = mreq.getParameter("passwd");
        
        //2. 유효성 체크
        if(numStr==null|| title==null || name==null || passwd==null || numStr.trim().isBlank()
            || title.trim().isBlank() || name.trim().isBlank() || passwd.trim().isBlank()) {
            this.setRedirect(true); //redirect이동
            this.setViewName("update.do"); //update.do로 redirect이동
            return;
        }
        int num = Integer.parseInt(numStr.trim());
        //3. 1번에서 받은 값을 BoardVO에 담기
        BoardVO vo = new BoardVO(num, name, passwd, title, content, null0, fileName, fileSize);
        //4. BoardDAO의 updateBoard(vo) 호출
        BoardDAO dao = new BoardDAO();
        int n = dao.updateBoard(vo);
        
        //5. 그 결과 메시지, 이동경로 처리
        String msg = (n>0)? "글수정 성공":"글수정 실패";
        String loc = (n>0)? "list.do":"javascript:history.back()";
        req.setAttribute("msg", msg);
        req.setAttribute("loc", loc);
        
        this.setViewName("/board/message.jsp");
        this.setRedirect(false);
    }
 
}
cs

 

[Model] BoardDAO

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
    public int updateBoard(BoardVO vo) throws SQLException {
        try {
            con = ds.getConnection();
            StringBuffer buf = new StringBuffer("UPDATE mvc_board SET name = ?, passwd = ?,")
                    .append(" title = ?, content = ? ");
                    if(vo.getFileName()!=null) {//첨부파일이 있다면
                        buf.append(" , fileName = ?, fileSize = ? ");
                    }
                    buf.append(" WHERE num = ?");
            String sql = buf.toString();
            System.out.println(sql);
            ps = con.prepareStatement(sql);
            ps.setString(1, vo.getName());
            ps.setString(2, vo.getPasswd());
            ps.setString(3, vo.getTitle());
            ps.setString(4, vo.getContent());
            if(vo.getFileName()!=null) {
                ps.setString(5, vo.getFileName());
                ps.setLong(6, vo.getFileSize());
                ps.setInt(7, vo.getNum());
            }else {
                ps.setInt(5, vo.getNum());
            }
            
            return ps.executeUpdate();            
        } finally {
            close();
        }
        
    }
cs

실행 결과

 

+ Recent posts