1. 기능별 URI 정의
읽기 : GET, 지정된 번호의 게시물을 보여준다.
/board/read?bno=번호
삭제 : POST, 게시물을 삭제한다.
/board/remove
쓰기1 : GET, 게시물을 작성하기 위한 화면을 보여준다.
/board/write
쓰기2 : POST, 작성한 게시물을 저장한다.
/board/write
수정1 : GET, 게시물을 수정하기 위해 읽어온다.
/board/modify?bno=번호
수정2 : POST, 수정된 게시물을 저장한다.
/board/modify
boardList.jsp에서 리스트의 제목을 누르면
GET으로 URI(/board/read?bno=533)를
BoardController의 read(Integer bno)가 bno를 받아서,
boardService.read(bno)를 호출하면 DB에서 게시글 하나를 읽어오고,
DB에서 boardDto에 게시글 정보를 담아서 Controller로 주면,
Controller에서 board.jsp로 ${boardDto.title}, ${boardDto.content}를 전달.
$("input[name=title]", "#form").attr('readonly', false);
$("textarea", "#form").attr('readonly', false);
<input name="title" type="text" value="no title220" placeholer=" 제목을 입력해 주세요." readonly='readonly'>
<textarea name="content" rows="20" placeholer=" 내용을 입력해 주세요." readonly='readonly'>no content220</textarea>
BoardController
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, Integer page, Integer pageSize, Model m, HttpSession session, RedirectAttributes rattr){
String writer = (String)session.getAttribute("id");
boardDto.setWriter(writer);
try {
m.addAttribute("page", page);
m.addAttribute("pageSize", pageSize);
int rowCnt = boardService.modify(boardDto);
if(rowCnt!=1)
throw new Exception("Modify failed");
rattr.addFlashAttribute("msg", "MOD_OK");
return "redirect:/board/list";
} catch (Exception e) {
e.printStackTrace();
m.addAttribute(boardDto);
m.addAttribute("msg", "MOD_ERR");
return "board";
}
}
@PostMapping("/write")
public String write(BoardDto boardDto, Model m, HttpSession session, RedirectAttributes rattr){
String writer = (String)session.getAttribute("id");
boardDto.setWriter(writer);
try {
int rowCnt = boardService.write(boardDto);
if(rowCnt!=1)
throw new Exception("Write failed");
rattr.addFlashAttribute("msg", "WRT_OK");
return "redirect:/board/list";
} catch (Exception e) {
e.printStackTrace();
m.addAttribute(boardDto);
m.addAttribute("msg", "WRT_ERR");
return "board";
}
}
@GetMapping("/write")
public String write(Model m) {
m.addAttribute("mode", "new");
return "board"; //읽기와 쓰기에 사용. 쓰기에 사용할 때는 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);
if(rowCnt!=1)
throw new Exception("board remove error");
rattr.addFlashAttribute("msg", "DEL_OK");
return "redirect:/board/list";
} catch (Exception e) {
e.printStackTrace();
rattr.addFlashAttribute("msg", "DEL_ERR");
}
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;
}
}
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>
<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=="WRT_ERR") alert("게시물 등록에 실패했습니다. 다시 시도해 주세요.");
</script>
<div style="text-align:center">
<h2>게시물 ${mode=="new" ? "글쓰기" : "읽기"}</h2>
<form action="" id="form">
<input type="hidden" name="bno" value="${boardDto.bno}" readonly="readonly">
<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(){
alert("listBtn clicked")
location.href = "<c:url value='/board/list'/>?page=${page}&pageSize=${pageSize}";
});
$('#modifyBtn').on("click", function(){
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;
}
form.attr("action", "<c:url value='/board/modify'/>?page=${page}&pageSize=${pageSize}");
form.attr("method", "post");
form.submit();
});
$('#writeBtn').on("click", function(){
let form = $('#form');
form.attr("action", "<c:url value='/board/write'/>");
form.attr("method", "post");
form.submit();
});
$('#removeBtn').on("click", function(){
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>
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>
<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=="WRT_OK") alert("성공적으로 등록되었습니다.");
if(msg=="DEL_OK") alert("성공적으로 삭제되었습니다.");
if(msg=="DEL_ERR") alert("삭제에 실패했습니다.");
</script>
<div style="text-align:center">
<button type="button" id="writeBtn"token tag"><c:url value="/board/write"/>'">글쓰기</button>
<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>
<div>
<c:if test="${ph.showPrev}">
<a href="<c:url value='/board/list?page=${ph.beginPage-1}&pageSize=${ph.pageSize}'/>"><</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}'/>">></a>
</c:if>
</div>
</div>
</body>
</html>