글목록
boardListForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시물 목록</title>
<style type="text/css">
body {
background-color: #FFE2FA;
font-family: 'Arial', sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 30vh;
flex-direction: column;
}
table {
border-collapse: collapse;
border-radius: 10px;
background-color: white;
width: 800px;
padding: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
margin: 0 auto;
}
th, td {
padding: 10px;
border: 1px solid #CCC;
text-align: center;
font-size: 14px;
}
th {
background-color: #F2F2F2;
color: #333;
font-size: 16px;
}
td {
color: #333;
}
input[type="button"] {
background-color: #FF9ADB;
border: none;
font-size: 14px;
padding: 8px 12px;
border-radius: 5px;
cursor: pointer;
color: white;
transition: background-color 0.3s ease;
margin: 10px;
}
input[type="button"]:hover {
background-color: #FF70C0;
}
img {
margin-bottom: 20px;
cursor: pointer;
display: block;
}
</style>
</head>
<body>
<img src="../image/free-icon-love-4096198.png" alt="홈" width="60" height="60" onclick="location.href='../index.jsp'" />
<table>
<thead>
<tr>
<th>글번호</th>
<th>제목</th>
<th>작성자</th>
<th>작성일</th>
<th>조회수</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'get',
url: '../board/boardList.jsp',
dataType: 'json',
success: function(data){
console.log(data);
$.each(data, function(index, item) {
console.log(data);
let row =
'<tr>' +
'<td>' + item.seq + '</td>' +
'<td>' + item.subject + '</td>' +
'<td>' + item.name + '</td>' +
'<td>' + item.logtime + '</td>' +
'<td>' + item.hit + '</td>' +
'</tr>';
document.querySelector('tbody').insertAdjacentHTML('beforeend', row);
});
},
error: function(e){
console.log(e);
}
});
});
</script>
</body>
</html>
boardList.jsp
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="board.bean.BoardDTO"%>
<%@page import="board.dao.BoardDAO"%>
<%@ page import="java.util.List" %>
<%@ page import="org.json.JSONArray" %>
<%@ page import="org.json.JSONObject" %>
<%@page import="java.text.SimpleDateFormat"%>
<%
BoardDAO boardDAO = BoardDAO.getInstance();
List<BoardDTO> list = boardDAO.boardList();
// JSON 배열 생성
JSONArray jsonArray = new JSONArray();
// 날짜 포맷팅
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
for (BoardDTO boardDTO : list) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("seq", boardDTO.getSeq());
jsonObject.put("subject", boardDTO.getSubject());
jsonObject.put("name", boardDTO.getName());
// 날짜 포맷팅
String logtime = sdf.format(boardDTO.getLogtime());
jsonObject.put("logtime", logtime);
jsonObject.put("hit", boardDTO.getHit());
// JSON 배열에 추가
jsonArray.put(jsonObject);
}
// JSON 배열을 문자열로 변환
String json = jsonArray.toString();
System.out.println(json);
%>
<%= json %>
BoardDAO.java
public List<BoardDTO> boardList(){
List<BoardDTO> boardList = new ArrayList<>();
String sql = "select * from board order by seq desc";
try {
con = ds.getConnection();
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
BoardDTO boardDTO = new BoardDTO();
boardDTO.setSeq(rs.getInt("seq"));
boardDTO.setSubject(rs.getString("subject"));
boardDTO.setName(rs.getString("name"));
boardDTO.setLogtime(rs.getDate("logtime"));
boardDTO.setHit(rs.getInt("hit"));
boardList.add(boardDTO);
}
} catch (SQLException e) {
e.printStackTrace();
}
return boardList;
}
페이징 처리
index.jsp ?pg=1 추가하기 ----> boardList.jsp
<body>
<h2>메인화면</h2>
<div class="nav-bar">
<% if(session.getAttribute("memId") == null){ %>
<h3><a href="./member/memberWriteForm.jsp">회원가입</a></h3>
<h3><a href="./member/memberLoginForm.jsp">로그인</a></h3>
<% } else { %>
<h3><a href="./member/memberLogout.jsp">로그아웃</a></h3>
<h3><a href="./member/memberUpdateForm.jsp">회원정보수정</a></h3>
<h3><a href="./board/boardWriteForm.jsp">글쓰기</a></h3>
<% } %>
<h3><a href="./board/boardList.jsp?pg=1">목록</a></h3>
</div>
</body>
board.js ?pg=1 추가하기 ---> boardList.jsp
// 유효성 검사를 모두 통과한 경우에만 ajax 요청 실행
if (isValid) {
$.ajax({
type: 'post',
url: '../board/boardWrite.jsp',
data: $('#boardWriteForm').serialize(),
success: function() {
alert('게시물 작성에 성공하였습니다!');
window.location.href = "../board/boardList.jsp?pg=1";
},
error: function(e) {
console.log(e);
}
});
}
boardList.jsp에서 페이지값 먼저 얻어내야한다.
boardList.jsp
int pg = Integer.parseInt(request.getParameter("pg"));
//1페이지당 5개씩
select * from board order by seq desc;
글번호 제목 그룹번호 글순서
seq subject ref step
10 컴퓨터 10 0
11 과일(원글) 11 0
12 사과(답글) 11 1
원글 -- 원글의 ref는 seq와 똑같이 들어가면 된다.
답글의 ref는 내가 갖고있는 글의 답이므로 원글의 ref와 똑같이 잡아줘야한다.
답글
원글의 step은 0이라면 답글의 step은 원글 + 1이 된다.
select할 때 순서가 이렇게 되어야한다. 답글은 원글 밑으로 와야한다.
과일
사과
컴퓨터
우리가 select해서 가져올 때 seq로 내림차순해라 하면 사과 과일 컴퓨터 이런식으로 가져와지게 된다.
글번호 제목 그룹번호 글순서
seq subject ref step
10 컴퓨터(원글) 10 0
11 과일(원글) 11 0
12 사과(답글) 11 1
13 키보드(답글) 10 1
14 부사(답글) 11 2
과일
사과
부사
컴퓨터
키보드
select * from board order by ref desc, step asc
11 0 -- 과일
11 1 -- 사과
11 2 -- 부사
10 0 -- 컴퓨터
10 1 -- 키보드
select rownum rn, tt.* from
(select * from board order by ref desc, step asc) tt;
select* from
(select rownum rn, tt.* from
(select * from board order by ref desc, step asc) tt)
where rn>=1 and rn<=5;
select* from
(select rownum rn, tt.* from
(select * from board order by ref desc, step asc) tt)
where rn>=6 and rn<=10;
startNum endNum
pg = 1 rn>=1 and rn<=5
pg = 2 rn>=6 and rn<=10
pg = 3 rn>=11 and rn<=15
boardList.jsp
int pg = Integer.parseInt(request.getParameter("pg"));
//1페이지당 5개씩
int endNum = pg * 5;
int startNum = endNum - 4;
BoardDAO boardDAO = BoardDAO.getInstance();
List<BoardDTO> list = boardDAO.boardList(startNum, endNum);
BoardDAO.java
public List<BoardDTO> boardList(int startNum, int endNum){
List<BoardDTO> list = new ArrayList<>();
String sql = """
select* from
(select rownum rn, tt.* from
(select * from board order by ref desc, step asc) tt)
where rn>=? and rn<=?
""";
try {
con = ds.getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, startNum);
pstmt.setInt(2, endNum);
rs = pstmt.executeQuery();
while(rs.next()) {
BoardDTO boardDTO = new BoardDTO();
boardDTO.setSeq(rs.getInt("seq"));
boardDTO.setId(rs.getString("id"));
boardDTO.setName(rs.getString("name"));
boardDTO.setEmail(rs.getString("email"));
boardDTO.setSubject(rs.getString("subject"));
boardDTO.setContent(rs.getString("content"));
boardDTO.setRef(rs.getInt("ref"));
boardDTO.setLev(rs.getInt("lev"));
boardDTO.setStep(rs.getInt("step"));
boardDTO.setPseq(rs.getInt("pseq"));
boardDTO.setReply(rs.getInt("reply"));
boardDTO.setHit(rs.getInt("hit"));
boardDTO.setLogtime(rs.getDate("logtime"));
list.add(boardDTO);
}
} catch (SQLException e) {
e.printStackTrace();
list = null;
}finally {
try {
if(rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
try 부분에서 잘못되면 list를 null로 초기화하는 작업을 한다 !
boardList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="board.bean.BoardDTO"%>
<%@page import="board.dao.BoardDAO"%>
<%@ page import="java.util.List" %>
<%
int pg = Integer.parseInt(request.getParameter("pg"));
//1페이지당 5개씩
int endNum = pg * 5;
int startNum = endNum - 4;
BoardDAO boardDAO = BoardDAO.getInstance();
List<BoardDTO> list = boardDAO.boardList(startNum, endNum);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시물 목록</title>
<style type="text/css">
body {
background-color: #FFE2FA;
font-family: 'Arial', sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 70vh;
flex-direction: column;
}
table {
border-collapse: collapse;
border-radius: 10px;
background-color: white;
width: 800px;
padding: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
margin: 0 auto;
}
th, td {
padding: 10px;
border: 1px solid #CCC;
text-align: center;
font-size: 14px;
}
th {
background-color: #F2F2F2;
color: #333;
font-size: 16px;
}
td {
color: #333;
}
input[type="button"] {
background-color: #FF9ADB;
border: none;
font-size: 14px;
padding: 8px 12px;
border-radius: 5px;
cursor: pointer;
color: white;
transition: background-color 0.3s ease;
margin: 10px;
}
input[type="button"]:hover {
background-color: #FF70C0;
}
img {
margin-bottom: 20px;
cursor: pointer;
display: block;
}
</style>
</head>
<body>
<img src="../image/free-icon-love-4096198.png" alt="홈" width="60" height="60" onclick="location.href='../index.jsp'" />
<table>
<thead>
<tr>
<th>글번호</th>
<th>제목</th>
<th>작성자</th>
<th>작성일</th>
<th>조회수</th>
</tr>
</thead>
<tbody>
<% if(list != null) { %>
<% for(BoardDTO boardDTO : list) { %>
<tr>
<td><%=boardDTO.getSeq() %></td>
<td><%=boardDTO.getSubject() %></td>
<td><%=boardDTO.getName() %></td>
<td><%=boardDTO.getLogtime() %></td>
<td><%=boardDTO.getHit() %></td>
</tr>
<%} %>
<%} %>
</tbody>
</table>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.7.1.min.js"></script>
</body>
</html>
board.bean.BoardPaging.java
[ 1 ] [ 2 ] [ 3 ] [ 다음 ]
[ 이전 ] [ 4 ] [ 5 ] [ 6 ] [ 다음 ]
[ 이전 ] [ 7 ] [ 8 ]
startPage endPage
BoardPaging.java
package board.bean;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class BoardPaging {
private int currentPage; //현재페이지
private int pageBlock; //[이전][1][2][3][다음]
private int pageSize; //1페이지당 5개씩
private int totalA; //총글수
private StringBuffer pagingHTML;
public void makePagingHTML() {
pagingHTML = new StringBuffer();
int totalP = (totalA + pageSize-1) / pageSize;
int startPage = (currentPage-1) / pageBlock * pageBlock + 1;
int endPage = startPage + pageBlock - 1;
if(endPage > totalP)
endPage = totalP;
if(startPage != 1)
pagingHTML.append("<span id='paging' onclick='boardPaging(" + (startPage-1) + ")'>이전</span>");
for(int i=startPage; i<=endPage; i++) {
if(i == currentPage)
pagingHTML.append("<span id='currentPaging' onclick='boardPaging(" + i + ")'>" + i + "</span>");
else
pagingHTML.append("<span id='paging' onclick='boardPaging(" + i + ")'>" + i + "</span>");
}//for
if(endPage < totalP)
pagingHTML.append("<span id='paging' onclick='boardPaging(" + (endPage+1) + ")'>다음</span>");
}
}
boardList.jsp
//페이징 처리
int totalA = boardDAO.getTotalA();
boardDAO.java
public int getTotalA() {
int totalA = 0;
String sql = "select count(*) from board";
try {
con = ds.getConnection();
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
rs.next();
totalA = rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return totalA;
}
boardList.jsp
BoardPaging boardPaging = new BoardPaging();
boardPaging.setCurrentPage(pg);
boardPaging.setPageBlock(3);
boardPaging.setPageSize(5);
boardPaging.setTotalA(totalA);
boardPaging.makePagingHTML();
<table>
<thead>
<tr>
<th>글번호</th>
<th>제목</th>
<th>작성자</th>
<th>작성일</th>
<th>조회수</th>
</tr>
</thead>
<tbody>
<% if(list != null) { %>
<% for(BoardDTO boardDTO : list) { %>
<tr>
<td><%=boardDTO.getSeq() %></td>
<td><%=boardDTO.getSubject() %></td>
<td><%=boardDTO.getName() %></td>
<td><%=boardDTO.getLogtime() %></td>
<td><%=boardDTO.getHit() %></td>
</tr>
<%} %>
<%} %>
</tbody>
</table>
<div><%=boardPaging.getPagingHTML() %></div>
<div style="border: 1px solid red;">
<%=boardPaging.getPagingHTML() %>
</div>
boardList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="board.bean.BoardDTO"%>
<%@page import="board.bean.BoardPaging"%>
<%@page import="board.dao.BoardDAO"%>
<%@ page import="java.util.List" %>
<%
int pg = Integer.parseInt(request.getParameter("pg"));
//1페이지당 5개씩
int endNum = pg * 5;
int startNum = endNum - 4;
//DB
BoardDAO boardDAO = BoardDAO.getInstance();
List<BoardDTO> list = boardDAO.boardList(startNum, endNum);
//페이징 처리
int totalA = boardDAO.getTotalA();
BoardPaging boardPaging = new BoardPaging();
boardPaging.setCurrentPage(pg);
boardPaging.setPageBlock(3);
boardPaging.setPageSize(5);
boardPaging.setTotalA(totalA);
boardPaging.makePagingHTML();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시물 목록</title>
<style type="text/css">
body {
background-color: #FFE2FA;
font-family: 'Arial', sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 70vh;
flex-direction: column;
}
table {
border-collapse: collapse;
border-radius: 10px;
background-color: white;
width: 800px;
padding: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
margin: 0 auto;
}
th, td {
padding: 10px;
border: 1px solid #CCC;
text-align: center;
font-size: 14px;
}
th {
background-color: #F2F2F2;
color: #333;
font-size: 16px;
}
td {
color: #333;
}
#currentPaging {
color: red;
font-size: 15px;
padding: 5px 8px;
margin: 3px;
}
#paging {
color: black;
font-size: 15px;
padding: 5px 8px;
margin: 3px;
}
span:hover {
text-decoration: underline;
cursor: pointer;
}
img {
margin-bottom: 20px;
cursor: pointer;
display: block;
}
</style>
</head>
<body>
<img src="../image/free-icon-love-4096198.png" alt="홈" width="60" height="60" onclick="location.href='../index.jsp'" />
<table>
<thead>
<tr>
<th>글번호</th>
<th>제목</th>
<th>작성자</th>
<th>작성일</th>
<th>조회수</th>
</tr>
</thead>
<tbody>
<% if(list != null) { %>
<% for(BoardDTO boardDTO : list) { %>
<tr>
<td><%=boardDTO.getSeq() %></td>
<td><%=boardDTO.getSubject() %></td>
<td><%=boardDTO.getName() %></td>
<td><%=boardDTO.getLogtime() %></td>
<td><%=boardDTO.getHit() %></td>
</tr>
<%} %>
<%} %>
</tbody>
</table>
<div style="margin-top: 15px;">
<%=boardPaging.getPagingHTML() %>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.7.1.min.js"></script>
</body>
</html>
<script type="text/javascript">
function boardPaging(pg){
location.href = "boardList2.jsp?pg=" + pg;
}
</script>
'HOMEWORK' 카테고리의 다른 글
DAY 51 - MVC HOMEWORK( 2024.09.12 ) (1) | 2024.09.12 |
---|---|
DAY49 - MyBatis HOMEWORK (2024.09.10) (0) | 2024.09.10 |
DAY 45 - JSP 미니프로젝트(member) HOMEWORK - 중복체크 / 회원가입 (2024.09.04) (0) | 2024.09.04 |
DAY 43 - Servlet HOMEWORK (2024.09.02) (6) | 2024.09.02 |
DAY 33 - JS HOMEWORK - 덧셈문제 (2024.08.19) (0) | 2024.08.22 |