MyBatis

5. 게시판 읽기, 쓰기, 삭제, 수정 기능구현(1) - 패스트캠퍼스 백엔드 부트캠프 3기

gkss2tpt 2025. 3. 3. 16:22

1. 기능별 URI 정의

  • URL : 리소스 경로(전체 경로)
  • URI : 유일한 이름(URL일부 경로)

 

2. 게시물 읽기 기능의 구현

  • board.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<body>
<head>
    <meta charset="UTF-8">
    <title>fastcampus</title>
    <link rel="stylesheet" href="<c:url value='/css/menu.css'/>">
</head>
<div id="menu">
    <ul>
        <li id="logo">fastcampus</li>
        <li><a href="<c:url value='/'/>">Home</a></li>
        <li><a href="<c:url value='/board/list'/>">Board</a></li>
        <li><a href="<c:url value='/login/login'/>">login</a></li>
        <li><a href="<c:url value='/register/add'/>">Sign in</a></li>
        <li><a href=""><i class="fas fa-search small"></i></a></li>
    </ul>
</div>
<div style ="text-align:center">
    <h2>게시물 읽기</h2>
   <form action="" id="form">
       <input type="text" name="bno" value="${boardDto.bno}" readonly="readonly">
       <input type="text" name="title" value="${boardDto.title}" readonly="readonly">
       <textarea name="content" id="" cols="30" rows="10" readonly="readonly">${boardDto.content}</textarea>
       <button type="button" id="writeBtn" class="btn">등록</button>
       <button type="button" id="modifyBtn" class="btn">수정</button>
       <button type="button" id="removeBtn" class="btn">삭제</button>
       <button type="button" id="listBtn" class="btn">목록</button>
   </form>
</div>
</body>
</html>

 

  • 목록을 누르면 BoardController에 Get요청이가고 list() 메서드가 호출이되고 boardService를통해 getPage를 실행 가져온 Page를 List<BoardDto>에 담아서  반환한 것을 BoardList에 구현

  • boardList.jsp(var 이름을 boardDto로 변경하고 들어온갈 게시물 번호, 들어온 페이지, 페이지 사이즈를 넘겨준다.)
<c:forEach var="boardDto" items="${list}">
<tr>
    <td>${boardDto.bno}</td>
    <td><a href="<c:url value='/board/read?bno=${boardDto.bno}&page=${ph.page}&pageSize=${ph.pageSize}'/>">${boardDto.title}</a></td>
    <td>${boardDto.writer}</td>
    <td>${boardDto.reg_date}</td>
    <td>${boardDto.view_cnt}</td>
</tr>
</c:forEach>
  • boardList.jsp에 page와 pageSize를 모델에 담아서 보내줘야하기때문에 BoardController의 list()메서드의 Model에 page와 pageSize를 추가
@GetMapping("/list")
public String list(Integer page, Integer pageSize, HttpServletRequest request, Model m){
    if(!(loginCheck(request)))
        return "redirect:/login/login?toURL="+request.getRequestURL();

    if(page==null) page=1;
    if(pageSize==null) pageSize=10;

    try{
        int totalCnt = boardService.getCount();
        PageHandler pageHandler = new PageHandler(totalCnt,page, pageSize);

        Map map = new HashMap();
        map.put("offset", (page-1)*pageSize);
        map.put("pageSize", pageSize);

        List<BoardDto> list = boardService.getPage(map);
        m.addAttribute("list", list);
        m.addAttribute("ph", pageHandler);
        m.addAttribute("page", page);
        m.addAttribute("pageSize", pageSize);
    }catch(Exception e){
        e.printStackTrace();
    }

    return "boardList";
}
  • list()메서드에서 넘겨준 page와 pageSize가 boardList.jsp 뷰를 통해서 read()메서드로 넘어왔고, 다시 모델에 담아서 board.jsp로 넘겨준다.
