JAVA/Spring Boot

(프로젝트 공부)스프링부트를 이용한 게시글 작성.

ri5 2021. 3. 19. 17:12

-게시글 작성페이지 구현

1. templates에 posts-save.mustache생성.

posts-save 파일 위치

2. posts-save.mustache 템플릿 구현.

{{>layout/header}}
<h1>게시글 등록</h1>

<div class="col-md-12">
    <div calss="col-md-4">
        <form>
            <div class="form-group">
                <label for="title">제목</label>
                <input type="text" class="form-control" id="title" placeholder="제목을 입력하세요">
            </div>

            <div class="form-group">
                <label for="author">작성자</label>
                <input type="text" class="form-control" id="author" placeholder="작성자를 입력하세요">
            </div>

            <div class="form-group">
                <label for="content">내용</label>
                <textarea class="form-control" id="content" placeholder="내용을 입력하세요"></textarea>
            </div>

            <a href="/" role="button" class="btn btn-primary" id="btn-save">등록</a>
        </form>
    </div>
</div>

{{>layout/footer}}

게시글 작성 페이지 

-게시글 작성페이지 이동 추가

1. index.mustache에 추가

<!-- //header 파일 가져오기 -->
{{>layout/header}}
    <h1>스프링 부트로 시작하는 웹 서비스</h1>
    <!--게시글 작성 페이지 이동-->
    <div class ="col-md-12">
        <div class="row">
            <div class = "col-md-6">
                <a href="/posts/save" role="button" class="btn btn-primary">글 등록</a>
            </div>
        </div>
    </div>
{{>layout/footer}}

 

-게시글 작성 기능 구현

1. 게시글 작성 구현을 위해 static/js/app/index.js 생성

index.js 파일 위치

2. index.js 기능 구현.

let main = {
    init : function () {
        let _this = this; //main{}

        //save-btn event handler
        $('#btn-save').on('click', function (){
            _this.save();
        });
    },
    save : function () {

        //html에서 데이터를 가져옴
        let data = {
            title: $('#title').val(),
            author: $('#author').val(),
            content: $('#content').val()
        };

        // 브라우저에서 지원하는 비동기적인 통신방법
        $.ajax({
          type: 'POST', //전송방식
          url: '/api/v1/posts', //호출 url
          dataType: 'json', //전송받는 data type
          contentType:'application/json; charset=utf-8', //서버에서 데이터를 보낼때 보내는 타입
          data: JSON.stringify(data)//게시글에 들어갈 데이터 JSON.stringify()로 문자열로 변형시킴.
        }).done(function (){
            alert('글이 등록되었습니다'); //성공시 띄워줄 알림창
            window.location.href = '/'; //다시 홈페이지로 이동
        }).fail(function (error) {
            alert(JSON.stringify(error)); //실패시 실패이유를 알림창으로 띄워줌
        });

        console.log(data);
    }
};

main.init(); //main에 있는 init기능 실행

3. footer에 스크립트 삽입.

 

 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
		<!-- 게시글 저장 이벤트-->
        <script src="/js/app/index.js"></script>
    </body>
</html>

 

- 동작하는 구조

1.게시글 작성 버튼을 클릭한다. (이벤트 핸들러 실행)

 

let main = {
    init : function () {
        let _this = this; //main{}

        //save-btn event handler
        $('#btn-save').on('click', function (){
            _this.save();
        });
    },
    // 버튼 클릭 이벤트 실행.
    save : function () {

        //html에서 데이터를 가져옴
        let data = {
            title: $('#title').val(),
            author: $('#author').val(),
            content: $('#content').val()
        };

        // 브라우저에서 지원하는 비동기적인 통신방법
        $.ajax({
          type: 'POST', //전송방식
          url: '/api/v1/posts', //호출 url
          dataType: 'json', //전송받는 data type
          contentType:'application/json; charset=utf-8', //서버에서 데이터를 보낼때 보내는 타입
          data: JSON.stringify(data)//게시글에 들어갈 데이터 JSON.stringify()로 문자열로 변형시킴.
        }).done(function (){
            alert('글이 등록되었습니다'); //성공시 띄워줄 알림창
            window.location.href = '/'; //다시 홈페이지로 이동
        }).fail(function (error) {
            alert(JSON.stringify(error)); //실패시 실패이유를 알림창으로 띄워줌
        });

        console.log(data);
    }
};

