일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- index.html
- TDD
- 코딩테스트
- spring
- rombok
- test case
- SpringBean
- JPA
- SpringDataJPA
- springboot
- DynamicProgramming
- 프로그래머스
- baekjoon
- 해싱
- API
- C++
- SpringSecurity
- JPA autiding
- testcode
- kotlin
- 알고리즘
- SpringFramework
- mustache
- tdo
- DB
- 알고리즘 #코딩테스트 #프로그래머스 #C++ #vector #string
- Java
- gitignore
- Gradle
- Comparable
- Today
- Total
천천히, 한결같이
[Spring] 글 등록 화면 만들기 본문
이동욱 님의 스프링 부트와 AWS로 혼자 구현하는 웹 서비스책을 공부하며 정리한 내용입니다. 틀린 정보가 있을 수 있으니 주의하시고 댓글로 남겨주시길 바랍니다.
공통 Layout 추가하기
프론트엔드 라이브러리를 사용할 수 있는 방법은 크게 2가지가 있습니다. 하나는 외부 CDN을 받아서 사용하는 방법이고, 하나는 직접 라이브러리를 받아서 사용하는 방법입니다.
실무에선 외부 CDN을 받아서 사용하게 된다면 외부 CDN에 서비스가 종속, 즉 의존되는 문제가 생기 때문에 후자의 방법을 사용합니다. 저희는 우선 전자인 외부 CDN을 사용해서 구현해 보겠습니다. HTML/JSP/Mustache
에 코드만 한 줄 추가하면 사용할 수 있어서 매우 편리합니다!
2개의 라이브러리 부트스트랩과 제이쿼리를 index.mustache
에 추가해야 합니다만, 바로 추가하지 않고 레이아웃 방식으로 추가해 보겠습니다. 공통 영역을 별도의 파일로 분리하여 필요한 곳에서 가져다 쓰는 방식을 의미합니다. 요번에 추가하는 2개의 라이브러리는 머스테치 화면 어디에서나 필요하기 때문에 레이아웃 파일을 따로 만들어서 추가합니다.
src/main/resources/templates
디렉토리에 layout
디렉토리를 추가로 생성하고, header.mustache
, footer.mustache
파일을 생성합니다.
- 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>
</body>
</html>
페이지의 로딩속도를 높이기 위해서 css는 header에, js는 footer에 배치합니다. HTML은 위에서 부터 실행이 된다는 점을 활용해 위와 같이 배치한다면 페이지의 로딩속도를 상승시킬 수 있습니다.
위와 같이 layout 디렉토리를 통해서 공통되는 모든 mustache 파일에 header와 footer를 설정했으니, index.mustache는 아래와 같이 코드가 단순화됩니다!
- index.mustache (전)
<!DOCTYPE HTML>
<html>
<head>
<title>SpringBoot Webservice</title>
<meta http-equiv="Content-Type" content = "text/html"; charset="UTF-8" />
</head>
<body>
<h1>Webservice with SpringBoot</h1>
</body>
</html>
- index.mustache (후)
{{>layout/header}}
<h1>Webservice with SpringBoot</h1>
{{>layout/footer}}
글 동록 UI 만들기
layout을 활용해서 header, footer를 분리했으니 이제 index.mustache
에 글 등록 버튼을 추가합니다.
- index.mustache
{{>layout/header}}
<h1>Webservice with SpringBoot</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}}
<a>
태그를 활용해서 글 등록 페이지로 이동하는 글 등록 버튼을 만들었습니다. 이동하는 주소는 /posts/save
입니다. 당연히 posts/save
주소에 해당하는 Controller를 IndexController
에다가 만들어줍니다! (페이지에 관련된 컨트롤러는 모두 IndexController를 사용합니다.)
- IndexController.java
package com.hwanld.book.springboot.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
@GetMapping("posts/save")
public String postsSave() {
return "posts-save";
}
}
/posts/save
를 호출하면 posts-save.mustache
를 호출하는 메소드가 추가되었습니다. 당연하게 posts-save.mustache
파일을 생성해 주도록 합니다. 위치는 index.mustache와 동일하게 설정합니다.
- 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}}
여기까지 추가하고 난 후, 제대로 동작하는 지 확인하기 위해서 tomcat을 직접 실행시켜서 확인해봅니다. http://localhost:8080
주소로 접속하면 당연히 index.mustache 파일을 볼 수 있을테고, <a>
태그를 사용해서 만들어 두었던 버튼을 클릭하면 http://localhost:8080/posts/save
주소로 이동되고, 컨트롤러에 의해서 posts-save.mustache
파일을 볼 수 있을 것입니다!
하지만 글을 등록하는 기능을 따로 구현하지 않아서 지금 등록 버튼은 사용이 불가할 것 입니다. 등록 버튼에 기능을 만들어 주기 위해서 API를 호출하는 JS를 src/main/resources
에 static/js/app
디렉토리를 생성하고 index.js
파일을 생성합니다.
글 등록 API 구현하기
- 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();
js를 생성했으니, mustache에서 사용할 수 있도록 footer.mustache에 추가하면 js를 사용할 수 있을 겁니다! 아래와 같이 footer.mustache를 수정해서 js를 추가해 주도록 합니다.
- 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>
index.js 호출 코드를 보면 절대 경로로 바로 시작합니다. 스프링 부트는 기본적으로 src/main/resources/static
에 위치한 JS, CSS, 이미지 등 정적 파일들은 URL에서 /로 설정됩니다.
모든 기능이 추가되었으니, 톰캣을 실행시켜서 잘 작동하는지 확인한 후, 실제로 등록한 글이 잘 등록되었는지도 localhost:8080/h2-console
에 접속해서 실제로 DB에 데이터가 등록되어 있는지도 확인합니다!
'Spring' 카테고리의 다른 글
[Spring] IntelliJ exit with non-zero value 1 오류 (0) | 2022.01.18 |
---|---|
[Spring] 스프링 시큐리티, OAuth2를 사용해서 Google 서비스 등록하기 (0) | 2022.01.08 |
[Spring] Mustache로 기본 페이지(index.html) 만들기 (0) | 2022.01.01 |
[Spring] 의존성 주입(Dependency Injection) (0) | 2021.12.31 |
[Spring] JPA Auditing으로 생성시간, 수정시간 자동화하기 (0) | 2021.12.31 |