@GetMapping("/read")
    public String read(Integer bno, Integer page, Integer pageSize, Model m){
        try {
            BoardDto boardDto = boardService.read(bno);
//            m.addAttribute("boardDto",boardDto);
            m.addAttribute(boardDto);
            m.addAttribute("page", page);
            m.addAttribute("pageSize", pageSize);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return "board";
    }
  • JQuery를 사용해서 받아보겠다.

  • board.jsp에 jquery를 추가하고 다운로드
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<body>
<head>
    <meta charset="UTF-8">
    <title>fastcampus</title>
    <link rel="stylesheet" href="<c:url value='/css/menu.css'/>">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<div id="menu">
    <ul>
        <li id="logo">fastcampus</li>
        <li><a href="<c:url value='/'/>">Home</a></li>
        <li><a href="<c:url value='/board/list'/>">Board</a></li>
        <li><a href="<c:url value='/login/login'/>">login</a></li>
        <li><a href="<c:url value='/register/add'/>">Sign in</a></li>
        <li><a href=""><i class="fas fa-search small"></i></a></li>
    </ul>
</div>
<div style ="text-align:center">
    <h2>게시물 읽기</h2>
   <form action="" id="form">
       <input type="text" name="bno" value="${boardDto.bno}" readonly="readonly">
       <input type="text" name="title" value="${boardDto.title}" readonly="readonly">
       <textarea name="content" id="" cols="30" rows="10" readonly="readonly">${boardDto.content}</textarea>
       <button type="button" id="writeBtn" class="btn">등록</button>
       <button type="button" id="modifyBtn" class="btn">수정</button>
       <button type="button" id="removeBtn" class="btn">삭제</button>
       <button type="button" id="listBtn" class="btn">목록</button>
   </form>
</div>
<script>
    $(document).ready(function(){   // main()
        // listBtn을 클릭하면 일어날일을 정의
        $('#listBtn').on("click", function(){
            // board/list로 돌아가기
            location.href = "<c:url value='/board/list'/>?page=${page}&pageSize=${pageSize}";
        });
    });
</script>
</body>
</html>
  • script를 추가해주고 실행하면...

  • 잘들어가지고... 목록을 누르면 다시 원래 있던 페이지로 이동한다.

3. 게시물 삭제 기능의 구현

  • BoardController 클래스
@PostMapping("/remove")
public String remove(Integer bno, Integer page, Integer pageSize, Model m, HttpSession session){
    String writer = (String)session.getAttribute("id");
    try{
        boardService.remove(bno, writer);
    }catch(Exception e){
        e.printStackTrace();
    }

    m.addAttribute("page",page);
    m.addAttribute("pageSize",pageSize);

    return "redirect:/board/list";
}
  • boardService.remove메서드로 삭제하고 다시 원래있던 페이지로 돌아가는 remove메서드
<script>
    $(document).ready(function(){   // main()
        // listBtn을 클릭하면 일어날일을 정의
        $('#listBtn').on("click", function(){
            // board/list로 돌아가기
            location.href = "<c:url value='/board/list'/>?page=${page}&pageSize=${pageSize}";
        });
        $('#removeBtn').on("click",function(){
            // id가 form인 요소에 대한 참조를 얻어서 form에 저장
            let form = $('#form');
            form.attr("action", "<c:url value='/board/remove'/>?page=${page}&pageSize=${pageSize}");
            form.attr("method", "post");
            form.submit();
        });
    });
</script>
  • asdf로 로그인후 삭제를 누르면

  • 삭제완료

  • confirm추가
<script>
    $(document).ready(function(){   // main()
        // listBtn을 클릭하면 일어날일을 정의
        $('#listBtn').on("click", function(){
            // board/list로 돌아가기
            location.href = "<c:url value='/board/list'/>?page=${page}&pageSize=${pageSize}";
        });
        $('#removeBtn').on("click",function(){
            if(!confirm("정말로 삭제하시겠습니까?")) return;
            // id가 form인 요소에 대한 참조를 얻어서 form에 저장
            let form = $('#form');
            form.attr("action", "<c:url value='/board/remove'/>?page=${page}&pageSize=${pageSize}");
            form.attr("method", "post");
            form.submit();
        });
    });
</script>
  • 삭제를 누르면 확인창이 나온다. 확인하면 삭제완료

  • msg추가하기 BoardController 클래스
@PostMapping("/remove")
public String remove(Integer bno, Integer page, Integer pageSize, Model m, HttpSession session){
    String writer = (String)session.getAttribute("id");
    try{
        int rowCnt = boardService.remove(bno, writer);

        m.addAttribute("page",page);
        m.addAttribute("pageSize",pageSize);
        if(rowCnt==1){
            m.addAttribute("msg", "DEL_OK");
            return "redirect:/board/list";
        }

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

    return "redirect:/board/list";
}
  • boardList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<body>
<head>
    <meta charset="UTF-8">
    <title>fastcampus</title>
    <link rel="stylesheet" href="<c:url value='/css/menu.css'/>">
</head>
<div id="menu">
    <ul>
        <li id="logo">fastcampus</li>
        <li><a href="<c:url value='/'/>">Home</a></li>
        <li><a href="<c:url value='/board/list'/>">Board</a></li>
        <li><a href="<c:url value='/login/login'/>">login</a></li>
        <li><a href="<c:url value='/register/add'/>">Sign in</a></li>
        <li><a href=""><i class="fas fa-search small"></i></a></li>
    </ul>
</div>
<script>
    let msg = "${param.msg}"
    if(msg=="DEL_OK") alert("성공적으로 삭제되었습니다.");
</script>
<div style ="text-align:center">
    <table border="1">
        <tr>
            <th>번호</th>
            <th>제목</th>
            <th>이름</th>
            <th>등록일</th>
            <th>조회수</th>
        </tr>
        <c:forEach var="boardDto" items="${list}">
        <tr>
            <td>${boardDto.bno}</td>
            <td><a href="<c:url value='/board/read?bno=${boardDto.bno}&page=${ph.page}&pageSize=${ph.pageSize}'/>">${boardDto.title}</a></td>
            <td>${boardDto.writer}</td>
            <td>${boardDto.reg_date}</td>
            <td>${boardDto.view_cnt}</td>
        </tr>
        </c:forEach>
    </table>
        <br>
        <div>
            <c:if test="${ph.showPrev}">
                <a href="<c:url value='/board/list?page=${ph.beginPage-1}&pageSize=${ph.pageSize}'/>">&lt;</a>
            </c:if>
            <c:forEach var="i" begin="${ph.beginPage}" end="${ph.endPage}">
                <a href="<c:url value='/board/list?page=${i}&pageSize=${ph.pageSize}'/>">${i}</a>
            </c:forEach>
            <c:if test="${ph.showNext}">
                <a href="<c:url value='/board/list?page=${ph.endPage+1}&pageSize=${ph.pageSize}'/>">&gt;</a>
            </c:if>

        </div>
</div>
</body>
</html>
  • 삭제가 성공하면 msg가 나온다.

  • 447번 게시물의 bno의 readonly를 삭제하고 변경해주면...
@PostMapping("/remove")
public String remove(Integer bno, Integer page, Integer pageSize, Model m, HttpSession session){
    String writer = (String)session.getAttribute("id");
    try{
        int rowCnt = boardService.remove(bno, writer);

        m.addAttribute("page",page);
        m.addAttribute("pageSize",pageSize);
        if(rowCnt!=1)
            throw new Exception("board remove error");

        m.addAttribute("msg", "DEL_OK");
    }catch(Exception e){
        e.printStackTrace();
        m.addAttribute("msg", "DEL_ERR");
    }

    return "redirect:/board/list";
}
  • boardList.jsp에 추가
<script>
    let msg = "${param.msg}"
    if(msg=="DEL_OK") alert("성공적으로 삭제되었습니다.");
    if(msg=="DEL_ERR") alert("삭제에 실패했습니다.")
</script>

  • 삭제에 실패

  • 447번 게시물도 삭제되지않았다.

  • 그런데 새로고침시에 계속 삭제에 실패했다고 나오는데...

  • RedirectAttributes를 매개변수로 선언 -> addFlashAttribute로 한번만 사용가능한 값을 모델대신 넘겨준다.
@PostMapping("/remove")
public String remove(Integer bno, Integer page, Integer pageSize, Model m, HttpSession session, RedirectAttributes rattr){
    String writer = (String)session.getAttribute("id");
    try{
        int rowCnt = boardService.remove(bno, writer);

        m.addAttribute("page",page);
        m.addAttribute("pageSize",pageSize);
        if(rowCnt!=1)
            throw new Exception("board remove error");

        rattr.addFlashAttribute("msg", "DEL_OK");
    }catch(Exception e){
        e.printStackTrace();
        rattr.addFlashAttribute("msg", "DEL_ERR");
    }

    return "redirect:/board/list";
}
  • boardList.jsp도 변경해주면...
<script>
    let msg = "${msg}"
    if(msg=="DEL_OK") alert("성공적으로 삭제되었습니다.");
    if(msg=="DEL_ERR") alert("삭제에 실패했습니다.")
</script>
  • 삭제 실패후...

  • 새로고침을 해도 다시 메시지가 나오지 않는다.