1. Board 테이블 생성

Board

package shop.mtcoding.blog.board;

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

import java.sql.Timestamp;

@Data
@Table(name = "board_tb")
@Entity
public class Board {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String title;
    private String content;
    private String username;
    private Timestamp createdAt;
}

application-dev.yml

server:
  servlet:
    encoding:
      charset: utf-8
      force: true
  port: 8080

spring:
  mustache:
    servlet:
      expose-session-attributes: true
      expose-request-attributes: true
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:test;MODE=MySQL
    username: sa
    password:
  h2:
    console:
      enabled: true
  sql:
    init:
      data-locations:
        - classpath:db/data.sql
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true
    properties:
      hibernate:
        format_sql: true
    defer-datasource-initialization: true

2. 더미데이터 만들기

글 목록보기를 할 때 게시글이 없으면, 매번 글쓰기를 하고 글 목록보기를 테스트해야해서 귀찮다.

더미데이터를 만들어두자.

resources/db/data.sql

insert into board_tb(title, content, username, created_at) values('제목1','내용1','ssar',now());
insert into board_tb(title, content, username, created_at) values('제목2','내용2','ssar',now());
insert into board_tb(title, content, username, created_at) values('제목3','내용3','cos',now());
insert into board_tb(title, content, username, created_at) values('제목4','내용4','love',now());

Untitled

3. view 변경

<aside> 💡 익명 유저 input tag 만들기

</aside>

{{> /layout/header}}

<div class="container p-5">

    <!-- 요청을 하면 localhost:8080/board/save POST로 요청됨
    title=사용자입력값&content=사용자값 -->
    <div class="card">
        <div class="card-header"><b>글쓰기 화면입니다</b></div>
        <div class="card-body">
            <form action="/board/save" method="post">
                <div class="mb-3">
                    <input type="text" class="form-control" placeholder="Enter username" name="username">
                </div>
                <div class="mb-3">
                    <input type="text" class="form-control" placeholder="Enter title" name="title">
                </div>
                <div class="mb-3">
                    <textarea class="form-control" rows="5" name="content"></textarea>
                </div>
                <button class="btn btn-primary form-control">글쓰기완료</button>
            </form>
        </div>
    </div>
</div>

{{> /layout/footer}}

4. form 값 받기 잘되는지 확인

@PostMapping("/board/save")
public String save(String title, String content, String username){
    System.out.println("title : "+username);
    System.out.println("content : "+content);
    System.out.println("username : "+username);
    return "redirect:/";
}

Untitled

Untitled