main.init(); //main에 있는 init기능 실행

2. 이벤트 핸들러가 ajax를 통해 url 호출 컨트롤러 실행

package com.jojoldu.book.springboot.web;

import com.jojoldu.book.springboot.service.posts.PostsService;
import com.jojoldu.book.springboot.web.dto.PostsResponseDto;
import com.jojoldu.book.springboot.web.dto.PostsSaveRequestDto;
import com.jojoldu.book.springboot.web.dto.PostsUpdateRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor //초기화 되지않은 final 필드나 @notnull이 붙은 필드에 생성자를 생성
@RestController //Json 형태로 객체 데이터를 반환하기위한 컨트롤러
public class PostApiController {
    private final PostsService postsService;

    @PostMapping("/api/v1/posts") // @RequestBody 어노테이션을 이용하면 HTTP 요청 Body를 자바 객체로 저장.
    public long save(@RequestBody PostsSaveRequestDto requestDto){
        return postsService.save(requestDto);
    }

    @PutMapping("/api/v1/posts/{id}") //기존의 Mapping 정보를 수정하는데 사용.
    public long update(@PathVariable Long id, @RequestBody PostsUpdateRequestDto requestDto){
        return postsService.update(id, requestDto);
    }

    @GetMapping("/api/v1/posts/{id}") //특정 핸들링 메서드에 매핑하기위하
    public PostsResponseDto findById(@PathVariable Long id){
        return postsService.findById(id);
    }
}

 3. 컨트롤러의 @Requestbody  PostsSaveRequestDto를 통해 https에서 요청받은 body를 자바객체로 받아옴

package com.jojoldu.book.springboot.web.dto;

import com.jojoldu.book.springboot.domain.posts.Posts;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
public class PostsSaveRequestDto {
    private String title;
    private String content;
    private String author;

    @Builder
    public PostsSaveRequestDto(String title, String content, String author) {
        this.title = title;
        this.content = content;
        this.author = author;
    }

    public Posts toEntity() {
        return Posts.builder()
                .title(title)
                .content(content)
                .author(author)
                .build();
    }
}

 

4. PostSaveRequestDto를 통해 받은 객체를 저장하는 메서드 실행.(postsService에 save 메서드 실행)

package com.jojoldu.book.springboot.service.posts;

import com.jojoldu.book.springboot.domain.posts.PostsRepository;
import com.jojoldu.book.springboot.domain.posts.Posts;
import com.jojoldu.book.springboot.web.dto.PostsResponseDto;
import com.jojoldu.book.springboot.web.dto.PostsSaveRequestDto;
import com.jojoldu.book.springboot.web.dto.PostsUpdateRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@RequiredArgsConstructor //초기화 되지않은 final 필드나 @notnull이 붙은 필드에 생성자를 생성
@Service
public class PostsService {
    private final PostsRepository postsRepository;

    @Transactional//여러기능을 하나로 묶어 실행해서 하나라도 잘못되면 모두 취소해야한다(데이터 무결성 보장).
    public long save(PostsSaveRequestDto requestDto){
        return postsRepository.save(requestDto.toEntity()).getId();
    }
    public long save(PostsSaveRequestDto requestDto){
        return postsRepository.save(requestDto.toEntity()).getId();
    }

    @Transactional
    public Long update(Long id, PostsUpdateRequestDto requestDto){
        Posts posts = postsRepository.findById(id).orElseThrow(() ->
                new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
        posts.update(requestDto.getTitle(), requestDto.getContent());

        return id;
    }

    public PostsResponseDto findById (long id) {
        System.out.print("아이디는" + id);
        Posts entity = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));

        return new PostsResponseDto(entity);
    }
}

 

5. 받은 데이터 객체 저장

package com.jojoldu.book.springboot.domain.posts;

import org.springframework.data.jpa.repository.JpaRepository;

public interface PostsRepository extends JpaRepository<Posts, Long> {

}

JpaRepository.save()의 기능

  • Transient(새로운) 상태의 객체라면 EntityManager.persist() 
  • Detached(이미있는) 상태의 객체라면 EntityManager.merge()

EntityManager.persist() 

엔티티 매니저(Session)를 통해서 엔티티를 영속성 컨텍스트에 저장했다.

 

EntityManager.merge()

기존에 있는 데이터면 update 없으면 insert