스프링부트와 AWS로 혼자 구현하는 웹 서비스 4장

2022. 1. 19. 23:32잡다한 IT/Springboot와 AWS로 혼자 구연하는 웹 서비스

이번장에는 머스테치라는 서버 템플릿 엔진을 통해 HTMl을 구축하는 방법에 대해 알아보도록 하겠다. 머스테치는 심플한 템플릿 엔진으로서 루비, js, python 등등 대부분의 언어를 지원하는 클라이언트 템플릿 엔진이다.

 

https://mustache.github.io/

 

{{ mustache }}

Logic-less templates. Available in Ruby, JavaScript, Python, Erlang, Elixir, PHP, Perl, Raku, Objective-C, Java, C#/.NET, Android, C++, CFEngine, Go, Lua, ooc, ActionScript, ColdFusion, Scala, Clojure[Script], Clojure, Fantom, CoffeeScript, D, Haskell, XQu

mustache.github.io

설치하는 방법도 간단하다. setting에 들어간 후 mustache를 검색 후 다운로드 받으면 된다.

이 후 build.gradle에 아래의 의존성을 추가하도록 하자. 파일위치는 기본적으로 src/main/resources/templates/에 있다.

compile('org.springframework.boot:spring-boot-starter-mustache')

이 후 index.mustache 파일을 만들도록 하자. 개인적으로 vscode와 함께 사용하는것을 권하는데 인텔리 j는 html과 관련된 문법을 많이 지원해 주지 않기 때문에 (ex. ! 을 입력하면 기본 html 화면이 나타나는것과 같은것을 지원해주지 않는다) 코드작성을 vscode에서, 실행을 인텔리 j에서 하는것을 추천한다.

index.mustache(src/main/resources/templates)

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>springboot webservice</title>
</head>
<body>
    <h1>스프링부트로 시작하는 웹 서비스</h1>
</body>
</html>

이 후 url을 Controller에서 매핑해 주도록 하자.

package com.test.page.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {
    @GetMapping("/")
    public String index(){
        return "index";
    }
}

이것이 잘 실행되는지 테스트 코드를 실행해 보도록 하자.

IndexControllerTest(src/test/java/com/test/page/web/Dto)

package com.test.page.web;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class IndexControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void 메인페이지_로딩(){
        //when
        String body = this.restTemplate.getForObject("/", String.class);

        //then
        assertThat(body).contains("스프링부트로 시작하는 웹 서비스");
    }
}

아주 잘 되는것을 확인할 수 있다. 또한 Application을 실행해 8080으로 접근해 보더라도 잘 되는것을 확인할 수 있다.

이제 본격적으로 화면을 만들어 보도록 하자. 기본적인 API는 구축된 상태니 부트스트렙 등인 외부 CDN을 사용해 이쁘게 만들어 보도록 하자. 레이아웃방식으로 추가해 보도록 할 텐데 공통 영역을 별도의 파일로 분리하여 필요한 곳에 가져다 쓰는 방식을 의미한다. 즉 어디에서나 항상 사용되는 화면이라는 의미이다(ex. 화면 최상단의 메뉴, 혹은 최 하단의 저작권, 연락처 등등)

 

css는 header에 js는 footer에 두는것이 페이지 로딩속도를 높일 수 있는 방법이다. html은 위에서부터 코드가 실행되기때문이다.(head => body 순) 그렇기에 js의 용량이 크면 클 수록 body의 실행이 늦어지기에 하단에 두는것이 이롭다.

반면 css는 화면을 '그리는' 역할을 하기에 상단에서부터 만드는것이 좋다. 또한 부트스트렙은 제이쿼리에 의존하기에 상단에 위치하도록 했다.

header.mustache

<!DOCTYPE HTML>
<html>
<head>
    <title>스프링부트 웹서비스</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>

footer.mustache

<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>

<!--index.js는 잠시 후 추가할 예정이다. -->
<script src="/js/app/index.js"></script>
</body>
</html>

자 이제 글 등록 이라는 버튼을 하나 만들어 보도록 하자. 페이지 주소는 /posts/save로 지정했으며 save에 관련된 모든 컨트롤러는 IndexController를 사용하도록 하자.

index.mustache

{{>layout/header}}
<h1>스프링부트로 시작하는 웹 서비스</h1>
<div classs="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}}

posts-save.mustache(resources/templates/posts-save.mustache)

{{>layout/header}}

<h1>게시글 등록</h1>

<div class="col-md-12">
    <div class="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>
        </form>
        <a href="/" role="button" class="btn btn-secondary">취소</a>
        <button type="button" class="btn btn-primary" id="btn-save">등록</button>
    </div>
</div>

{{>layout/footer}}

IndexController

@RequiredArgsConstructor
@Controller
public class IndexController {
    @GetMapping("/")
    public String index(){
        return "index";
    }

    @GetMapping("/posts/save")
    public String postsSave(){
        return "posts-save";
    }
}

 

접근이 잘 되는것을 확인할 수 있다. 하지만 실제로 등록 버튼을 클릭하게 되더라도 글이 등록되지는 않는데 그 이유는 등록에 대한 '기능' 이 없기 때문이다. 그렇기에 이제 js파일을 추가해 기능을 추가해 보도록 하자.

 

첫 문장을 var main라는 코드를 선언했다. 브라우저의 스코프는 공용공간으로 쓰이기 때문에 나중에 로딩된 js의 init, save가 먼저 로딩된 js의 funcion을 덮어쓰게 된다. 즉 중복함수 이름에 대해 생기는 문제를 방지하기 위해 index.js만의 유효 범위를 만들어 사용하는 것 이다. 이 객체(var main)엔아 모든 function을 선언하기 때문에 index객체 안에서만 funcion이 유효하는 효과를 발생시켜 다른 JS와 곂칠 위험이 사라지게 된다.

