SpringBoot

[2] IntelliJ 스프링부트 게시판_게시글 작성

https.. 2024. 2. 12. 23:04

https://youtu.be/VAYJ8iDHpJg?feature=shared


게시판 주요 기능
1. 글쓰기(/board/save)
2. 글목록 (/board/)
3. 글조회 (/board/{id})
4. 글수정 (/board/update/{id})
5. 글삭제 (/board/delete/{id})
6. 페이징처리 (/board/paging)
7. 파일(이미지) 첨부하기
 

01


test.board에 Controller 패키지를 생성하고 HomeController Java Class를 생성한다.

package test.board.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {
    @GetMapping("/")
    public String index() {
        return "index";
    }
}

resources>templates에 index.html을 생성한다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <button onclick="saveReq()">글작성</button>
    <a href="/board/save">글작성(링크)</a>
</body>
<script>
    const saveReq = () => {
        location.href = "/board/save";
    }
</script>
</html>

BoardController을 생성, 글쓰기를 처리하는 save 기능을 구현한다.

package test.board.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/board")
public class BoardController {
    @GetMapping("/save")
    public String saveForm() {
        return "save";
    }
}

save.html을 생성, Shift + F10으로 실행시킨다.

이렇게 글작성 페이지가 나오면 성공!
 
 
 

02

 
save.html에 아래의 코드를 작성한다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>save</title>
</head>
<body>
<form action="/board/save" method="post" enctype="multipart/form-data">
    writer: <input type="text" name="boardWriter"> <br>
    pass: <input type="text" name="boardPass"> <br>
    title: <input type="text" name="boardTitle"> <br>
    contents: <textarea name="boardContents" cols="30" rows="10"></textarea> <br>
    <input type="submit" value="글작성">
</form>
</body>
</html>

작성 후 실행시키기

 
BoardController에 save 기능 추가한다.

    @GetMapping("/save")
    public String save() {
        return null;
    }

 
test.board에 DTO 패키지를 생성, BoardDTO 클래스를 만든다.

package test.board.DTO;

import lombok.*;
import java.time.LocalDateTime;

@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BoardDTO {
    private Long id;
    private String boardWriter;
    private String boardPass;
    private String boardTitle;
    private String boardContents;
    private int boardHits;
    private LocalDateTime boardCreatedTime;
    private LocalDateTime boardUpdatedTime;
}

 
BoardController을 수정

@PostMapping("/save")
    public String save(@ModelAttribute BoardDTO boardDTO) throws IOException {
        System.out.println("boardDTO = " + boardDTO);
        boardService.save(boardDTO);
        return null;

 
test.board에 Entity, Repository, Service 패키지를 생성한다..
Entity에 작성

package test.board.Entity;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter
@Setter
@Table(name = "board_table")
public class BoardEntity {
    @Id // pk 컬럼 지정. 필수
    @GeneratedValue(strategy = GenerationType.IDENTITY) // auto_increment
    private Long id;

    @Column(length = 20, nullable = false) // 크기 20, not null
    private String boardWriter;

    @Column // 크기 255, null 가능
    private String boardPass;

    @Column
    private String boardTitle;

    @Column(length = 500)
    private String boardContents;

    @Column
    private int boardHits;
}

 
BaseEntity생성

package test.board.Entity;

import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import lombok.Getter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Getter
public class BaseEntity {
    @CreationTimestamp
    @Column(updatable = false)
    private LocalDateTime createdTime;

    @UpdateTimestamp
    @Column(insertable = false)
    private LocalDateTime updatedTime;
}

 
BoardEntity를 수정

public class BoardEntity extends BaseEntity {

 
BoardService 생성

package test.board.Service;

import org.springframework.stereotype.Service;

@Service
public class BoardService {
}

 
BoardRepository 생성

package test.board.Repository;

import org.springframework.data.jpa.repository.JpaRepository;
import test.board.Entity.BoardEntity;

public interface BoardRepository extends JpaRepository<BoardEntity, Long> {
}

 
BoardController의
boardService.save(boardDTO);의 save메서드를 생성한다.

BoardService

package test.board.Controller;

import lombok.RequiredArgsConstructor;
import org.antlr.v4.runtime.misc.LogManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import test.board.DTO.BoardDTO;
import test.board.Service.BoardService;

import java.io.IOException;

@Controller
@RequiredArgsConstructor
@RequestMapping("/board")
public class BoardController {
    private final BoardService boardService;

    @GetMapping("/save")
    public String saveForm() {
        return "save";
    }

    @PostMapping("/save")
    public String save(@ModelAttribute BoardDTO boardDTO) throws IOException {
        System.out.println("boardDTO = " + boardDTO);
        boardService.save(boardDTO);
        return "index";
    }
}

 
BoardEntity에 추가

public static BoardEntity toSaveEntity(BoardDTO boardDTO) {
    BoardEntity boardEntity = new BoardEntity();
    boardEntity.setBoardWriter(boardDTO.getBoardWriter());
    boardEntity.setBoardPass(boardDTO.getBoardPass());
    boardEntity.setBoardTitle(boardDTO.getBoardTitle());
    boardEntity.setBoardContents(boardDTO.getBoardContents());
    boardEntity.setBoardHits(0);
    return boardEntity;
}

 
BoardService 추가, save() 부분도 save(boardEntity)로 수정

BoardEntity boardEntity = BoardEntity.toSaveEntity(boardDTO);
boardRepository.save(boardEntity);

 
BoardController의 null부분을 index로 수정한다.

@PostMapping("/save")
public String save(@ModelAttribute BoardDTO boardDTO) throws IOException {
    System.out.println("boardDTO = " + boardDTO);
    boardService.save(boardDTO);
    return "index";
}

 
application.yml의 create로 실행시킨 후, 데이터베이스가 실행할 때마다 생성되지 않고 계속 반영되게 하려면 update로 수정해줘야 한다.

글작성 화면에서 내용이 입력되면 성공!
 
 

터미널에 작성한 내용이 입력된 것을 볼 수 있다.