20250730 학습일지

창훈·2025년 7월 30일

Templates을 적용하기 위한 Controller 구현

@RequiredArgsConstructor
@Controller
public class QuestionController {
    private final QuestionRepository questionRepository; 

    @GetMapping("/question/list")
    public String list(Model model) { //org.springframework.ui.Model;
        List<Question> questionList = this.questionRepository.findAll();
        model.addAttribute("questionList", questionList);
        return "question_list";
    }
}

@RequiredArgsConstructor : Lombok 라이브러리에서 제공하는 어노테이션.필수 인자를 받는 생성자를 자동으로 만들어주는 기능으로 하단의 private final QuestionRepository questionRepository; 설정에 관여하고 있다. 관련 변수/값을 생성하거나 가져오는 과정을 생략할 수 있다.
떠라서 클래스 내에 import lombok.RequiredArgsConstructor; 이 먼저 선언되어야 한다.
QuestionRepository class 파일에는 @Repository가 선언되어 있어야 하며 관련 변수 특성이 등록되어 있다.

Model model : Spring MVC에서 컨트롤러와 뷰 사이의 데이터를 전달하는 역할.

  • Spring에서 제공하는 인터페이스.(import org.springframework.ui.Model;)
  • 컨트롤러 → JSP(또는 템플릿 뷰) 로 데이터를 실어서 보내주는 바구니 같은 역할.
  • 내부적으로 Map처럼 key-value 구조로 동작
    List questionList = this.questionRepository.findAll();
    model.addAttribute("questionList", questionList);
    return "question_list";
  • 클라이언트가 /question/list 요청
  • list() 메서드가 실행됨
  • questionRepository.findAll()로 데이터 조회
  • model.addAttribute()로 뷰에 데이터 전달
  • 뷰 템플릿 question_list.html

Templates 을 이용한 view 구현

<table class="table-1" style="border:1px" >
    <thead>
    <tr onclick="alert()">
        <th>제목</th>
        <th>내용</th>
        <th>생성일시</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>
            [[${questionList[0].subject}]]
        </td>
        <td>
            [[${questionList[0].content}]]
        </td>
        <td>
            [[${questionList[0].createDate}]]
        </td>
    </tr>
    <tr>
        <td th:text="${questionList[0].subject}"></td>
        <td th:text="${questionList[0].content}"></td>
        <td th:text="${questionList[0].createDate}"></td>
    </tr>
    </tbody>
</table>
<hr>
<table class="table-1" style="border:1px" >
    <thead>
    <tr onclick="alert()">
        <th>ID</th>
        <th>제목</th>
        <th>내용</th>
        <th>생성일시</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="q : ${questionList}">
        <td th:text="${q.id}"></td>
        <td th:text="${q.subject}"></td>
        <td th:text="${q.content}"></td>
        <td th:text="${q.createDate}"></td>
    </tr>
    </tbody>
</table>

REDIRECT TO THE ROOT DIRECTORY WITH SPRINGBOOT

    @GetMapping("/")
    public String root() {
        return "redirect:/question/list";
    }

@ GetMapping annotation을 이용하여 사용자가 Root directory 로 접근했을 때 [site url : localhost]/question/list 으로 포워딩하게 하고 @GetMapping("question/list")가 선언된 곳의 return 값을 실행하게 함.

profile
한줄소개불가

0개의 댓글