본문 바로가기
JSP

221207 Board list출력

board_list

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>    
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>    
<%@include file="../include/header.jsp" %>

	<div class="container">
		<h3>My Web게시판</h3>

		<table class="table table-bordered">
			<thead>
				<tr>
					<th>순서</th>
					<th>글 번호</th>
					<th>작성자</th>
					<th>제목</th>
					<th>날짜</th>
					<th>조회수</th>
				</tr>
			</thead>

			
			<tbody>
				<c:forEach var="vo" items="${list }" varStatus="num">
				<tr>
					<td>${num.count }</td>
					<td>${vo.bno }</td>
					<td>${vo.writer }</td>
					<td><a href="board_content.board?bno=${vo.bno }" >${vo.title }</a></td>
					<td><fmt:formatDate value="${vo.regdate }" pattern="yyyy-MM-dd HH시 mm분 ss초"/></td>
					<td>${vo.hit }</td>
				</tr>
				</c:forEach>
			</tbody>
			
			<tbody>
				<tr>
					<td colspan="6" align="right">
						<form action="" class="form-inline" >
						  <div class="form-group">
						    <input type="text" name="search" placeholder="제목검색" class="form-control" >
						  	<input type="submit" value="검색" class="btn btn-default">
							<input type="button" value="글 작성" class="btn btn-default" onclick="location.href='board_write.board'">
						  </div>
						</form> 
					</td>
				</tr>
			</tbody>
		
		</table>
	</div>
	
<%@include file="../include/footer.jsp" %>

list에 출력하려면?

vo는 한 행만 가져오겠다는 뜻. list에 vo를 담아서 가져와야 한다

컨트롤러, 서비스, DAO에 생성한 메서드의 반환타입을 list로. 

글 목록에서 제목 등을 눌러서 이동할 때는 a태그를 사용한다
get방식의 '?변수명=값' 쿼리스트링으로 보낸다. 보낼 값이 더 필요하면 &로 묶음

 

시간은 format을 사용하여 형식을 바꾸어줘야 한다

 

varStatus="이름"을 통해 이름.count로 순서 출력

foramt을 통해 날짜의 출력형식 바꾸기. vo.regdate는 날짜 형식이다. 

 

a태그를 통해 제목을 누르면 그 글의 content로 넘어가도록.

 

 

 

 

board_write

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@include file="../include/header.jsp" %>

<div align="center" class="div_center">
	<h3>게시판 글 작성 페이지</h3>
	<hr>
	
	<form action="registForm.board" method="post">
		<table border="1" width="500">
			<tr>
				<td>작성자</td>
				<td>
					<input type="text" name="writer" size="10" required>
				</td>
			</tr>
			<tr>
				<td>글 제목</td>
				<td>
					<input type="text" name="title" required>
				</td>
			</tr>
			<tr>
				<td>글 내용</td>
				<td>
					<textarea rows="10" style="width: 95%;" name="content"></textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="작성 완료">
					&nbsp;&nbsp;
					<input type="button" value="목록" onclick="location.href='board_list.board'">         
				</td>
			</tr>
			
		</table>
	</form>
	
</div>

<%@include file="../include/footer.jsp" %>

write에 작성이 완료되면 action을 통해 컨트롤러로 이동

 

 

board_controller

package com.example.controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.board.model.BoardVO;
import com.example.board.service.BoardService;
import com.example.board.service.BoardServiceImpl;


@WebServlet("*.board")
public class BoardController extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}
	protected void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				//한글처리
				request.setCharacterEncoding("utf-8");
				
				//요청분기
				String uri = request.getRequestURI();
				String path = request.getContextPath();
				String command =uri.substring(path.length());
				
				System.out.println("요청경로:"+command);
				BoardService service=new BoardServiceImpl();
				
			if(command.equals("/board/board_write.board")) { //등록화면
				request.getRequestDispatcher("board_write.jsp").forward(request, response);
				
			}else if(command.equals("/board/board_list.board")) { //목록화면
				
				//조회메서드 - 
				ArrayList<BoardVO> list = service.getList(request, response);
				request.setAttribute("list",list);
				request.getRequestDispatcher("board_list.jsp").forward(request, response);
				
			}else if(command.equals("/board/board_content.board")) { //상세내용화면
				
				//조회한 글에 대한 정보 조회
				BoardVO vo = service.getContent(request, response);
				request.setAttribute("vo", vo);
				
				request.getRequestDispatcher("board_content.jsp").forward(request, response);
				
			}else if(command.equals("/board/board_modify.board")) { //수정화면
				//조회한 글에 대한 정보 조회 재활용!! 어차피 똑같은 내용
				BoardVO vo = service.getContent(request, response);
				request.setAttribute("vo", vo);
				
				request.getRequestDispatcher("board_modify.jsp").forward(request, response);
				
			}else if(command.equals("/board/registForm.board")) {//글 등록
				
				/*
				 * 1.service의 regist메서드로 연결
				 * 2.service에서 등록에 필요한 파라미터를 받습니다.
				 * 3.dao의 void regist()메서드를 생성하고 insert작업
				 * 4.insert이후 컨트롤러에서 리스트로 리다이렉트
				 */
				service.regist(request, response);
				response.sendRedirect("board_list.board");
				
			}else if(command.equals("/board/updateForm.board")) {
				
			}
		
	}

}

메서드를 통해 받은 list를 request를 통해 전달. 어차피 한번만 보이면 됨

수정화면에서도 작성했던 글을 받아올 것이기 때문에 content로 이동하는 if문의 내용물을 가져오면 됨

 

서비스에 메서드 추가

//BoardService에 메서드 추가

ArrayList<BoardVO> getList(HttpServletRequest request, HttpServletResponse response);//조회
	//public 생략해도 public. vo는 한 행만 가져오겠다는 뜻. list에 vo를 담아서 가져와야 한다
    
//BoardServiceImpl에 메서드 추가

public ArrayList<BoardVO> getList(HttpServletRequest request, HttpServletResponse response) {
			BoardDAO dao = BoardDAO.getInstance();
			ArrayList<BoardVO> list = dao.getList();
			
		return list;
	}

 

DAO에 메서드 추가

public ArrayList<BoardVO> getList() {
		ArrayList<BoardVO> list = new ArrayList<>();
		
		String sql="select * from board order by bno desc";//최신글 순서대로
		
		try {
			conn=DriverManager.getConnection(URL, UID, UPW);
			
			pstmt=conn.prepareStatement(sql);
			rs=pstmt.executeQuery();
			
			//rs결과를 list에 저장
			while(rs.next()) {
				int bno2=Integer.parseInt(rs.getString("bno"));
				String writer=rs.getString("writer");
				String title=rs.getString("title");
				String content = rs.getString("content");
				Timestamp date = rs.getTimestamp("regdate");
				int hit=Integer.parseInt(rs.getString("hit"));
				
				BoardVO vo = new BoardVO(bno2, writer, title, content, date, hit);
				list.add(vo);
				//반복문 맨 처음에 vo를 기본생성자로 생성하고 vo.setBno(rs.getInt("bno")) 방식으로 돌려도 된다
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(conn, pstmt, rs);
		}
		
		return list;
	}

최신글 순서대로 보이게 하기 위해 sql구문에서 order by를 desc로.

DB에서 한 행이 나올 때마다 그 정보들을 vo에 담아 list에 저장