Coding/Back - Spring Framework

Spring View-Thymeleaf #Day16

꿀딴지- 2023. 9. 11. 14:12

Thymeleaf

Spring에서 MVC의 View를 구현하기 위해 사용하는 방법 중 하나(mustche → 좀더 간단)

BE에서 FE까지 구현하는 방식이며 SSR : 서버 사이드 랜더링(view)

dependencies { ...
	//타임리프
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	
}

~APIController : API 컨트롤러 @RestController

~ViewController : 화면제어 컨트롤러 @Controller

  • getmapping만 사용 : post/put/delete 방식은 데이터를 처리하기 위한 메서드 → 일반 주소창에는 데이터를 실을 수가 없어서 오류가 남
  • 파일명을 return해줌 → 템플릿 엔진이 해석해서 해당 html 띄워줌(파일명 바뀌면 같이 바뀌어야 함)
  • resources 폴더
    1. templates : .html 파일
    2. static : js, 이미지 파일
  • Model 객체를 통해 html에 데이터 전달 가능
@Controller
@RequiredArgsConstructor
public class ArticleViewController {
    private final ArticleService articleService;
    private final ArticleMapper articleMapper;

    //전체 게시글 조회
    @GetMapping("/articles")
    public String getAllArticels(Model model){
        Page<Article> pageArticles = articleService.findAllArticle(0, 10);
        //List<ArticleResponseDto> articles = articleMapper.articleToArticleResponseDtos(pageArticles.getContent());
        List<ArticleResponseDto> articles = ArticleResponseDto.articleToArticleResponseDtos(pageArticles.getContent());
        model.addAttribute("articles", articles);
        return "articleList";
    }

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Articles</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div>
        <div>로그인 정보 : <span id = "printId"></span>
        <a href="/newArticle" class="btn btn-primary btn-sm">새 게시글 작성하기</a>
        <button type="button" id="viewBTN" class="btn btn-primary btn-sm">작성글 보기</button>
        </div>
        <script>
            name = sessionStorage.getItem('name');
            viewWriterBtn = true;
            if(name===""|| name === 'undefined' || name === 'null'){
                name = "사용자 정보 없음 "
                viewWriterBtn = false;
            }
            else if(name === "게스트") viewWriterBtn = false;
            console.log(name);
            document.getElementById("printId").innerText = name;
        </script>
    </div>
    <div class="row-6" th:each="item : ${articles}">
        <div class="card">
            <div class="card-header" th:text="|${itemStat.index+1} / ${item.title}|"></div>

            <div class="card-body">
                <input type="hidden" id="articleId" th:value="${item.articleId}">
                <a th:href="@{/articles/{id}(id=${item.articleId})}"> 상세 </a>
                <p class="card-text" th:text="|내용 : ${item.content}|"></p>
            </div>
            <div class="card-footer text-muted" th:text="|작성자 : ${item.memberName}  / 작성일 : ${#temporals.format(item.createdAt, 'yy년 M월 d일 HH:mm')}|"></div>
        </div>
    </div>
</div>
<script th:inline="javascript" src="/js/article.js"></script>
</body>
</html>

 

타임리프 조건문

<a th:href="@{/articles/{id}(id=${item.id})}" class="btn btn-primary">조회</a>
<button type="button" id="modify-btn"
                th:onclick="|location.href='@{/new-article?id={articleId}(articleId=${article.id})}'|"
                class="btn btn-primary btn-sm">수정</button>
        <button type="button" id="delete-btn"
                class="btn btn-secondary btn-sm">삭제</button>