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

Spring) 게시판 쓰기를 만들어보자!

by 휴일이 2022. 11. 22.

 

이번엔 쓰기를 만들어보쟈 :)

 

1) 제목, 내용을 쓰고 등록

2) id는 로그인한, session에 등록된 id로 등록한다

3) 등록이 되면 등록 완료, 실패하면 등록 실패

 

 

 

일단

BoardController

@GetMapping("write")
public String write(Model m, HttpServletRequest request) {
    if(loginCheck(request)) {
        return "login";
    }
    // 쓰기 모드로 변경하기 위해
    m.addAttribute("mode", "new");
    return "board";
}

@PostMapping("/write")
public String write(BoardDto dto, HttpSession session, HttpServletRequest request, Model m, RedirectAttributes rattr) {
    if(loginCheck(request)) {
        return "login";
    }

    System.out.println("dto = " + dto);
    try {
        // DTO 널체크
        if(dto == null) {
            throw new Exception("dto is null");
        }
        // 세션에 있는 id (로그인 된 id) 가져오기
            String id = (String)session.getAttribute("id");
            dto.setId(id);

            int check = service.write(dto);
            // 수정이 안 되면 오류 발생
        if (check == 0) {
            throw new Exception("write failed");
        }
        // redirect 할 때 정보를 가져가는 것
        rattr.addFlashAttribute("msg","WRITE OK");

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("e = " + e);
        // 실패하면 alert 띄우기 위해
        m.addAttribute("msg","WRT_ERR");
        return "boardList";

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

 

RedirectAttributes

요놈은 Redirect가 될 때 세션에 살짝 값을 추가해주는 녀석이다(Redirect 이후에는 바로 소멸한다고 한다)

게시글 작성이 성공하면 "redirect:/board/list" 로 가게 되는데,

이 때 /board/list 에 정보를 가지고 가는 것이다

그래서 boardList.jsp에

 

<script>
    let msg = "${msg}";
    if(msg == "WRITE OK") alert("등록 완료");
</script>

 

요녀석을 살짜쿵 추가해주면

RedirectAttributes 가 boardList.jsp에 값을 가져가고

msg가 WRITE OK 라면 등록 완료 창을 띄워준다!

 

 

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' ? '쓰기' : '읽기'}</h2>
    <form id = "form" action="" method="POST">
        <table>
            <tr>
                <th>제목 <input type="text" id="title" name="title" value="${boardDto.title}" ${mode=="new" ? "" : "readonly='readonly'"}></th>
            </tr>
            <tr>
                <c:if test="${mode ne 'new'}">
                    <th><input type="text" id="id" name="id" value="${boardDto.id}" readonly></th>
                </c:if>
            </tr>
            <tr>
                <td><textarea name="content" id="content" rows="20" ${mode=="new" ? "" : "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> <br>
        <c:if test="${mode ne 'new'}">
            <button type="button" id = "writeNewBtn" onclick="location.href='/board/write'">글쓰기</button>
        </c:if>
        <c:if test="${mode eq 'new'}">
            <button type="button" id = "writeBtn">등록</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();
        })
    })
</script>
</body>
</html>

 

 

저번에 ajax로 정보를 보냈다면

이번엔 submit으로 정보를 보내보았다!

 

name 이 dto 변수명과 같다면

submit을 하면 name에 맞춰 컨트롤러에 dto로 받아올 수 있다!

 

 

읽기일 경우, 쓰기일 경우

보이는 버튼과 내용이 다르기 때문에

Model에 mode를 준 후

조건연산자(삼항ㅇ연산자?)를 사용해서

mode 값이 new 라면 쓰기에 알맞은 상태가 되도록 jsp를 수정해보았다!

 

 

 

 

결과는?

 

글쓰기창
요로케 써주고 등록을 누르면?

 

등록 완료!

 

 

무사히 글이 등록되었담

 

 

글 읽기!

 

 

 

 

내일은 삭제와 수정에 도전해보자!

728x90