Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
Tags
- Algorithm
- Serialization
- Stack
- stream
- list 컬렉션
- buffer
- 혼자 공부하는 C언어
- s
- C 언어 코딩 도장
- Selection Sorting
- datastructure
- coding test
- Graph
- JSON
- 윤성우의 열혈 자료구조
- R
- 윤성우 열혈자료구조
- 메모리구조
- C programming
- insertion sort
- 이스케이프 문자
- 알기쉬운 알고리즘
- 이것이 자바다
Archives
- Today
- Total
Engineering Note
[스프링 부트 입문] 15 데이터 수정하기 본문
본 내용은 홍팍 스프링부트 강좌를 참고하였습니다.
Mission
- 수정페이지에서 수정된 데이터를 DB에도 반영하기!
[스프링 부트 입문] 14 수정 폼 만들기에서는 Edit 버튼 누르면 DB에서 기존에 데이터를 불러와서 수정 페이지에서 확인 가능하도록 하는 작업까지 완료했다.
이제 이렇게 불러와진 수정 페이지에서 데이터를 수정하고 다시 저장했을 때 DB에 데이터가 업데이트 되고 다시 바뀐 바뀐 글을 보는 페이지로 리다이렉트 하도록하는 컨트롤러를 개발해야한다.
{{>layouts/header}}
{{#article}}
<form class = "container" action="/articles/update" method="post">
<input name="id" type="hidden" value="{{id}}">
<div clss = "mb-3">
<label class="form-label">제목</label>
<input type="text" class="form-control" name="title" value="{{title}}">
</div>
<div class = "mb-3">
<label class="form-label">내용</label>
<textarea class="form-control" rows="3" name="content" >{{content}}</textarea>
</div>
<button type="submit" class="btn btn-primary">제출</button>
<a href="/articles/{{id}}">Back</a>
</form>
{{/article}}
{{>layouts/footer}}form 태그의 전송시 실행할 url action과 http method를 지정해준다. 데이터를 수정할 http method는 patch 이지만 form태가 post만을 지원하기 때문에 이곳에서는 post를 사용했다.
그리고 controller에서 글의 id값으로 데이터를 업데이트 할 것이기 때문에 input value에 id를 넣어주어 서버에 DTO에서 데이터를 받을 수 있게 했다. (html내에 input 의 type은 hidden으로 안보이게 해주었다.)

package com.example.boardproject.dto;
import com.example.boardproject.entity.Article;
import lombok.AllArgsConstructor;
import lombok.ToString;
@AllArgsConstructor
@ToString
public class ArticleForm {
private Long id;// id 필드 추가!!
private String title;
private String content;
public Article toEntity() {
return new Article(id,title,content);
}
}Controller 코드
클라이언트 from 태그에서 보낸 데이터는 DTO로 받아오고 받은 DTO를 Entity로 변환한다.
변환한 Entity를 Repository JPA를 통해 DB 에 저장한다.
'Server > Spring' 카테고리의 다른 글
| Error parsing HTTP request header Note: further occurrences of HTTP request parsing errors will be logged at DEBUG level. (0) | 2022.08.05 |
|---|---|
| [Spring] Annotation 정리 (0) | 2022.08.05 |
| [스프링 부트 입문] 14 수정 폼 만들기 (0) | 2022.07.13 |
| [스프링 부트 입문] 12 데이터 목록 보기 (0) | 2022.07.12 |
| [스프링 부트 입문 11] 데이터 조회하기 (0) | 2022.07.10 |
Comments