글쓰기 기능 추가, boardList 에 글쓰기 버튼 추가 후 버튼 누르면 board/write로 이동

 

boardList.jsp

<button type="button" id="writeBtn" onclick="location.href='<c:url value="/board/write"/>'">글쓰기</button>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="loginOutLink" value="${sessionScope.id==null ? '/login/login' : '/login/logout'}"/>
<c:set var="loginOut" value="${sessionScope.id==null ? 'Login' : 'Logout'}"/>
    
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
    <title>중고헌터</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">중고헌터</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='${loginOutLink}'/>">${loginOut}</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">
<button type="button" id="writeBtn" onclick="location.href='<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}'/>">&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>
<script>
	let msg = "${msg}"
	if(msg=="DEL_OK") alert("성공적으로 삭제되었습니다.");
	if(msg=="DEL_ERROR") alert("삭제를 실패했습니다.");
</script>
</body>
</html>

 

 

board/write 에 빈 게시판 폼 나타내기

 

board.jsp

 

bno 는 hidden 타입으로

model 에 담긴 mode 가 new 이면 제목이 게시물 글쓰기로

title, content 가 readonly 가 아니게 하기

<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="btm">등록</button>
        <button type="button" id="modifyBtn" class="btm">수정</button>
        <button type="button" id="removeBtn" class="btm">삭제</button>
        <button type="button" id="listBtn" class="btm">목록</button>
    </form>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="loginOutLink" value="${sessionScope.id==null ? '/login/login' : '/login/logout'}"/>
