월루를 꿈꾸는 대학생

[Springboot] @RequireArgsConstructor & Model 본문

Programing/Spring Boot

[Springboot] @RequireArgsConstructor & Model

하즈시 2023. 1. 1. 01:33
728x90

타임리프 사용하기 

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'

 

질문 전용 컨트롤러 추가 

* @RequireArgsConstructor 로 final 속성 생성자 생성해서 쓰기! 

* model 객체로 html에 값 넘겨주기 

package com.example.sbb.question;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

// questionRepository 속성 포함하는 생성자 생성
// final 붙은 속성을 포함하는 생성자 자동 생성 즉 questionRepository 객체가 자동 주입 -> 권장방식!!!!
@RequiredArgsConstructor
@Controller
public class QuestionController {

    private final QuestionRepository questionRepository;
    @GetMapping("/question/list")
   // @ResponseBody
    public String list(Model model){
        List<Question> questionList = this.questionRepository.findAll();
        // model 객체는 자바 클래스와 템플릿간 연결고리 !
        // model에 값을 담아두면 템플리셍서 그 값 사용 가능  -> 객체 생성 불필요 컨트롤러 메서드에 매개변수 지정하면 자동 모델 객체 생성
        model.addAttribute("questionList", questionList);
        return "question_list";
    }
}

 

모델에서 전달 받은 데이터를 html에 표시하기 

 

<body>
<table>
    <thead>
    <tr>
        <th>제목</th>
        <th>작성일시</th>
    </tr>
    </thead>
    <tbody>
    <!--th 로 시작 : 타임리프 -->
    <!--questionList = Question 객체의 리스트들 ! -->
    <!--<tr> </tr> 이 엘리먼트를 questionList갯수 만큼 반복 출력  = for eatch -->
    <!--question 객체에서 하나씩 제목이랑 날짜를 표시함 -->
    <tr th:each="question : ${questionList}">
        <td th:text="${question.subject}"></td>
        <td th:text="${question.createDate}"></td>
    </tr>
    </tbody>
</table>
</body>

 

 

출처

https://wikidocs.net/161186

 

728x90

'Programing > Spring Boot' 카테고리의 다른 글

[Spring Boot] 서비스  (0) 2023.01.01
[Spring Boot] Root URL  (0) 2023.01.01
[GIT] .gitignore 관리  (0) 2022.12.23
[Spring Boot] Rest API & MySQL & MyBatis 연동  (0) 2022.12.23
[Spring Boot] 간단한 RestApi 만들기  (0) 2022.12.23