관리 메뉴

너와 나의 스토리

[Spring] 게시판 만들기(2) - Service/Controller/View 본문

개발/Spring Boot

[Spring] 게시판 만들기(2) - Service/Controller/View

노는게제일좋아! 2021. 1. 11. 21:33
반응형

1. Service 생성

  • 서비스 영역은 일반적으로 "Service interface"와 "Service Implementation" 클래스 두 개로 나누어 작성한다.
    • 이와 같이 인터페이스와 구현체를 분리하는 이유:
      • "느슨한 결합"을 유지하여 각 기능 간의 의존관계를 최소화 -> 기능의 변화에도 최소한의 수정만 필요
      • 모듈화를 통해 어디서든 사용할 수 있도록 하여 재사용성을 높임
      • 스프링의 IoC/DI 기능을 이용한 bean 관리 기능을 사용할 수 있다.
  • "BoardService" interface 생성
package com.example.board.board.service;

import com.example.board.board.dto.BoardDto;

import java.util.List;

public interface BoardService {

    List<BoardDto> selectBoardList() throws Exception;

}
  • "BoardServiceImpl" 구현체 생성
package com.example.board.board.service;

import com.example.board.board.dto.BoardDto;
import com.example.board.board.mapper.BoardMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BoardServiceImpl implements BoardService {

    @Autowired
    private BoardMapper boardMapper;

    @Override
    public List<BoardDto> selectBoardList() throws Exception {
        return boardMapper.selectBoardList();
    }
}

 

 

2. Controller 생성

package com.example.board.board.controller;

import com.example.board.board.dto.BoardDto;
import com.example.board.board.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class BoardController {

    @Autowired
    private BoardService boardService;

	@RequestMapping(value="/board", method=RequestMethod.GET)
    public ModelAndView openBoardList() throws Exception{
        ModelAndView mv = new ModelAndView("/board/boardList");

        List<BoardDto> list = boardService.selectBoardList();
        mv.addObject("list", list);

        return mv;
    }

}

 

 

3. View 작성하기

  • resources/teplates 밑에 board 폴더를 생성하고 그 안에 boardList.html 파일을 생성한다.
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>board</title>
    <link rel="stylesheet" th:href="@{/css/style.css}"/>
</head>
<body>
<div class="container">
    <h2>게시글 목록</h2>
    <table class="board_list">
        <colgroup>
            <col width="15%"/>
            <col width="*"/>
            <col width="15%"/>
            <col width="20%"/>
        </colgroup>
        <thead>
        <tr>
            <th scope="col">글번호</th>
            <th scope="col">제목</th>
            <th scope="col">조회수</th>
            <th scope="col">작성일</th>
        </tr>
        </thead>
        <tbody>
        <tr th:if="${#lists.size(list)} > 0" th:each="list : ${list}">
            <td th:text="${list.boardIdx}"></td>
            <!-- 여기 -->
            <td class="title"><a href="/board/" th:attrappend="href=${list.boardIdx}" th:text="${list.title}"></a></td>
            <td th:text="${list.hitCnt}"></td>
            <td th:text="${list.createdDatetime}"></td>
        </tr>
        <tr th:unless="${#lists.size(list)} > 0">
            <td colspan="4">조회된 결과가 없습니다.</td>
        </tr>
        </tbody>
    </table>
    <!-- 여기 -->
    <a href="/board/write" class="btn">글 쓰기</a>
</div>
</body>
</html>

 

 

4. 결과 보기

<css를 추가하지 않은 화면>

<css를 입힌 화면>

 

<데이터를 하나 추가한 모습>

INSERT INTO t_board
(
    title,
    contents,
    creator_id,
    created_datetime
)
VALUES
(
    '첫번째 게시글',
    '내용이닷!',
    'admin',
    NOW()
);

 

 

 

 

참고:

- [스프링 부트 시작하기: 차근차근 따라 하는 단계별 실습]

반응형
Comments