Template

suhan cho·2022년 7월 7일
0

404에러 안뜨게

@Controller
public class QuestionController {
    @RequestMapping("/question/list")
    @ResponseBody
    public String list(){
        return "question_list";
    }
}

템플릿 설정

  • 보통 브라우저에 응답하는 문자열은 return question_list 이런식으로 직접 만들지 않는다.

  • 일반적으로 템플릿 방식으로 작성한다.

탬플릿이란?

  • 자바코드를 삽입할 수 있는 HTML형식의 파일
  • 스프링부트에서는 템플릿 엔진으로 Thymeleaf, Mustache, Groovy등이 있다.

템플릿 작성

이 위치에

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>hello </h2>
</body>
</html>

작성한 후

Controller
public class QuestionController {
    @RequestMapping("/question/list")
//    @ResponseBody
    public String list(){
        return "question_list";
    }
}
  • @ResponseBody 생략

데이터 조회하여 템플릿에 전달

  • 템플릿에 질문목록을 조회하기 위해서는 Question리포지터리를 사용해야한다.
  • Question 리포지터리로 조회한 질문 목록은 Model 클래스를 사용하여 템플릿에 전달 가능
@Controller
public class QuestionController {

    @Autowired
    private final QuestionRepository questionRepository;

    public QuestionController(QuestionRepository questionRepository) {
        this.questionRepository = questionRepository;
    }


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

의존성주입

  • @Autowired속성 - @Autowired를 적용하여 객체를 주입하는 방식

  • 생성자 - 생성자를 작성하여 객체를 주입하는 방식 (권장하는 방식)

  • Setter - Setter 메서드를 작성하여 객체를 주입하는 방식 ( 메서드에 @Autowired 애너테이션 적용이 필요)

  • Question 리포지터의 findAll 메서드를 사용하여 질문목록 데이터인 questionList를 생성하고 Model객체에 "questionList"라는 이름으로 값을 저장했다

  • Model 객체는 자바클래스와 템플릿간의 연결고리 역할

  • Model 객체에 값을 담아두면 템플릿에서 그 값을 사용할 수 있다.

( Model 객체는 따로 생성할 필요없이 컨트롤러 메서드의 매개변수로 지정하기만 하면 스프링부트가 자동으로 Model 객체를 생성)

템플릿에서 전달받은 데이터 사용하기

  • Model객체에 저장한 값을 템플릿에 사용하는 방법
<table xmlns:th="http://www.w3.org/1999/xhtml">
    <thead>
        <tr>
            <th>제목</th>
            <th>작성일시</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="question : ${questionList}">
            <td th:text="${question.subject}"></td>
            <td th:text="${question.createDate}"></td>
        </tr>
    </tbody>
</table>

th:each="question : ${questionList}"

  • th로 시작하는 속성은 타임리프 템플릿 엔진이 사용하는 속성
  • "questionList"라는 이름으로 Model객체에 저장
  • 타임리프는 Model객체에 저장된 값을 읽을 수 있으므로 템플릿에서 questionList를 사용할 수 있게 한다.
    • questionList에 저장된 데이터를 하나씩 꺼내 question객체에 대입하여 반복구간내에서 사용할 수 있게한다.

자주 사용하는 타임리프 속성

  1. 분기문 속성
  • th:if="${question != null}"
  • null이 아닌 경우에 해당 엘리먼트가 표시된다
  1. 반복문 속성
  • 자바의 for each문과 유사
  • th:each="question : ${questionList}"
  1. 텍스트 속성
  • th:text=값은 해당 엘리먼트의 텍스트로 값 출력
  • th:text="${question.subject}"
profile
안녕하세요

0개의 댓글