1. 기능별 URI정의

       
  URL Uniform Resource Locator 웹페이지, 이미지, 동영상 등 인터넷상의 리소스 위치를 지정하는 웹 주소
  URI  Uniform Resource Identifier 터넷에서 이름이나 리소스를 식별하는 일련의 문자열
  URN Uniform Resource Name 인터넷에서 리소스에 대해 영구적이고 위치 독립적인 이름을 제공
인터넷에서 리소스의 위치를 ​​지정하는 URL과 달리 URN은 다양한 컨텍스트에서 리소스를 참조하는 데 사용할 수 있는 리소스 이름을 제공

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

읽기 → 목록


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

 


@Controller
@RequestMapping("/board")
public class BoardController {

    @Autowired
    BoardService boardService;

    @PostMapping("/remove")
    public String remove(Integer bno, Integer page, Integer pageSize, Model m, HttpSession session, RedirectAttributes rattr) {
        String writer = (String) session.getAttribute("id");
        try {

            m.addAttribute("page",page);
            m.addAttribute("pageSize",pageSize);
            int rowCnt = boardService.remove(bno, writer); // writer은 어디에서 가져오는지? 세션에서

            if(rowCnt != 1)
                throw new Exception("board remove error");
            rattr.addFlashAttribute("msg", "del_ok");  // rattr.addFlashAttribute 사용시,
                                                                    // error, ok가 한번만 나오게된다.(1회성) 세션을 이용함

        } catch (Exception e) {
            e.printStackTrace();
            rattr.addAttribute("msg", "del_error");

        }
        return "redirect:/board/list";
    }


    @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) {
            e.printStackTrace();
        }
        return "board";
    }


    @GetMapping("/list")
    public String list(Integer page, Integer pageSize, Model m, HttpServletRequest request) {
        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"; // 로그인을 한 상태이면, 게시판 화면으로 이동
    }

    private boolean loginCheck(HttpServletRequest request) {
        // 1. 세션을 얻어서
        HttpSession session = request.getSession();
        // 2. 세션에 id가 있는지 확인, 있으면 true를 반환
        return session.getAttribute("id")!=null;
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<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-1.11.3.js"></script>
</head>
<body>
<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 () {
    $('#listBtn').on("click", function () {
      location.href="<c:url value='/board/list'/>?page=${page}&pageSize=${pageSize}"; //브라우저창 주소줄에 입력하는것과 같기에 Get
    });
    $('#removeBtn').on("click", function () {  // 삭제는 Post로 처리해야되기 때문에 get하던방식과 다름
      if (!confirm("정말 삭제하시겠습니까?")) return;
      let form = $('#form');
      form.attr("action", "<c:url value='/board/remove'/>?page=${page}&pageSize=${pageSize}");
      form.attr("method", "post");
      form.submit();
    });


  });

</script>


</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>fastcampus</title>
  <link rel="stylesheet" href="<c:url value='/css/menu.css'/>">
</head>
<body>
<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 = "${msg}"
  if(msg=="del_ok") alert("성공적으로 삭제되었습니다.")
  if(msg=="del_error") alert("삭제에 실패하였습니다.")
</script>


<div style="text-align:center">
  <h1>This is BOARD</h1>
  <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=${page}&pageSize=${pageSize}'/>"> ${boardDto.title}</a></td>
        <td>${boardDto.writer}</td>
        <td>${boardDto.reg_date}</td>
        <td>${boardDto.view_cnt}</td>
      </tr>
    </c:forEach>
  </table>
<br>
    <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>
</body>
</html>

 



4. 게시물 쓰기 기능의 구현


5. 게시물 수정 기능의 구현

 

package com.fastcampus.ch4.controller;

import com.fastcampus.ch4.domain.BoardDto;
import com.fastcampus.ch4.domain.PageHandler;
import com.fastcampus.ch4.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/board")
public class BoardController {

    @Autowired
    BoardService boardService;

    @PostMapping("/modify")
    public String modify(BoardDto boardDto, HttpSession session, Model m, RedirectAttributes rattr, Integer page, Integer pageSize){
        String writer = (String) session.getAttribute("id");
        boardDto.setWriter(writer);

        try {
            int rowCnt = boardService.modify(boardDto); // 등록실패시 0
            m.addAttribute("page", page);
            m.addAttribute("pageSize", pageSize);

            if (rowCnt != 1) {
                throw new Exception("modify failed");
            }
//            m.addAttribute("msg", "Write_OK"); // 이렇게 작성시 계속 주소창에 남음  ↓ 이렇게 작성 추천
            rattr.addFlashAttribute("msg", "modify_ok"); // 세션을 이용한 1회성 저장
            return "redirect:/board/list";

        } catch (Exception e) {
            e.printStackTrace();
            m.addAttribute(boardDto);
            m.addAttribute("msg", "modify_error"); // 이렇게 작성시 계속 주소창에 남음 ↓ 이렇게 작성 추천
//            rattr.addFlashAttribute("msg", "write_error"); // 세션을 이용한 1회성 저장
            return "board";  // 등록 실패시, 입력했던 내용 다시 보여줄수 있도록
        }
    }

