728x90

Controller에서 정보 find 해서 프론트 html 화면으로 넘겨주는 과정에서 계속 문제가 생겼다... ㅠ ㅠ ㅠ ㅠ

일단 템플릿 파싱 문제가 여러가지 나왔는데 인자값을 어떻게 어떻게 바꿔주어도 해결이 안되었다... 아놔

 

마지막에 나온 오류가 이것이었다. 

 

Property or field ' ? ' cannot be found on object of type 'java.util.ArrayList' - maybe not public or not valid?

 

 

흠 필드/프로퍼티 뭐가 public이 아니라구여...? 먼소리얌........

 

일단 냅다 써치

 

일단 내 원래 컨트롤러 코드가 이랬다.

 

<Controller>

    @GetMapping("/")
    public String todoList(Model model) {
        List<Todo> todoList = todoService.findAll(); // todoService의 전체투두 조회 불러들여서 List에 저장
        model.addAttribute("todoList", todoList); //그 결과를 모델에 맵핑하여 todoList.html로 이동!
        return "todoList";
    }

 

원인은 이 컨트롤러에 있었다. 

컨트롤러에서 뷰로 넘겨줄 때 List<Todo> 이렇게 리스트로 담아 넘겨준 것이 문제였다..... 

 

모델에 맵핑 시켜줄 때 쓰는 메서드를 살펴보았다.

addAttribute(String name, Object value) : value 객체를 name 이름으로 추가해줌 > 뷰에서는 name으로 지정된 value를 사용한다.

 

그러면 addAttribute("todoList", todoList) : todoList 객체를 "todoList"이름으로 추가해주므로

뷰에서 "todoList"를 불러들이면 이 지정된 value인 todoList객체를 받아오는 것이다..

즉 Todo객체를 모아놓은 List 객체를 받아오는 것이다.

 

그것이 아니라 나는 todoService.findAll()에서의 Todo 객체의 정보 하나하나가 필요한 것이다!! 

 

그러려면 Controller에서 얘를 List<Todo>로 변수를 만들어서 저장하여 전달해주는 것이 아니라, value 자리에 바로 넣어주어야 한다!

    @GetMapping("/")
    public String todoList(Model model) {
        model.addAttribute("todoList",  todoService.findAll());
        return "todoList";
    }

 

 

 

그리고 html파일에서 이 name을 적어주면 된다. 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Todo List</title>
</head>
<body>

<h1>Todo List</h1>

<form action="#" th:action="@{/add}" th:object="${todoList}" method="post">
    <label for="todo">Task:</label>
    <input type="text" id="todo" name="todo" th:value="${todo}" required>
    <input type="hidden" id="id" name="id" th:value="${id}">
    <input type="hidden" id="done " name="done" th:value="${done}">
    <button type="submit">Add Task</button>
</form>

<table id="container">
    <thead>
    <tr>
        <th>N.</th>
        <th>To do</th>
        <th>Done</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="do: ${todoList}">
        <td th:text="${do.id}"></td>
        <td th:text="${do.todo}"></td>
        <td th:text="${do.done}?'완료':'진행중'"></td>
    </tr>
    </tbody>
</table>

</body>
</html></body>

 

 

 

문제가 해결되어 요렇게 이쁘게 잘 나왔다.

개발자 도구 통해 보면 이렇게 하나씩 잘 나와서 넣어졌다! 

728x90

BELATED ARTICLES

more