날아라김지원
article thumbnail

- Update : 수정폼 만들기

아래와 같이 게시판의 글을 수정하고 싶다.

먼저 글 상세페이지로 들어가고

글의 상세페지로 들어가 Edit을 누르면 수정으로 들어가게 되는데 그러려면 상세 페이지를 담당하는

 

show.mustache파일을 수정해야 한다. 테이블밑에 Edit을 추가해주고 아이디를 파라메터로 같이 전송해주는 링크를

 

만들어준다.

show.mustache

{{>layouts/header}}

<table class="table">
    <thead>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">title</th>
        <th scope="col">content</th>

    </tr>
    </thead>
    <tbody>
    {{#article}}
<!--    이 간격안에서 article모델 가져올 수 있다.-->
    <tr>

        <td>{{id}}</td>
        <td>{{title}}</td>
        <td>{{content}}</td>
    </tr>
    {{/article}}
    </tbody>
</table>
<a href="/articles/{{article.id}}/edit" class="btn btn-primary">Edit</a>
<!--POST, GET ,UPDATE, DELETE 가 원래 있지만 여기선 GET, a태그 링크를 사용해서 요청해보자-->
<a href="/articles/{{article.id}}/delete" class="btn btn-danger">Delete</a>
<a href="/articles">Go To Article List</a>
{{>layouts/footer}}

그리고 컨트롤러에 edit와 update를 아래와 같이 만들어준다.

 

그리고 위그림같이 기존의 데이터를 가져올 필요도 있기 떄문에 edit.mustache도 만들어준다.

ArticleController.java

    @GetMapping("/articles/{id}/edit")
    ///articles/{article.id}/edit 이건 오류!
    public String edit(@PathVariable Long id,Model model){
//        수정할 데이터를 가져오기!
         Article articleEntity = articleRepository.findById(id).orElse(null);
         // id는 url파라미터로 가져오고싶다. 패쓰 배리어블

        //모델에 데이터 등록
        model.addAttribute("article",articleEntity);

        //  뷰 페이지 설정!
        return "articles/edit";
    }

	@PostMapping("articles/update")
    public String update(ArticleForm form){
        log.info(form.toString());

        // 1: DTO를 엔티티로 변환한다!
         Article articleEntity = form.toEntity();
        log.info(articleEntity.toString());
        // 2: 엔티티를 DB로 저장한다!
        // 2-1 : DB에서 기존 데이터를 가져온다!
        Article target = articleRepository.findById(articleEntity.getId()).orElse(null);
        // 2-2 : 기존 데이터에 값을 갱신한다!
        if (target!=null){
            articleRepository.save(articleEntity); // 엔티티가 db로 갱신!
        }


        // 3: 수정 결과 페이지로 리다이렉트한다.
        return "redirect:/articles/" + articleEntity.getId();
    }
edit.mustache

{{>layouts/header}}

{{#article}}
<!--    이렇게 감싸주면 title,content,id전부 article.~로 쓰는거 줄여줄 수있다. article.title.등..-->
<form class="container" action="/articles/update" method="post">
<!--    form이 get과 post만 지원해서 put써야하지만 post를 우선 사용하기-->
    <!--    action 어디로, method 어떻게-->
    <input name="id" type="hidden" value="{{id}}">
<!--    아이디도 숨겨서 보내주기-->
    <div class="mb-3">
        <label class="form-label">subject</label>
        <input type="text" class="form-control" name="title" value="{{title}}">
    </div>
    <div class="mb-3">
        <label class="form-label">content</label>
        <textarea class="form-control" rows="3" name="content" >{{content}}</textarea>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
    <a href="/articles/{{id}}">Back</a>
</form>
{{/article}}

{{>layouts/footer}}

Form 태그에서 post와 get만 지원하기 때문에 두가지를 사용했고 원래대로라면 put 을 사용해 줘야한다.

 

전체 흐름을 살펴보면 

 

1)게시 상세글에서 링크를건다 (수정페이지)

 

2)컨트롤러에서 요청을 받는다.

 

3)수정 페이지를 작성한다.

 

4)이때 수정페이지의 기존 데이터를 불러온다.

 

5)기존 데이터의 값을 갱신한다.

 

첫 학습이라 흐름만 최대한 알아보려고 하고있는데도 마냥 쉽지는 않다. 그래도 큰 뭉텅이로는 이해가 가니

 

추후 좀더 자세히 작은 코드단위로 살펴 봐야겠다.

 

 

- 참고

https://m.blog.naver.com/adamdoha/221754911797

스프링부트, 입문!

https://www.inflearn.com/course/%EA%B0%9C%EB%85%90%EC%8B%A4%EC%8A%B5-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8-%EC%9E%85%EB%AC%B8/dashboard

finished with non-zero exit value 1 오류

https://yjh5369.tistory.com/entry/intellij-%EC%8B%A4%ED%96%89-%EC%8B%9C-finished-with-non-zero-exit-value-1-%EC%98%A4%EB%A5%98

profile

날아라김지원

@flykimjiwon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!