Spring Boot To do List_02 main page

송지윤·2024년 4월 12일
0

Spring Framework

목록 보기
18/65

Main page

main 페이지 들어가자마자 전체 Todo 개수, 완료된 Todo 개수, 할 일 목록 보여줄 거

브라우저에서 요청 보냈을 때 DB 조회해와야해서 Controller 에서 최상위 요청 받아서 html 보여주는 경로 return 해줄 거

main 페이지 보여줄 때 해야할 거

  1. controller 에서 service 메서드 호출
  2. service 에서 List 형태로 todoList select 문 조회 sql 메서드 호출
  3. service 에서 완료된 개수 조회 하는 select 문 조회 sql 메서드 호출
  4. Mapper 인터페이스에 추상메서드 생성해서 mapper.xml 에서 sql 문 작성해서 값 돌려보냄
  5. service 단으로 돌아온 값을 Map 형태로 세팅 후 다시 Controller로 돌려줌
  6. Controller에서 돌려 받은 Map을 다시 나눠서 request scope에 실어서 html 로 보내줌
  7. html 에서 thymeleaf 사용하여 화면 출력

1. controller 에서 service 메서드 호출

Service 메서드 호출 후 결과 반환 받기
목록 조회 , 카운트 조회 -> Map 으로 가져올 거

MainController

Map<String, Object> map = service.selectAll();

2. service 에서 List 형태로 todoList select 문 조회 sql 메서드 호출

3. service 에서 완료된 개수 조회 하는 select 문 조회 sql 메서드 호출

TodoServiceImpl

	// 할 일 목록 + 완료된 할 일 개수 조회
	@Override
	public Map<String, Object> selectAll() {
		
		// 1. 할 일 목록 조회
		List<Todo> todoList = mapper.selectAll();
		// 2. 완료된 할 일 개수 조회
		int completeCount = mapper.getCompleteCount();
  1. Mapper 인터페이스에 추상메서드 생성해서 mapper.xml 에서 sql 문 작성해서 값 돌려보냄

TodoMapper interface

	/** 할 일 목록 조회
	 * @return todoList
	 */
	List<Todo> selectAll();

	/** 완료된 할 일 개수 조회
	 * @return completeCount
	 */
	int getCompleteCount();

todo-mapper.xml

	<select id="selectAll" resultType="Todo">
		SELECT TODO_NO, TODO_TITLE , TODO_CONTENT , COMPLETE,
		TO_CHAR(REG_DATE, 'YYYY-MM-DD HH24:MI:SS') REG_DATE 
		FROM TB_TODO
		ORDER BY TODO_NO
	</select>
	
	<!-- Java 의 int 는 마이바티스의 _int -->
	<select id="getCompleteCount" resultType="_int">
		SELECT COUNT(*)
		FROM TB_TODO
		WHERE COMPLETE = 'Y'
	</select>

com.home.todo.model.mapper.TodoMapper 이 인터페이스의 selectAll() 메서드와 연결 ==> selectAll() 메서드 호출 시 연결된 SQL 실행
com.home.todo.model.dto.Todo -> Todo 라고 써도 됨 (DBConfig에서 별칭 등록 해둠)

<select> 태그 속성

  • id 속성 : 태그를 식별하는 값
    (연결된 Mapper 의 메서드명과 동일하게 작성해서 연결)
  • resultType : 조회 결과 한 줄(1행)을 저장하여 반환할 변수/객체 자료형 지정
    -> 조회 결과가 여러 행이면 행 별로 변수/객체 자료형으로 저장 후 모아서 List 로 반환

5. service 단으로 돌아온 값을 Map 형태로 세팅 후 다시 Controller로 돌려줌

TodoServiceImpl

		// Map 으로 묶어서 반환
		Map<String, Object> map = new HashMap<>();
		
		map.put("todoList", todoList);
		map.put("completeCount", completeCount);
		
		return map;
}

6. Controller에서 돌려 받은 Map을 다시 나눠서 request scope에 실어서 html 로 보내줌

MainController

map에 담긴 내용 추출
Map에 value가 Object형이어서 List<Todo> 형태로 다운캐스팅 해줌

completeCount도 마찬가지 int로 다운 캐스팅


		List<Todo> todoList = (List<Todo>) map.get("todoList");

		int completeCount = (int)map.get("completeCount");
		
		// request scope 에 세팅해서 보내줄 거임
		// Model : 값 전달용 객체(request scope) + session 변환 가능
		model.addAttribute("todoList", todoList);
		model.addAttribute("completeCount", completeCount);
		
		// 메인페이지로 forward 시켜줄거임
		return "common/main";
		// classpath:/templates/
		// common/main
		// .html
		// -> 이쪽으로 forward 시켜주겠다.

7. html 에서 thymeleaf 사용하여 화면 출력

table로 정리해서 List 출력

<body>
    <h1>Todo List</h1>

    <!-- ${#lists.size(todoList)} == ${todoList.size()} -->
    <h3 th:text="|전체 Todo 개수 : ${#lists.size(todoList)}개 / 
    완료된 Todo 개수 : ${completeCount}개|">내용</h3>

    <table border="1">
        <thead>
            <th>번호</th>
            <th>할 일 제목</th>
            <th>완료 여부</th>
            <th>등록 날짜</th>
        </thead>

        <tbody>
            <tr th:each="todo : ${todoList}" th:object="${todo}">
                
                <td th:text="*{todoNo}">할 일 번호</td>

                <td>
                    <a th:text="*{todoTitle}">할 일 제목</a>
                </td>

                <td th:text="*{complete}">완료 여부(Y/N)</td>

                <td th:text="*{regDate}">등록일</td>
            </tr>
        </tbody>
    </table>
</body>

0개의 댓글