게시판 만들기/JSP ➜ Spring

[Spring]1. 게시판 구현 CRUD - 글쓰기

code-mo 2023. 2. 9. 07:30
728x90

1. 게시판 테이블

글순번을 기본키를 사용해서 게시글을 식별한다.

 

2. JSP 글 작성 페이지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<form method="post" action="writeAct">
    <table class="table table-striped"
        style="text-align: center; border: 1px solid #dddddd">
        <thead>
            <tr>
                <th colspan="2"
                    style="background-color: #eeeeee; text-align: center;">게시판
                    글쓰기 양식</th>
        </thead>
        <tbody>
            <tr>
                <td><input type="text" class="form-control"
                    placeholder="글 제목" name="bbsTitle" maxlength="50"></td>
            </tr>
            <tr>
                <td><textarea class="form-control" placeholder="글 내용"
                        name="bbsContent" maxlength="2048" style="height: 350px;"></textarea></td>
            </tr>
        </tbody>
    </table>
    <input type="submit" class="btn btn-primary pull-right" value="글쓰기">
</form>
cs

 

2. 글 작성 Controller

1. 글 작성 시 로그인한 사용자의 아이디를 세션에서 가져와서 작성자로 데이터를 넘겨준다. 
2.  게시판의 테이블레 기본키를  AUTO_INCREMENT를 이용하지 않았기 때문에 작성된 게시글의
     마지막 순번을 조회하여 직접 게시글 순번을 넣어준다.
1
2
3
4
5
6
7
8
9
10
11
12
//게시글 작성
@RequestMapping(value = "/writeAct", method = RequestMethod.POST)
public String joinAct(HttpServletRequest request, HttpServletResponse response,
        BoardDTO boardDTO) {
    
    String userID = (String)request.getSession().getAttribute("userID");
    int bbsMaxNum = boardSvc.selectBoardMaxNum();
    boardDTO.setBbsID(bbsMaxNum);
    boardDTO.setUserID(userID);
    boardSvc.insertBoard(boardDTO);
    return "redirect:/board";
}
cs

 

3. 글 작성 Service

1
2
3
4
5
6
7
8
9
//게시글 순번 마지막 번호 조회
public int selectBoardMaxNum() {
    return session.selectOne("selectBoardMaxNum");
}
 
//게시글 작성
public void insertBoard(BoardDTO boardDTO) {
    session.insert("insertBoard", boardDTO);
}
cs

 

4. 글 작성 Insert 쿼리

1
2
3
4
5
6
7
8
9
10
11
<!-- 게시글 순번 마지막 번호 조회 -->
<select id="selectBoardMaxNum" resultType="java.lang.Integer">
    SELECT IFNULL(MAX(bbsID),0)+1 FROM bbs.bbs
    WHERE bbsAvailable = 1
</select>
 
<!-- 게시글 작성 -->
<insert id="insertBoard" parameterType="com.member.MemberDTO">
    INSERT INTO bbs.bbs (bbsID, bbsTitle, userID, bbsDate, bbsContent)
    VALUES (#{bbsID}, #{bbsTitle}, #{userID}, NOW(), #{bbsContent})
</insert>
cs