    @PostMapping("/write")
    public String write(BoardDto boardDto, HttpSession session, Model m, RedirectAttributes rattr){
        String writer = (String) session.getAttribute("id");
        boardDto.setWriter(writer);

        try {
            int rowCnt = boardService.write(boardDto); // 등록실패시 0

            if (rowCnt != 1) {
                throw new Exception("Write failed");
            }
//            m.addAttribute("msg", "Write_OK"); // 이렇게 작성시 계속 주소창에 남음  ↓ 이렇게 작성 추천
            rattr.addFlashAttribute("msg", "write_ok"); // 세션을 이용한 1회성 저장
            return "redirect:/board/list";

        } catch (Exception e) {
            e.printStackTrace();
            m.addAttribute(boardDto);
            m.addAttribute("msg", "write_error"); // 이렇게 작성시 계속 주소창에 남음 ↓ 이렇게 작성 추천
//            rattr.addFlashAttribute("msg", "write_error"); // 세션을 이용한 1회성 저장
            return "board";  // 등록 실패시, 입력했던 내용 다시 보여줄수 있도록
        }

    }

    @GetMapping("/write")
    public String write(Model m) {
        m.addAttribute("mode", "new");
        return "board"; // board.jsp 를 읽기와 쓰기에 사용 ( 쓰기 사용시 mode=new ,   mode가 new가 아니라면 읽기)
    }

    @PostMapping("/remove")
    public String remove(Integer bno, Integer page, Integer pageSize, Model m, HttpSession session, RedirectAttributes rattr) {
        String writer = (String) session.getAttribute("id");
        try {

            m.addAttribute("page",page);
            m.addAttribute("pageSize",pageSize);
            int rowCnt = boardService.remove(bno, writer); // writer은 어디에서 가져오는지? 세션에서

            if(rowCnt != 1)
                throw new Exception("board remove error");
            rattr.addFlashAttribute("msg", "del_ok");  // rattr.addFlashAttribute 사용시,
                                                                    // error, ok가 한번만 나오게된다.(1회성) 세션을 이용함

        } catch (Exception e) {
            e.printStackTrace();
            rattr.addAttribute("msg", "del_error");

        }
        return "redirect:/board/list";
    }

    @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) {
            e.printStackTrace();

        }
        return "board";
    }

    @GetMapping("/list")
    public String list(Integer page, Integer pageSize, Model m, HttpServletRequest request) {
        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"; // 로그인을 한 상태이면, 게시판 화면으로 이동
    }

    private boolean loginCheck(HttpServletRequest request) {
        // 1. 세션을 얻어서
        HttpSession session = request.getSession();
        // 2. 세션에 id가 있는지 확인, 있으면 true를 반환
        return session.getAttribute("id")!=null;
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<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-1.11.3.js"></script>
</head>
<body>
<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 = "${msg}"
  if(msg=="write_error") alert("게시물 등록에 실패하였습니다. 다시 시도 해주세요");

</script>


<div style="text-align:center">

  <h2>게시물 ${mode=="new" ?  "글쓰기" : "읽기"}</h2>
  <form action="" id="form">
    <input type="hidden" name="bno" value="${boardDto.bno}" >
    <input type="text" name="title" value="${boardDto.title}" ${mode=="new" ? '':'readonly="readonly"'}>
    <textarea name="content" id="" cols="30" rows="10" ${mode=="new" ? '':'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 () {
    $('#listBtn').on("click", function () {
      location.href="<c:url value='/board/list'/>?page=${page}&pageSize=${pageSize}"; //브라우저창 주소줄에 입력하는것과 같기에 Get
    });

    $('#modifyBtn').on("click", function () {  // 글등록 Post로 처리해야되기 때문에 get하던방식과 다름
      // 1. 읽기상태이면 수정상태로변경
      let form = $('#form');
      let isReadOnly = $("input[name=title]").attr('readonly');

      if(isReadOnly=='readonly'){
        $("input[name=title]").attr('readonly', false);
        $("textarea").attr('readonly', false);
        $("#modifyBtn").html("등록");
        $("h2").html("게시물 수정");
        return ;
      }
      // 2. 수정상태이면, 수정된 내용을 서버로 전송
      form.attr("action", "<c:url value='/board/modify'/>");
      form.attr("method", "post");
      form.submit();
      location.href="<c:url value='/board/list'/>?page=${page}&pageSize=${pageSize}";
    });

    $('#writeBtn').on("click", function () {  // 글등록 Post로 처리해야되기 때문에 get하던방식과 다름
      let form = $('#form');
      form.attr("action", "<c:url value='/board/write'/>");
      form.attr("method", "post");
      form.submit();
    });

    $('#removeBtn').on("click", function () {  // 삭제는 Post로 처리해야되기 때문에 get하던방식과 다름
      if (!confirm("정말 삭제하시겠습니까?")) return;
      let form = $('#form');
      form.attr("action", "<c:url value='/board/remove'/>?page=${page}&pageSize=${pageSize}");
      form.attr("method", "post");
      form.submit();
    });
  });

</script>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>fastcampus</title>
  <link rel="stylesheet" href="<c:url value='/css/menu.css'/>">
</head>
<body>
<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 = "${msg}"
  if(msg=="del_ok") alert("성공적으로 삭제되었습니다.")
  if(msg=="del_error") alert("삭제에 실패하였습니다.")
  if(msg=="write_ok") alert("성공적으로 등록되었습니다..")
  if(msg=="write_error") alert("등록이 실패하였습니다.")
</script>
<div style="text-align:center">
  <button type="button" id="writeBtn" onclick="location.href='<c:url value="/board/write"/>'">글쓰기</button>


  <h1>This is BOARD</h1>
  <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=${page}&pageSize=${pageSize}'/>"> ${boardDto.title}</a></td>
        <td>${boardDto.writer}</td>
        <td>${boardDto.reg_date}</td>
        <td>${boardDto.view_cnt}</td>
      </tr>
    </c:forEach>
  </table>
<br>
    <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>
</body>
</html>

 


참고 :

남궁성, 스프링의 정석

+ Recent posts