프로그래밍 공부

2025.02.25 MVC패턴 공부

3452 2025. 2. 25. 17:59

게시판 만들기

 

게시글 보기(Read)

 

1. menu.jsp에서 게시판 <a> 태그 클릭(뷰)

<li class ="nav-item"><a href = "BoardListAction?pageNum=1" class = "nav-link" >게시판</a></li>

 

2. Board_Read_Controller로 이동(컨트롤러)

//전처리

int pagenum = Integer.parseInt(req.getParameter("pageNum"));

int limit = 5;

int total_page;

컨트롤러 전처리

게시판 페이지번호(pagenum)과 한 번에 표시되는 게시글의 수(limit), 총 게시글 갯수(total_page)를 선언해준다.

 

//모델이동

BoardRepository br = BoardRepository.getInstance();

ArrayList<Board> boardlist = br.getAllList(pagenum, limit);

모델이동

BoardRepository br을 객체를 생성하고 boadlist ArrayList를 만들어서 br에 있는 getAllList()메서드를 실행하기 위해 pagenum과 limit 변수를 파라미터로 호출한다.

 

public ArrayList<Board> getAllList(int page, int limit){

//페이징 처리된 함수

 

int total_record = getListCount();

int start = (page - 1) * limit;

int index = start + 1;

 

ArrayList<Board> ab = new ArrayList<Board>();

try {

//데이터베이스 연결

conn = DBConnection.connection();

//쿼리작성 및 실행

String sql = "select * from Board";

pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

rs = pstmt.executeQuery();

// ResultSet --> DTO --> ArrayList<DTO>

while (rs.absolute(index)) {

Board board = new Board();

board.setNum(rs.getInt("num"));

board.setId(rs.getString("id"));

board.setName(rs.getString("name"));

board.setSubject(rs.getString("subject"));

board.setContent(rs.getString("content"));

board.setRegist_day(rs.getString("regist_day"));

board.setHit(rs.getInt("hit"));

board.setIp(rs.getString("ip"));

ab.add(board);

 

if (index < (start + limit) && index <= total_record)

index++;

else

break;

}

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

return ab;

모델

page와  limit를 받아서 호출되고

그 값을 이용해서 getListCount() 함수를 거쳐 total_record, start, index값을 정하고

ab ArrayList를 만들고 데이터베이스에 연결하여 쿼리를 실행함으로써 데이터베이스로 부터 ResultSet rs를 받아와 rs를 while 문으로 순회하면서 데이터베이스에 등록된 게시글의 번호, 작성자id, 이름, 제목, 내용등의 정보를 가져와서 board 객체에 담은 다음 board를 ab 어레이리스트에 담는다.

 

그후 if 문을 이용하여 한페이지에 글이 5개 이상이 되거나, 총 게시글의 수보다 인덱스의 값이 커지게 되면 더 이상 게시글을 불러오지 않고 while문을 종료한다.

 

그런후 어레이리스트 ab를 반환한다.

int total_record = br.getListCount();

 

if (total_record % limit == 0){

total_page =total_record/limit;

Math.floor(total_page);

}

else{

total_page =total_record/limit;

Math.floor(total_page);

total_page = total_page + 1;

}

모델에서 컨트롤러로 돌아온 후

 

총 게시글 수를 limit(5)로 나눴을 때 나머지가 0이면 페이지 수는 게시글/리미트의 값으로 한다.

 

나머지가 존재하면 총 페이지 +1의 값으로 한다.

 

이 말은 게시글이 5개, 10개등으로 딱 떨어지면 몫인 1페이지, 2페이지로 하고, 게시글의 수가 5로 나누어떨어지지 않으면 그래도 남은글들도 불러와야 하기 때문에 +1페이지를 해서 나머지도 불러온다는 의미이다.

 

//뷰이동

req.setAttribute("Total_Record", total_record);

req.setAttribute("Total_Page", total_page);

req.setAttribute("pageNum", pagenum);

req.setAttribute("list", boardlist);

RequestDispatcher ds = req.getRequestDispatcher("board/list.jsp");

ds.forward(req, resp);

컨트롤러에서 전처리와 모델 이동을 거쳐 값을 구했으니 뷰로 이동한다.

 

그 전에 컨트롤러에서 구했던 값들을 request에 넣고 RequestDispatcher forward를 이용해 파라미터를 가지고 페이지를 이동하게 된다.

 

 

3. list.jsp(뷰)

<%@ page contentType="text/html; charset=utf-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="java.util.*"%>

<%@ page import="dto.Board"%>

<%@ page session="false" %>

<%

//게시글 5개가 담겨있음

ArrayList<Board> boardList = (ArrayList<Board>) request.getAttribute("list");

 

int total_record = (Integer) request.getAttribute("Total_Record");

int pageNum =(Integer) request.getAttribute("pageNum");

int total_page=(Integer) request.getAttribute("Total_Page");

HttpSession session = request.getSession(false);

//String sessionId = (String) session.getAttribute("sessionId");

String sessionId =null;

if(session!=null){

sessionId = session.getId();

System.out.println("세션아이디값"+sessionId);

} else {

System.out.println("세션 아이디가 없습니다.");

}

 

%>

<html>

<head>

<link rel="stylesheet" href="./resources/css/bootstrap.min.css" />

<title>Board</title>

<script type="text/javascript">

function checkForm() {

let session_value="<%=sessionId%>";

console.log(session_value);

if (session_value=="null") {

alert("로그인 해주세요.");

return false;

}

 

location.href = "BoardWriteForm?id=<%=sessionId%>"

}

</script>

</head>

<body>

<div class="container py-4">

<jsp:include page="../menu.jsp" />

 

<div class="p-5 mb-4 bg-body-tertiary rounded-3">

<div class="container-fluid py-5">

<h1 class="display-5 fw-bold">게시판</h1>

<p class="col-md-8 fs-4">Board</p>

</div>

</div>

 

<div class="row align-items-md-stretch text-center">

<form action="<c:url value="./BoardListAction.do"/>" method="post">

 

 

<div class="text-end">

<span class="badge text-bg-success">전체 <%=total_record%></span>

</div>

 

<div style="padding-top: 20px">

<table class="table table-hover text-center">

<tr>

<th>번호</th>

<th>제목</th>

<th>작성일</th>

<th>조회</th>

<th>글쓴이</th>

</tr>

<%

 

for (int j = 0; j < boardList.size() ; j++){

 

Board notice = (Board) boardList.get(j);

%>

<tr>

<td><%=notice.getNum()%></td>

<td><a href="BoardViewAction?num=<%=notice.getNum()%>&pageNum=<%=pageNum%>"><%=notice.getSubject()%></a></td>

<td><%=notice.getRegist_day()%></td>

<td><%=notice.getHit()%></td>

<td><%=notice.getName()%></td>

</tr>

<%

}

%>

</table>

</div>

<div align="center">

<% for(int i=1; i<=total_page;i++){ %>

<a href="BoardListAction?pageNum=<%=i%>">

<%if(pageNum==i){ %>

<font color='FF0000'><b> [<%=i %>]</b></font>

<%

}

else

{

%>

<font color='000000'> [<%=i %>]</font>

<%} %>

</a>

<%} %>

</div>

 

<div class="py-3" align="right">

<a href="#" onclick="checkForm(); return false;" class="btn btn-primary">&laquo;글쓰기</a>

</div>

<div align="left">

<select name="items" class="txt">

<option value="subject">제목에서</option>

<option value="content">본문에서</option>

<option value="name">글쓴이에서</option>

</select> <input name="text" type="text" /> <input type="submit" id="btnAdd" class="btn btn-primary " value="검색 " />

</div>

 

</form>

</div>

<jsp:include page="../footer.jsp" />

</div>

 

</body>

</html>

 

최종적으로 뷰에서는 컨트롤러에서 가져온 값들을 바탕으로 게시글의 갯수, 한페이지당 불러올 게시글 수 등을 파악하고 커스터머에게 불러온 게시글과 페이징처리를 보여준다.

 


 

게시글 작성하기(Create)

 

1. list.jsp에서 글쓰기 버튼 클릭 →  js의 checkForm()메서드 발생(뷰)

<a href="#" onclick="checkForm(); return false;" class="btn btn-primary">&laquo;글쓰기</a>

<script type="text/javascript">

function checkForm() {

let session_value="<%=sessionId%>";

console.log(session_value);

if (session_value=="null") {

alert("로그인 해주세요.");

return false;

}

 

location.href = "BoardWriteForm?id=<%=sessionId%>"

}

</script>

글쓰기 버튼을 누르면서 checkForm() 메서드가 실행되면서 로그인 상태를 확인하기 위해 세션이 존재하는지 확인하고 세션이 존재하지 않을때(=비로그인상태) "로그인 해주세요" 라는 경고창을 출력하고, 세션이 있는 상태(=로그인상태)에서는 BoardWriteForm을 호출하게 된다.

 

2. Board_Create_Controller 이동 (컨트롤러)

@WebServlet("/BoardWriteForm")

public class Board_Create_Controller extends HttpServlet{

 

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

RequestDispatcher rd = req.getRequestDispatcher("board/writeForm.jsp");

rd.forward(req, resp);

}

서블릿에 의해 호출된 컨트롤러에 의해 writeForm.jsp로 이동한다.

 

3. writeForm.jsp(뷰)

<%@ page contentType="text/html; charset=utf-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page session="false" %>

<%@ page import="dto.Member" %>

<%

HttpSession session = request.getSession(false);

Member mb = null;

if(session != null) {

mb = (Member)session.getAttribute("member");

}

 

%>

<html>

<head>

<link rel="stylesheet" href="./resources/css/bootstrap.min.css" />

<title>Board</title>

</head>

<script type="text/javascript">

function checkForm() {

if (!document.newWrite.name.value) {

alert("성명을 입력하세요.");

return false;

}

if (!document.newWrite.subject.value) {

alert("제목을 입력하세요.");

return false;

}

if (!document.newWrite.content.value) {

alert("내용을 입력하세요.");

return false;

}

}

</script>

<body>

<div class="container py-4">

<jsp:include page="../menu.jsp" />

 

<div class="p-5 mb-4 bg-body-tertiary rounded-3">

<div class="container-fluid py-5">

<h1 class="display-5 fw-bold">게시판</h1>

<p class="col-md-8 fs-4">Board</p>

</div>

</div>

 

<div class="row align-items-md-stretch text-center">

 

<form name="newWrite" action="BoardWriteForm" method="post" onsubmit="return checkForm()">

<input name="id" type="hidden" class="form-control"

value="${sessionId}">

<div class="mb-3 row">

<label class="col-sm-2 control-label" >성명</label>

<div class="col-sm-3">

<input name="name" type="text" class="form-control" value="<%=mb.getName()%>" placeholder="name" readonly>

</div>

</div>

<div class="mb-3 row">

<label class="col-sm-2 control-label" >제목</label>

<div class="col-sm-5">

 

<input name="subject" type="text" class="form-control" placeholder="subject">

</div>

</div>

<div class="mb-3 row">

<label class="col-sm-2 control-label" >내용</label>

<div class="col-sm-8">

<textarea name="content" cols="50" rows="5" class="form-control"placeholder="content"></textarea>

</div>

</div>

<div class="mb-3 row">

<div class="col-sm-offset-2 col-sm-10 ">

<input type="submit" class="btn btn-primary " value="등록 ">

<input type="reset" class="btn btn-primary " value="취소 ">

</div>

</div>

</form>

 

</div>

<jsp:include page="../footer.jsp" />

</div>

</body>

</html>

해당 폼에서는 게시글의 작성자 이름, 제목, 내용의 데이터를 입력받아 등록 버튼을 누르면 form태그 action에 등록된 Board_Create_Controller로 post방식으로 데이터를 가지고 이동한다.

 

4. Board_Create_Controller(컨트롤러)

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

HttpSession session = req.getSession(false);

Member mb = null;

if(session != null) {

mb = (Member)session.getAttribute("member");

}

String id = mb.getId();

String name = req.getParameter("name");

String subject = req.getParameter("subject");

String content = req.getParameter("content");

String regist_day = LocalDate.now().toString();

int hit = 0;

String ip = req.getRemoteAddr();

System.out.println(id);

System.out.println(name);

System.out.println(subject);

System.out.println(content);

System.out.println(regist_day);

System.out.println(ip);

 

Board bd = new Board();

bd.setId(id);

bd.setName(name);

bd.setSubject(subject);

bd.setContent(content);

bd.setRegist_day(regist_day);

bd.setIp(ip);

돌아온 컨트롤러에서는 폼에서 작성된 데이터를 기반으로 게시글을 DB에 삽입하기 위해 먼저 폼에서 입력한 데이터를 불러와 변수에 담고 다시 이를 옮기기 위해 bd 객체를 생성해 담아서 데이터를 옮길 준비를 한다.

//모델이동

BoardRepository br = BoardRepository.getInstance();

br.addBoard(bd);

준비된 bd 객체를 DB에 넣기 위해서 리퍼지토리를 싱글턴방식으로 생성한후 데이터를 집어넣은 bd를 파라미터로 리퍼지토리안의 DB에 저장하는 메서드에 넣는다.

 

5. BoardRepository(모델, DAO)

//Create

public void addBoard(Board bd) {

//데이터 베이스 연결

try {

conn = DBConnection.connection();

//쿼리 작성및 실행

String sql = "insert into Board values(?,?,?,?,?,?,?,?)";

pstmt = conn.prepareStatement(sql);

pstmt.setString(1, null);

pstmt.setString(2, bd.getId());

pstmt.setString(3, bd.getName());

pstmt.setString(4, bd.getSubject());

pstmt.setString(5, bd.getContent());

pstmt.setString(6, bd.getRegist_day());

pstmt.setInt(7, bd.getHit());

pstmt.setString(8, bd.getIp());

pstmt.executeUpdate();

//ResultSet

}

catch(Exception e) {}

}

파라미터로 전달받은 bd 객체를 addBoard() 메서드를 이용하여 DB와 연결, 쿼리작성 및 실행의 과정을 거쳐 DB에 삽입되게 된다.

 

5. Board_Create_Controller(컨트롤러)

resp.sendRedirect("BoardListAction?pageNum=1");

모든 작업을 마친후 컨트롤러로 돌아와 컨트롤러에 의해 게시글 목록페이지로 이동하게 된다.

 

'프로그래밍 공부' 카테고리의 다른 글

2025.02.27 SQL 공부  (0) 2025.02.27
2025.02.26 MVC패턴 공부  (0) 2025.02.26
2025.02.24 MVC패턴 공부  (0) 2025.02.24
2025.02.21 JSP 공부  (0) 2025.02.21
2025.02.20 JSP 공부  (0) 2025.02.20