Spring/My First Blog Project
My First Blog Project (16) : 게시판 글 목록 보기
디깅
2022. 12. 26. 09:37
728x90
BoardController.java
package com.cos.blog.controller;
import com.cos.blog.config.auth.PrincipalDetail;
import com.cos.blog.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class BoardController {
@Autowired
private BoardService boardService;
@GetMapping({"","/"})
public String index(Model model){
model.addAttribute("boards",boardService.글목록());
return "index"; //viewResolver 작동
}
//USER권한이 필요
@GetMapping("/board/saveForm")
public String saveForm(){
return "board/saveForm";
}
}
Model에 담아서 board 전체를 화면으로 넘겨준다.
화면에서 사용하는 이름이 boards, 넘기는 data는 service에서 리턴되는값을 넘긴다
BoardService.java
package com.cos.blog.service;
import com.cos.blog.model.Board;
import com.cos.blog.model.User;
import com.cos.blog.repository.BoardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Service
public class BoardService {
@Autowired
private BoardRepository boardRepository;
@Transactional
public void 글쓰기(Board board, User user){
board.setCount(0);
board.setUser(user);
boardRepository.save(board);
}
public List<Board> 글목록() {
return boardRepository.findAll();
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ include file="layout/header.jsp" %>
<div class="container">
<c:forEach var="board" items='${boards}'>
<div class="card m-2">
<div class="card-body">
<h4 class="card-title">${board.title}</h4>
<a href="#" class="btn btn-primary"></a>
</div>
</div>
</c:forEach>
</div>
<%@ include file="layout/footer.jsp" %>
items에 controller가 넘겨준 model을 받는다.
넘겨온 boards를 forEach로 하나씩 꺼재준다.
${board.title}로 하나씩 뿌려준다.
반응형