1.View 확인하기
2. 익명 게시판이기에 save-form에 username 추가하기
{{> /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" enctype="application/x-www-form-urlencoded"> <div class="mb-3"><!--username 추가--> <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 type="submit" class="btn btn-primary form-control">글쓰기완료</button> </form> </div> </div> </div> {{> /layout/footer}}
3. BoardController에 save() 만들기
- 컨트롤러에 책임 확인하기
- PostMappingdmfh Post 요청하기
- 작성후 main 페이지로 이동하기
- DTO 없이 구현
매개변수에 바로 집어넣기
package shop.mtcoding.blog.board; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @Controller public class BoardController { @GetMapping( "/" ) public String index() { return "index"; } @PostMapping("/board/save") public String save(String username, String title, String content){ // DTO 없이 구현 // 꼭 출력해보기 System.out.println("username : " + username); System.out.println("username : " + title); System.out.println("username : " + content); return "redirect:/"; } @GetMapping("/board/save-form") public String saveForm() { return "board/save-form"; } @GetMapping("/board/{id}") public String detail(@PathVariable Integer id) { // Integer : 없으면 null, int : 0 return "board/detail"; } }
4. board_tb 만들기
- 생성자 : 최초의 값을 설정하는 것
- setter : 시간이 흐르면서 변경되는 것
ex) 게시글 수정시 제목과 내용만 바꿀 경우
package shop.mtcoding.blog.board; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.Getter; import java.sql.Timestamp; @Getter // 변경되는 데이터에만 setter가 필요함 @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; // 게시글 바꿀 때 뭘 수정할 것인가? // public void update() { // this.title = title; // this.content = content; } }
- 클래스명.class를 자동 파싱해 줄 때 어떤 생성자로 작동하나?
빈 생성자를 때려서 reflection으로 private 필드에 직접 접근하여 값을 설정할 수 있음
5. 데이터를 DB에 넣기
5-1. yml 설정하기
- H2 사용 가능
server: servlet: encoding: charset: utf-8 force: true # port: 8080 기본 셋팅이 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
5-2. BoardNativeRepository 만들기
- 나중에 안 쓰고 새로운 레파지토리를 쓸 예정임
package shop.mtcoding.blog.board; import jakarta.persistence.EntityManager; import jakarta.persistence.Query; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; // 나중에 안쓰고 새로운 레파지토리를 쓰고 이건 버릴거임 @RequiredArgsConstructor @Repository public class BoardNativeRepository { private final EntityManager em; @Transactional public void save(String title, String content, String username){ Query query = em.createNativeQuery("insert into board_tb (title, content, username, created_at) values (?,?,?,now())"); query.setParameter(1, title); query.setParameter(2, content); query.setParameter(3, username); query.executeUpdate(); } }
5-3. BoardController 설정하기
- Integer : 없으면 null
- int : 0
package shop.mtcoding.blog.board; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @RequiredArgsConstructor @Controller public class BoardController { private final BoardNativeRepository boardNativeRepository; @GetMapping("/") public String index() { return "index"; } @PostMapping("/board/save") public String save(String title, String content, String username) { // DTO 없이 구현 boardNativeRepository.save(title, content, username); return "redirect:/"; } @GetMapping("/board/save-form") public String saveForm() { return "board/save-form"; } @GetMapping("/board/{id}") public String detail(@PathVariable Integer id) { // Integer : 없으면 null, int : 0 return "board/detail"; } }
Share article