본문 바로가기
혼자서 개발새발

Spring) 게시판 글 수정을 만들어보자!

by 휴일이 2022. 11. 23.

 

글 수정을 만들어보자!!@

 

1) 수정 누르기

ㄴ 수정을 누르면 목록, 수정 버튼을 제외한 나머지 버튼이 사라져야함

2) 글 가져오고, 수정 가능한 상태 만들기

ㄴ 수정을 누르면 readonly를 풀고, 읽기에 있던 글 정보를 가져와야한다

3) 수정 누르면 정말 수정하시겠습니까? 뜨게 하기

4) 확인 누르면 수정 완료 또는 수정 실패

5) 본인 글이 아니면 수정이 안 됨

ㄴ 본인 글만 수정 가능하다고 뜨기

 

 

 

 

수정 도뎐 !

 

 

 

Controller

    @GetMapping("/modify")
    public String modify(HttpServletRequest request, Model m, BoardDto dto,Integer page, Integer pageSize, HttpSession session,
                         RedirectAttributes rattr) {
        if(loginCheck(request)) {
            return "login";
        }
        try {
            // dto 널체크
            if(dto == null) {
                throw new Exception("dto is null");
            }

            //글 읽어서 가져오기
            BoardDto boardDto = service.read(dto.getNo());
            if(boardDto == null) {
                throw new Exception("boardDto is null");
            }

            //본인 글 아니면 수정 못하게 하기
            String id = (String)session.getAttribute("id");
            if(!boardDto.getId().equals(id)) {
                rattr.addFlashAttribute("msg", "ID_DEF");
                return "redirect:/board/list?no="+dto.getNo()+"&page="+page+"&pageSize="+pageSize;
            }

            // 페이지 정보 가져오기
            m.addAttribute(boardDto);
            m.addAttribute("page", page);
            m.addAttribute("pageSize", pageSize);
            Page p = getPage(page, pageSize);
            m.addAttribute("p", p);
        } catch (Exception e) {
            e.printStackTrace();
            rattr.addFlashAttribute("msg", "MODI_ERR");
            return "redirect:/board/list?no="+dto.getNo()+"&page="+page+"&pageSize="+pageSize;
        }
        // 수정 모드로 바꾸기
        m.addAttribute("mode", "change");
        return "board";
    }

    @PostMapping("/modify")
    public String modify(BoardDto dto,HttpServletRequest request,RedirectAttributes rattr,Integer page, Integer pageSize,
                         HttpSession session) {
        if(loginCheck(request)) {
            return "login";
        }

        // DTO 널체크
        try {
            if(dto == null) {
                throw new Exception("dto is null");
            }
            String id = (String)session.getAttribute("id");
            dto.setId(id);
            // 게시물 수정
            int check = service.modify(dto);

            // 수정이 안 되면 오류 발생
            if(check == 0) {
                throw new Exception("modify failed");
            }

            rattr.addFlashAttribute("msg", "MODIFY OK");

        } catch(Exception e) {
            e.printStackTrace();
            System.out.println("e = " + e);
            rattr.addFlashAttribute("msg", "MODI_ERR");
            return "redirect:/board/list?no="+dto.getNo()+"&page="+page+"&pageSize="+pageSize;
        }

        return "redirect:/board/list";
    }

 

수정은 GET 메서드가 더 복잡하다

 

읽기로 글을 가져온다

본인 글이 아니면 수정을 못하게 한다

오류가 나면 원래 글로 돌아오기 위해 페이지 정보도 가져온다

mode에 change를 저장시켜서

수정모드로 갈 수 있게 도와준다

 

 

POST는 간단하게 수정만 하면 된다

 

 

 

 

board.jsp

 

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>게시판</title>
    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
</head>
<body>
<script>
    let msg = "${msg}";
    if(msg=="WRT_ERR") alert("등록 실패");