<c:set var="loginOut" value="${sessionScope.id==null ? 'Login' : 'Logout'}"/>
    
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
    <title>중고헌터</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">중고헌터</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='${loginOutLink}'/>">${loginOut}</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>게시물 ${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="btm">등록</button>
        <button type="button" id="modifyBtn" class="btm">수정</button>
        <button type="button" id="removeBtn" class="btm">삭제</button>
        <button type="button" id="listBtn" class="btm">목록</button>
    </form>
</div>

<script>
	$(document).ready(function(){ // main
		$('#listBtn').on("click", function(){
			location.href = "<c:url value='/board/list'/>?page=${page}&pageSize=${pageSize}";
		});
		$('#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>

 

 

boardContoller.java

 

	@GetMapping("write")
	public String write(Model m) {
		m.addAttribute("mode", "new");
		return "board";
	}
package com.jcy.usedhunter.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

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 com.jcy.usedhunter.domain.BoardDto;
import com.jcy.usedhunter.domain.PageHandler;
import com.jcy.usedhunter.service.BoardService;

@Controller
@RequestMapping("/board")
public class BoardController {
	@Autowired
	BoardService boardService;
	
	@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 ph = 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", ph);
			m.addAttribute("page", page);
			m.addAttribute("pageSize", pageSize);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "boardList";  // 로그인을 했으면 게시판 화면으로 이동
	}
	
	@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";
	}
	
	@PostMapping("remove")
	public String remove(HttpSession session, Integer bno, Integer page, Integer pageSize, Model m, RedirectAttributes rttr) {
		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");
			rttr.addFlashAttribute("msg", "DEL_OK");
		} catch (Exception e) {
			e.printStackTrace();
			rttr.addFlashAttribute("msg", "DEL_ERROR");

		}
		return "redirect:/board/list"; // 모델에 담으면 "redirect:/board/list?page=&pageSize" 으로 자동으로 생성
	}
	
	@GetMapping("write")
	public String write(Model m) {
		m.addAttribute("mode", "new");
		return "board";
	}

	private boolean loginCheck(HttpServletRequest request) {
		// 1. 세션을 얻고
		HttpSession session = request.getSession();
		// 2. 세션에  id 가 있는 지 확인 있으면 true 를 반환
//		if(session.getAttribute("id")!=null) {
//			return true;
//		} else {
//			return false;
//		}
		return session.getAttribute("id")!=null;
	}
}

 

 

 

 

글쓰고 등록하기

 

board.jsp

등록 jQuery 추가

 

$('#writeBtn').on("click", function(){
			let form = $('#form');
			form.attr("action", "<c:url value='/board/write'/>");
			form.attr("method", "post");
			form.submit();
		});

 

게시물 등록 실패 시 알림 창 추가

<script>
	let msg = "${msg}"
    if(msg=="WRT_ERROR") alert("게시물 등록에 실패했습니다. 다시 시도해 주세요.");
</script>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="loginOutLink" value="${sessionScope.id==null ? '/login/login' : '/login/logout'}"/>
<c:set var="loginOut" value="${sessionScope.id==null ? 'Login' : 'Logout'}"/>
    
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
    <title>중고헌터</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">중고헌터</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='${loginOutLink}'/>">${loginOut}</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_ERROR") 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="btm">등록</button>
        <button type="button" id="modifyBtn" class="btm">수정</button>
        <button type="button" id="removeBtn" class="btm">삭제</button>
        <button type="button" id="listBtn" class="btm">목록</button>
    </form>
</div>

<script>
	$(document).ready(function(){ // main
		$('#listBtn').on("click", function(){
			location.href = "<c:url value='/board/list'/>?page=${page}&pageSize=${pageSize}";
		});
		$('#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.jap

 

성공 시 알림 창 추가

<script>
	let msg = "${msg}"
    if(msg=="WRT_OK") alert("성공적으로 등록되었습니다.");
	if(msg=="DEL_OK") alert("성공적으로 삭제되었습니다.");
	if(msg=="DEL_ERROR") alert("삭제를 실패했습니다.");
</script>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="loginOutLink" value="${sessionScope.id==null ? '/login/login' : '/login/logout'}"/>
<c:set var="loginOut" value="${sessionScope.id==null ? 'Login' : 'Logout'}"/>
    
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
    <title>중고헌터</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">중고헌터</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='${loginOutLink}'/>">${loginOut}</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">
<button type="button" id="writeBtn" onclick="location.href='<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}'/>">&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>
<script>
	let msg = "${msg}"
    if(msg=="WRT_OK") alert("성공적으로 등록되었습니다.");
	if(msg=="DEL_OK") alert("성공적으로 삭제되었습니다.");
	if(msg=="DEL_ERROR") alert("삭제를 실패했습니다.");
</script>
</body>
</html>

 

BoardController.java

 

@PostMapping write 메서드 추가

package com.jcy.usedhunter.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

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 com.jcy.usedhunter.domain.BoardDto;
import com.jcy.usedhunter.domain.PageHandler;
import com.jcy.usedhunter.service.BoardService;

@Controller
@RequestMapping("/board")
public class BoardController {
	@Autowired
	BoardService boardService;
	
	@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 ph = 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", ph);
			m.addAttribute("page", page);
			m.addAttribute("pageSize", pageSize);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "boardList";  // 로그인을 했으면 게시판 화면으로 이동
	}
	
	@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";
	}
	
	@PostMapping("remove")
	public String remove(HttpSession session, Integer bno, Integer page, Integer pageSize, Model m, RedirectAttributes rttr) {
		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");
			rttr.addFlashAttribute("msg", "DEL_OK");
		} catch (Exception e) {
			e.printStackTrace();
			rttr.addFlashAttribute("msg", "DEL_ERROR");

		}
		return "redirect:/board/list"; // 모델에 담으면 "redirect:/board/list?page=&pageSize" 으로 자동으로 생성
	}
	
	@GetMapping("write")
	public String write(Model m) {
		m.addAttribute("mode", "new");
		return "board";
	}
	
	@PostMapping("write")
	public String write(BoardDto boardDto, Model m, HttpSession session, RedirectAttributes rttr) {
		String writer = (String)session.getAttribute("id");
		boardDto.setWriter(writer);
		
		try {
			int rowCnt = boardService.write(boardDto);
			
			if(rowCnt!=1) {
				throw new Exception("Write failed");
			}
			rttr.addFlashAttribute("msg", "WRT_OK");
			return "redirect:/board/list";
		} catch (Exception e) {
			e.printStackTrace();
			m.addAttribute(boardDto);
			m.addAttribute("msg", "WRT_ERROR");
			return "board";
		}
	}

	private boolean loginCheck(HttpServletRequest request) {
		// 1. 세션을 얻고
		HttpSession session = request.getSession();
		// 2. 세션에  id 가 있는 지 확인 있으면 true 를 반환
//		if(session.getAttribute("id")!=null) {
//			return true;
//		} else {
//			return false;
//		}
		return session.getAttribute("id")!=null;
	}
}

 

 

게시물 등록 실패 시 테스트

 

BoardServiceImpl.java

 

write 메서드 예외 발생

작성 하던 내용 남기기

	    @Override
	    public int write(BoardDto boardDto) throws Exception {
	    	throw new Exception("test");
//	        return boardDao.insert(boardDto);
	    }

게시물 수정 기능 만들기

 

boardMapper.xml

 

update 명령 where절에 writer 추가

	<update id="update" parameterType="BoardDto">
		UPDATE board
		SET title = #{title}
		, content = #{content}
		, up_date = now()
		WHERE bno = #{bno} and writer = #{writer}
	</update>

 

board.jsp

 

수정 jQuery 추가

$('#modifyBtn').on("click", function(){
			// 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();
		});
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="loginOutLink" value="${sessionScope.id==null ? '/login/login' : '/login/logout'}"/>
<c:set var="loginOut" value="${sessionScope.id==null ? 'Login' : 'Logout'}"/>
    
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
    <title>중고헌터</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">중고헌터</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='${loginOutLink}'/>">${loginOut}</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_ERROR") 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="btm">글쓰기</button>
        <button type="button" id="modifyBtn" class="btm">수정</button>
        <button type="button" id="removeBtn" class="btm">삭제</button>
        <button type="button" id="listBtn" class="btm">목록</button>
    </form>
</div>

<script>
	$(document).ready(function(){ // main
		$('#listBtn').on("click", function(){
			location.href = "<c:url value='/board/list'/>?page=${page}&pageSize=${pageSize}";
		});
		$('#writeBtn').on("click", function(){
			let form = $('#form');
			form.attr("action", "<c:url value='/board/write'/>");
			form.attr("method", "post");
			form.submit();
		});
		$('#modifyBtn').on("click", function(){
			// 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();
		});
		$('#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>

 

BoardController.java

 

@PostMapping modify 추가

@PostMapping("modify")
	public String modify(BoardDto boardDto, Model m, HttpSession session, RedirectAttributes rttr) {
		String writer = (String)session.getAttribute("id");
		boardDto.setWriter(writer);
		
		try {
			int rowCnt = boardService.modify(boardDto);
			
			if(rowCnt!=1) {
				throw new Exception("Modify failed");
			}
			rttr.addFlashAttribute("msg", "MOD_OK");
			return "redirect:/board/list";
		} catch (Exception e) {
			e.printStackTrace();
			m.addAttribute(boardDto);
			m.addAttribute("msg", "MOD_ERROR");
			return "board";
		}
	}
package com.jcy.usedhunter.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

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 com.jcy.usedhunter.domain.BoardDto;
import com.jcy.usedhunter.domain.PageHandler;
import com.jcy.usedhunter.service.BoardService;

@Controller
@RequestMapping("/board")
public class BoardController {
	@Autowired
	BoardService boardService;
	
	@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 ph = 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", ph);
			m.addAttribute("page", page);
			m.addAttribute("pageSize", pageSize);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "boardList";  // 로그인을 했으면 게시판 화면으로 이동
	}
	
	@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";
	}
	
	@PostMapping("remove")
	public String remove(HttpSession session, Integer bno, Integer page, Integer pageSize, Model m, RedirectAttributes rttr) {
		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");
			rttr.addFlashAttribute("msg", "DEL_OK");
		} catch (Exception e) {
			e.printStackTrace();
			rttr.addFlashAttribute("msg", "DEL_ERROR");

		}
		return "redirect:/board/list"; // 모델에 담으면 "redirect:/board/list?page=&pageSize" 으로 자동으로 생성
	}
	
	@GetMapping("write")
	public String write(Model m) {
		m.addAttribute("mode", "new");
		return "board";
	}
	
	@PostMapping("write")
	public String write(BoardDto boardDto, Model m, HttpSession session, RedirectAttributes rttr) {
		String writer = (String)session.getAttribute("id");
		boardDto.setWriter(writer);
		
		try {
			int rowCnt = boardService.write(boardDto);
			
			if(rowCnt!=1) {
				throw new Exception("Write failed");
			}
			rttr.addFlashAttribute("msg", "WRT_OK");
			return "redirect:/board/list";
		} catch (Exception e) {
			e.printStackTrace();
			m.addAttribute(boardDto);
			m.addAttribute("msg", "WRT_ERROR");
			return "board";
		}
	}
	
	@PostMapping("modify")
	public String modify(BoardDto boardDto, Model m, HttpSession session, RedirectAttributes rttr) {
		String writer = (String)session.getAttribute("id");
		boardDto.setWriter(writer);
		
		try {
			int rowCnt = boardService.modify(boardDto);
			
			if(rowCnt!=1) {
				throw new Exception("Modify failed");
			}
			rttr.addFlashAttribute("msg", "MOD_OK");
			return "redirect:/board/list";
		} catch (Exception e) {
			e.printStackTrace();
			m.addAttribute(boardDto);
			m.addAttribute("msg", "MOD_ERROR");
			return "board";
		}
	}

	private boolean loginCheck(HttpServletRequest request) {
		// 1. 세션을 얻고
		HttpSession session = request.getSession();
		// 2. 세션에  id 가 있는 지 확인 있으면 true 를 반환
//		if(session.getAttribute("id")!=null) {
//			return true;
//		} else {
//			return false;
//		}
		return session.getAttribute("id")!=null;
	}
}

 

 

수정 테스트

 

제목이 게시물 수정으로 바뀌고

수정 버튼이 등록으로 바뀌며 title, content 의 'readonly' 가 사라졌다.

 

test 를 test2로 수정 후 등록

 

복사했습니다!