index.js(resources/static/js/app/index.js)

var main = {
    init : function () {
        var _this = this;
        $('#btn-save').on('click', function () {
            _this.save();
        });
    },
    save : function () {
        var data = {
            title: $('#title').val(),
            author: $('#author').val(),
            content: $('#content').val()
        };

        $.ajax({
            type: 'POST',
            url: '/api/v1/posts',
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            data: JSON.stringify(data)
        }).done(function() {
            alert('글이 등록되었습니다.');
            window.location.href = '/';
        }).fail(function (error) {
            alert(JSON.stringify(error));
        });
    }
};
main.init();

글이 등록되었다는 알람이 나타났다! 이제 이 알람이 실제로 적용되고 있는지 h2콘솔을 통해서 확인해 보도록하자. select*from posts를 실행해 보니 잘 저장된 것을 확인할 수 있다.

이제 기세를 몰아서 게시글 수정, 삭제 기능을 추가해 보도록 하자.

먼저 PostsRepository에 아래의 쿼리를 추가하자.

@Query("SELECT p FROM pOSTS p ORDER BY p.id DESC")
List<Posts> findAlldesc();

그 다음으로는 PostsService에 아래의 코드를 추가하자. 아직 PostsListResponseDto클레스가 없으니 역시 이것도 생성하도록 하자.

@Transactional(readOnly = true)
public List<PostsListResponseDto> findAllDesc(){
    return postsRepository.findAllDesc().stream()
            .map(PostsListResponseDto::new)
            .collect(Collectors.toList());
}

PostsListResponseDto

@Getter
public class PostsListResponseDto {
    private Long id;
    private String title;
    private String author;
    private LocalDateTime modifiedDate;

    public PostsListResponseDto(Posts entity) {
        this.id = entity.getId();
        this.title = entity.getTitle();
        this.author = entity.getAuthor();
        this.modifiedDate = entity.getModifiedDate();
    }
}

IndexController

@RequiredArgsConstructor
@Controller
public class IndexController {

    private final PostsService postsService;

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("posts", postsService.findAllDesc());
        return "index";
    }

    @GetMapping("/posts/save")
    public String postsSave() {
        return "posts-save";
    }

    @GetMapping("/posts/update/{id}")
    public String postsUpdate(@PathVariable Long id, Model model) {
        PostsResponseDto dto = postsService.findById(id);
        model.addAttribute("post", dto);

        return "posts-update";
    }
}

posts-update.mustache(templates/posts-update.mustache)

{{>layout/header}}

<h1>게시글 수정</h1>

<div class="col-md-12">
    <div class="col-md-4">
        <form>
            <div class="form-group">
                <label for="title">글 번호</label>
                <input type="text" class="form-control" id="id" value="{{post.id}}" readonly>
            </div>
            <div class="form-group">
                <label for="title">제목</label>
                <input type="text" class="form-control" id="title" value="{{post.title}}">
            </div>
            <div class="form-group">
                <label for="author"> 작성자 </label>
                <input type="text" class="form-control" id="author" value="{{post.author}}" readonly>
            </div>
            <div class="form-group">
                <label for="content"> 내용 </label>
                <textarea class="form-control" id="content">{{post.content}}</textarea>
            </div>
        </form>
        <a href="/" role="button" class="btn btn-secondary">취소</a>
        <button type="button" class="btn btn-primary" id="btn-update">수정 완료</button>
        <button type="button" class="btn btn-danger" id="btn-delete">삭제</button>
    </div>
</div>

{{>layout/footer}}

index.js

var main = {
    init : function () {
        var _this = this;
        $('#btn-save').on('click', function () {
            _this.save();
        });

        $('#btn-update').on('click', function () {
            _this.update();
        });

        $('#btn-delete').on('click', function () {
            _this.delete();
        });
    },
    save : function () {
        var data = {
            title: $('#title').val(),
            author: $('#author').val(),
            content: $('#content').val()
        };

        $.ajax({
            type: 'POST',
            url: '/api/v1/posts',
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            data: JSON.stringify(data)
        }).done(function() {
            alert('글이 등록되었습니다.');
            window.location.href = '/';
        }).fail(function (error) {
            alert(JSON.stringify(error));
        });
    },
    update : function () {
        var data = {
            title: $('#title').val(),
            content: $('#content').val()
        };

        var id = $('#id').val();

        $.ajax({
            type: 'PUT',
            url: '/api/v1/posts/'+id,
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            data: JSON.stringify(data)
        }).done(function() {
            alert('글이 수정되었습니다.');
            window.location.href = '/';
        }).fail(function (error) {
            alert(JSON.stringify(error));
        });
    },
    delete : function () {
        var id = $('#id').val();

        $.ajax({
            type: 'DELETE',
            url: '/api/v1/posts/'+id,
            dataType: 'json',
            contentType:'application/json; charset=utf-8'
        }).done(function() {
            alert('글이 삭제되었습니다.');
            window.location.href = '/';
        }).fail(function (error) {
            alert(JSON.stringify(error));
        });
    }

};

main.init();

postsService

@Transactional
public void delete (Long id) {
    Posts posts = postsRepository.findById(id)
            .orElseThrow(() -> new IllegalArgumentException("해당 사용자가 없습니다. id=" + id));

    postsRepository.delete(posts);
}

PostsApiController

@DeleteMapping("/api/v1/posts/{id}")
public Long delete(@PathVariable Long id) {
    postsService.delete(id);
    return id;
}

 

자 이렇게 해서 4장을 마치도록 하겠다.