1. Service
클래스
- 기존의
findAll
메서드는 Board 객체의 리스트를 반환
- 위 반환값을 그대로 사용할 시 문제점 :
- 진행 중인 예제에서는 Board 객체의 id와 title만 활용할 예정입니다.
- 따라서 나머지 정보들은 전달하지 않아도 되는 불필요한 정보입니다.
따라서 단순히 Board 객체를 반환하지 않고, DTO 객체를 새로 만들어 필요한 정보만 담은 객체를 전달하도록 구성
1. DTO 클래스 내용:
public class BoardResponse {
@Data
public static class DTO {
private int id;
private String title;
public DTO(Board board) {
this.id = board.getId();
this.title = board.getTitle();
}
}
}
2. 위 DTO 클래스를 토대로 작성한 Service 객체 내용:
@RequiredArgsConstructor
@Service
public class BoardService {
private final BoardRepository boardRepository;
public List<BoardResponse.DTO> 게시글목록보기() {
List<BoardResponse.DTO> dtos = new ArrayList<>();
List<Board> boardList = boardRepository.findAll();
for (Board board : boardList) {
BoardResponse.DTO dto = new BoardResponse.DTO(board);
dtos.add(dto);
}
return dtos;
}
}
- 새로운 DTO 리스트를 생성. (빈 리스트)
- findAll 메서드를 통해 먼저 Board 객체 리스트를 반환 받음
- for-each 문을 통해 DTO를 반복적으로 생성하고, DTO 리스트에 담음
- 반복이 끝나면 DTO 리스트를 반환
2. Controller
@RequiredArgsConstructor// final이 붙어있는 변수의 생성자를 만들어 줌
@Controller
public class BoardController {
private final BoardService boardService;
// 컨트롤러는 view resolver 클래스를 가지고 있고, return 문자열과 동일한 파일을 찾아서 실행
@GetMapping("/")
public String list(Model model) { // DS(request 객체를 model이라는 객체로 랩핑해서 전달
List<BoardResponse.DTO> boardList = boardService.게시글목록보기();
model.addAttribute("models", boardList);
return "list";
}
}
Controller
는 전달 받은 DTO 리스트를model
에 담고Dispatcher-Servlet
에list
문자열을 전달Model
:request
객체를 랩핑한(감싼) 객체
Dispatcher-Servlet
은list
이름을 가진 뷰를 찾아 렌더링, 이 뷰는 주로 HTML 파일로 변환되어 클라이언트에 응답
3. 수정된 list.mustache
파일 내용
<section>
<table border="1">
<tr>
<th>번호</th>
<th>제목</th>
<th></th>
</tr>
{{#models}}
<tr>
<td>{{id}}</td>
<td>{{title}}</td>
<td><a href="/board/{{id}}">상세보기</a></td>
</tr>
{{/models}}
</table>
</section>
{{#모델속성명}} // 반복시작
{{필드값}}
{{/모델속성명}} // 반복종료
- 반복문 안에서 Board 객체의 특정 필드 값을 이용하려고 할 때도 중괄호 2개와 필드 명만 작성하면 쉽게 사용할 수 있음
4. 최종 출력 결과

Share article