</script>
<div>

    <h2>게시물 ${mode == 'new' ? '쓰기' : mode == 'change' ? '수정' : '읽기'}</h2>
    <form id = "form" action="" method="POST">
        <input type="text" value="${boardDto.no}" name = "no" hidden>
        <input type="text" value="${p.page}" name = "page" hidden>
        <input type="text" value="${p.pageSize}" name = "pageSize" hidden>
        <table>
            <tr>
                <th>제목 <input type="text" id="title" name="title" value="${boardDto.title}" ${mode=="new" ? "" : mode == "change" ? "" : "readonly='readonly'"}></th>
            </tr>
            <tr>
                <c:if test="${mode ne 'new'}">
                <c:if test="${mode ne 'change'}">
                    <th><input type="text" id="id" name="id" value="${boardDto.id}" readonly></th>
                </c:if>
                </c:if>
            </tr>
            <tr>
                <td><textarea name="content" id="content" rows="20" ${mode=="new" ? "" : mode == "change" ? "" : "readonly='readonly'"}>${boardDto.content}</textarea></td>
            </tr>
        </table>
        <button type="button" id = "listBtn" onclick="location.href='/board/list?page=${p.page}&pageSize=${p.pageSize}'">목록</button>
        <c:if test="${mode ne 'new'}">
        <c:if test="${mode ne 'change'}">
            <button type="button" id = "removeBtn">삭제</button>
            <button type="button" id = "modifyNewBtn" onclick="location.href='/board/modify?no=${boardDto.no}&page=${p.page}&pageSize=${p.pageSize}'">수정</button> <br>
            <button type="button" id = "writeNewBtn" onclick="location.href='/board/write'">글쓰기</button>
        </c:if>
        </c:if>
        <c:if test="${mode eq 'new'}">
            <button type="button" id = "writeBtn">등록</button>
        </c:if>
        <c:if test="${mode eq 'change'}">
            <button type="button" id = "modifyBtn">수정</button>
        </c:if>
    </form>
</div>
<script>
    $(document).ready(function () {
        let formCheck = function () {
            let title = document.getElementById('title').value;
            let content = document.getElementById('content').value;
            if(title == "") {
                alert("제목을 입력하세요");
                document.getElementById('title').focus();
                return false;
            }
            if(content == "") {
                alert("내용을 입력하세요");
                document.getElementById('content').focus();
                return false;
            }
            return true;
        }
        $('#writeBtn').click(function () {
            $("#form").attr("method", "POST");
            $("#form").attr("action", "/board/write");
            if(formCheck())
                $("#form").submit();
        })
        $('#removeBtn').click(function () {
            if(!confirm("정말 삭제하시겠습니까?")) return;
            $("#form").attr("method", "GET");
            $("#form").attr("action", "/board/remove");
            $("#form").submit();
        })
        $('#modifyBtn').click(function () {
            if(!confirm("정말 수정하시겠습니까?")) return;
            $("#form").attr("method", "POST");
            $("#form").attr("action", "/board/modify");
            $("#form").submit();
        })
    })
</script>
</body>
</html>

 

 

글쓰기 / 글읽기 / 글수정은 다 다르기때문에

mode 가 new 일 때, change 일 때, 없을 때 조건을 다르게 해서 적용시켰다

(중첩)삼항연산자를 유용하게 사용했다!

 

<h2>게시물 ${mode == 'new' ? '쓰기' : mode == 'change' ? '수정' : '읽기'}</h2>

요것이 중첩 삼항 연산자

 

 

boardList.jsp

<script>
    let msg = "${msg}";
    if(msg == "WRITE OK") alert("등록 완료");
    if(msg == "DELETE OK") alert("삭제 완료");
    if(msg == "MODIFY OK") alert("수정 완료");
    if(msg=="DEL_ERR") alert("삭제 실패");
    if(msg=="MODI_ERR") alert("수정 실패");
    if(msg=="ID_DEF") alert("본인 글만 수정 가능합니다");
</script>

 

각 메세지에 따라 알맞은 결과도 주도록 했다

 

 

 

결과는?

게시글에 들어가서 수정 버튼을 누르면?

 

 

요런 식으로 뜬다

 

 

수정 버튼을 누르면?

 

 

수정 확인을 한다

 

 

 

확인을 누르면 수정 완료!!

 

 

 

289번 글이 수정 완료 되었다

 

본인 글이 아닌데 수정을 누르면?

 

 

 

오류가 뜬다잉

 

 

 

수정 완뇨~

다음엔 댓글 기능을 쥬도록 하겟당

728x90