# Mustache 추가 및 index.html 추가
Mustache는 JSP처럼 Java코드를 html 상에서 작성하여 동작하는 템플릿 엔진 중 하나다.
대충 템플릿(미리 정의된 문법)에 따라 작성된 Java 코드를 포함하는 html 파일을 문법에 맞게 해석하여 다시 순수 html파일로 만들어주는 엔진이다.
어릴 때 처음 웹 공부할 때 이게 진짜 이해가 잘 안 되고 왜 쓰는지 이해가 안 됐는데, 이젠 뭐.. 당연하게 받아들인다.
## Mustache 설치
더보기
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-mustache:3.0.2'
}
## index.html 작성
더보기
{{>layout/header}}
<h1>스프링 부트로 시작하는 웹 서비스</h1>
{{>layout/footer}}
더보기
<!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>
더보기
<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>
더보기
package com.thuthi.springboot.web;
import com.thuthi.springboot.service.posts.PostsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@RequiredArgsConstructor
@Controller
public class IndexController {
private final PostsService postsService;
@GetMapping("/")
public String index(Model model) {
model.addAttribute("posts", postsService.findAllDesc());
return "index";
}
}
더보기
package com.thuthi.springboot.web;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class IndexControllerTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void 메인페이지_로딩() throws Exception {
// when
String body = this.restTemplate.getForObject("/", String.class);
// then
assertThat(body).contains("스프링 부트로 시작하는 웹 서비스");
}
}
# 게시글 등록 기능
더보기
public class IndexController {
private final PostsService postsService;
@GetMapping("/posts/save")
public String postsSave() {
return "posts-save";
}
}
더보기
{{>layout/header}}
<h1>스프링 부트로 시작하는 웹 서비스</h1>
<div class="row">
<div class="col-md-6">
<a href="/posts/save" role="button" class="btn btn-primary">
글 등록
</a>
</div>
<br>
</div>
{{>layout/footer}}
더보기
let main = {
init: function () {
let _this = this;
$('#btn-save').on('click', function () {
_this.save();
});
},
save: function () {
let 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(() => {
alert('글이 등록되었습니다.');
window.location.href = "/";
}).fail((error) => {
alert(JSON.stringify(error));
});
}
};
main.init();
index.js에서 굳이 화살표 함수를 안 쓰고 function을 통해서 람다함수를 정의하는데,
화살표 함수에서 this binding문제가 발생해서 function으로 정의한다. 자세한 설명은 구글링...
# 전체 조회 화면 만들기
더보기
{{>layout/header}}
<h1>스프링 부트로 시작하는 웹 서비스</h1>
<div class="row">
<div class="col-md-6">
<a href="/posts/save" role="button" class="btn btn-primary">
글 등록
</a>
</div>
<br>
<table class="table table-horizontal table-bordered">
<thead class="thead-strong">
<tr>
<th>게시글번호</th>
<th>제목</th>
<th>작성자</th>
<th>최종수정일</th>
</tr>
</thead>
<tbody id="tbody">
{{#posts}}
<tr>
<td>{{id}}</td>
<td><a href="/posts/update/{{id}}">{{title}}</a></td>
<td>{{author}}</td>
<td>{{updatedAt}}</td>
</tr>
{{/posts}}
</tbody>
</table>
</div>
{{>layout/footer}}
{{#posts}}는 posts라는 list를 순회한다. 내부적으로 for loop을 돌린다고 생각하면 된다.
{{#posts}}아래에 {{}}로 감싸진 변수들은 for loop으로 순회하여 얻은 객체의 필드명이다.
더보기
public interface PostsRepository extends JpaRepository<Posts, Long> {
@Query("SELECT p from Posts p order by p.id desc")
List<Posts> findAllDesc();
}
@Query어노테이션을 사용하지 않고 메서드를 직접 호출해서 해결할 수도 있다.
더보기
public class PostsService {
@Transactional(readOnly = true)
public List<PostsListResponseDto> findAllDesc() {
return postsRepository.findAllDesc().stream()
.map(PostsListResponseDto::new)
.collect(Collectors.toList());
}
}
더보기
package com.thuthi.springboot.web.dto;
import com.thuthi.springboot.domain.posts.Posts;
import java.time.LocalDateTime;
import lombok.Getter;
@Getter
public class PostsListResponseDto {
private final Long id;
private final String title;
private final String author;
private final LocalDateTime updatedAt;
public PostsListResponseDto(Posts posts) {
this.id = posts.getId();
this.title = posts.getTitle();
this.author = posts.getAuthor();
this.updatedAt = posts.getUpdatedAt();
}
}
더보기
public class IndexController {
private final PostsService postsService;
@GetMapping("/")
public String index(Model model) {
model.addAttribute("posts", postsService.findAllDesc());
return "index";
}
}
# 게시글 수정, 삭제
## 게시글 수정
더보기
{{>layout/header}}
<hl> 게시글 수정</hl>
<div class="col-md-12">
<div class="col-md-4">
<form>
<div class="form-group">
<label for=_’id">글번호</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}}
더보기
let main = {
init: function () {
let _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 () {
let 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(() => {
alert('글이 등록되었습니다.');
window.location.href = "/";
}).fail((error) => {
alert(JSON.stringify(error));
});
},
update: function () {
let data = {
title: $('#title').val(),
content: $('#content').val()
};
let id = $('#id').val();
$.ajax({
type: 'PUT',
url: '/api/v1/posts/' + id,
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify(data)
}).done(() => {
alert('글이 수정되었습니다.');
window.location.href = "/";
}).fail((error) => {
alert(JSON.stringify(error));
});
},
delete: function () {
let id = $('#id').val();
$.ajax({
type: 'DELETE',
url: '/api/v1/posts/' + id,
dataType: 'json',
contentType: 'application/json; charset=UTF-8'
}).done(() => {
alert('글이 삭제되었습니다.');
window.location.href = "/";
}).href((error) => {
alert(JSON.stringify(error));
});
}
};
main.init();
더보기
{{>layout/header}}
<h1>스프링 부트로 시작하는 웹 서비스</h1>
<div class="row">
<div class="col-md-6">
<a href="/posts/save" role="button" class="btn btn-primary">
글 등록
</a>
</div>
<br>
<table class="table table-horizontal table-bordered">
<thead class="thead-strong">
<tr>
<th>게시글번호</th>
<th>제목</th>
<th>작성자</th>
<th>최종수정일</th>
</tr>
</thead>
<tbody id="tbody">
{{#posts}}
<tr>
<td>{{id}}</td>
<td><a href="/posts/update/{{id}}">{{title}}</a></td>
<td>{{author}}</td>
<td>{{updatedAt}}</td>
</tr>
{{/posts}}
</tbody>
</table>
</div>
{{>layout/footer}}
더보기
public class IndexController {
@GetMapping("/posts/update/{id}")
public String postsUpdate(@PathVariable Long id, Model model) {
PostsResponseDto postsResponseDto = postsService.findById(id);
model.addAttribute("post", postsResponseDto);
return "posts-update";
}
}
## 게시글 삭제
posts-update.mustache, index.js는 게시글 수정의 코드와 동일하다.
더보기
public class PostsService {
public void delete(Long id) {
Posts posts = postsRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
postsRepository.delete(posts);
}
}
더보기
public class PostsApiController {
@DeleteMapping("/api/v1/posts/{id}")
public Long delete(
@PathVariable Long id) {
postsService.delete(id);
return id;
}
}