45일-4일 Tag Spring Framework 게시판 만들기 ShowOne 페이지 만들기

showAll.jsp 수정

태그를 사용하여 링크를 이동하도록 변경 에 추가

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <c:forEach items="${list}" var="item">
        <a href="http://oneul-coding.board/showOne/${item.id}">${item.id} ${item.title} ${item.entryDate}</a> <br>
    </c:forEach>
</body>
</html>

BoardService.java에 selectOne 추가

public BoardDTO selectOne(int id){
        BoardDTO b = null;

        String query = "SELECT * FROM `board` WHERE `id` = ?";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(query);
            preparedStatement.setInt(1, id);

            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()){
                b = new BoardDTO();
                b.setId(resultSet.getInt("id"));
                b.setTitle(resultSet.getString("title"));
                b.setContent(resultSet.getString("content"));
                b.setWriterId(resultSet.getInt("writerId"));
                b.setEntryDate(new Date(resultSet.getTimestamp("entry_date").getTime()));
                b.setModifyDate(new Date(resultSet.getTimestamp("modify_date").getTime()));

            }

            resultSet.close();
            preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return b;
    }

추가된 BoardService.java

package com.bit.spring.service;

import com.bit.spring.connector.MySqlConnector;
import com.bit.spring.model.BoardDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;

@Service
public class BoardService {
    private final int PAGE_SIZE = 15;
    private Connection connection;
    @Autowired
    public BoardService(MySqlConnector mySqlConnector){
        connection = mySqlConnector.makeConnection();
    }

    //특정 페이지 출력하기
    public ArrayList<BoardDTO> selectAll(int pageNo){
        ArrayList<BoardDTO> list = new ArrayList<>();
        String query = "SELECT * FROM `board` ORDER BY `id` LIMIT ?, ?";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(query);
            preparedStatement.setInt(1, (pageNo - 1) * PAGE_SIZE);
            preparedStatement.setInt(2, PAGE_SIZE);

            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()){
                BoardDTO boardDTO = new BoardDTO();
                boardDTO.setId(resultSet.getInt("id"));
                boardDTO.setTitle(resultSet.getString("title"));
                boardDTO.setContent(resultSet.getString("content"));
                boardDTO.setWriterId(resultSet.getInt("writerId"));
                boardDTO.setEntryDate(new Date(resultSet.getTimestamp("entry_date").getTime()));
                boardDTO.setModifyDate(new Date(resultSet.getTimestamp("modify_date").getTime()));

                list.add(boardDTO);
            }

            resultSet.close();
            preparedStatement.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }


        return list;
    }

    public BoardDTO selectOne(int id){
        BoardDTO b = null;

        String query = "SELECT * FROM `board` WHERE `id` = ?";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(query);
            preparedStatement.setInt(1, id);

            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()){
                b = new BoardDTO();
                b.setId(resultSet.getInt("id"));
                b.setTitle(resultSet.getString("title"));
                b.setContent(resultSet.getString("content"));
                b.setWriterId(resultSet.getInt("writerId"));
                b.setEntryDate(new Date(resultSet.getTimestamp("entry_date").getTime()));
                b.setModifyDate(new Date(resultSet.getTimestamp("modify_date").getTime()));

            }

            resultSet.close();
            preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return b;
    }
}

BoardController.java에 @GetMapping 추가

 @GetMapping("showOne/{id}")
    public String showOne(HttpSession session, RedirectAttributes redirectAttributes, Model model, @PathVariable int id){
        if (session.getAttribute("logIn") == null){
            redirectAttributes.addFlashAttribute("message", "다시 로그인해주세요.");
            return "redirect:/";
        }

        BoardDTO b = boardService.selectOnt(id);
        if (b == null){
            redirectAttributes.addFlashAttribute("message", "존재하지 않는 글 번호입니다.
"); return "redirect:/board/showAll/1"; } model.addAttribute("result", b); return "/board/showOne"; }

BoardController.java 추가

package com.bit.spring.controller;

import com.bit.spring.model.BoardDTO;
import com.bit.spring.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.time.chrono.MinguoDate;
import java.util.ArrayList;

@Controller
@RequestMapping("/board/")
public class BoardController {
    BoardService boardService;
    @Autowired
    public BoardController(BoardService boardService){
        this.boardService = boardService;
    }
    @GetMapping("showAll/{pageNo}")
    public String showAll(HttpSession session, RedirectAttributes redirectAttributes, Model model, @PathVariable int pageNo){
        if (session.getAttribute("logIn") == null){
            redirectAttributes.addFlashAttribute("message", "다시 로그인해주세요.");
            return "redirect:/";
        }

        ArrayList<BoardDTO> list = boardService.selectAll(pageNo);

        model.addAttribute("list", list);

        return "/board/showAll";
    }

    @GetMapping("showOne/{id}")
    public String showOne(HttpSession session, RedirectAttributes redirectAttributes, Model model, @PathVariable int id){
        if (session.getAttribute("logIn") == null){
            redirectAttributes.addFlashAttribute("message", "다시 로그인해주세요.");
            return "redirect:/";
        }

        BoardDTO b = boardService.selectOnt(id);
        if (b == null){
            redirectAttributes.addFlashAttribute("message", "존재하지 않는 글 번호입니다.
"); return "redirect:/board/showAll/1"; } model.addAttribute("result", b); return "/board/showOne"; } }

showOne.jsp 생성

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
글번호 : ${result.id} <br>
제목 : ${result.title} <br>
작성자 : ${result.writerId} <br>
작성일 : ${result.entryDate} <br>
수정일 : ${result.modifyDate} <br>
내용 ${result.content} <br>
</body>
</html>


결과