JSP 게시판 만들기(1)
이전 로그인 만들기에 이어 추가로 게시판을 만들어 볼 것이다.
[로그인 만들기 참고]
Java Beans 활용하여 로그인 만들기(2)
지난 시간에 이어 이번 시간에는 DB와 연동하여 Java Beans 를 활용한 로그인 로직을 만들어 볼 것이다. 먼저 로그인 로직에서 사용될 DTO, DAO 객체와 Dbconn.java 파일을 생성하여 작성한다. 기존에는 DB
bluechanyeong.tistory.com
아래와 같이 테이블을 DB에 추가한다.
tb_board(게시판 테이블)
-- 게시판 테이블
-- 글번호, 글쓴이(아이디), 제목, 내용, 날짜, 조회수, 좋아요
create table tb_board(
b_idx bigint auto_increment primary key,
b_userid varchar(20) not null,
b_title varchar(200) not null,
b_content varchar(2000) not null,
b_regdate datetime default now(),
b_hit int default 0,
b_like int default 0
);
tb_reply(게시판 댓글 테이블)
-- 게시판 댓글 테이블
-- 댓글 번호, 댓글 작성아이디, 내용, 등록날짜, 게시글번호
create table tb_reply(
r_idx bigint auto_increment primary key,
r_userid varchar(20) not null,
r_content varchar(500) not null,
r_regdate datetime default now(),
r_boardidx bigint not null
);
이제 게시글에 필요한 JSP 파일을 모아놓기 위한 board 폴더를 생성하여 아래와 같이 구성한다.
게시판 리스트 페이지(list.jsp) 작성
<%@page import="java.util.Date"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.koreait.db.Dbconn"%>
<%@ page import="java.sql.*"%>
<%
if(session.getAttribute("userid") == null){
%>
<script>
alert('로그인 후 이용하세요');
location.href='../login.jsp';
</script>
<%
}else{
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>커뮤니티 - 리스트</title>
</head>
<body>
<h2>커뮤니티 - 리스트</h2>
<%
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "";
int totalCount = 0;
int pagePerCount = 10;
int start = 0;
String pagenum = request.getParameter("pagenum") == null ? "" : request.getParameter("pagenum");
if(!pagenum.equals("")){
start = (Integer.parseInt(pagenum)-1) * pagePerCount;
}
try {
conn = Dbconn.getConnection();
sql = "select count(b_idx) as total from tb_board;";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()){
totalCount = rs.getInt("total");
}
sql = "select b_idx, b_title, b_userid, b_hit, b_regdate, b_like from tb_board order by b_idx DESC limit ?, ?;";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, start);
pstmt.setInt(2, pagePerCount);
rs = pstmt.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
%>
<p>게시글 : <%=totalCount%>개</p>
<table border="1" width="800">
<tr>
<th width="50">번호</th>
<th width="300">제목</th>
<th width="100">글쓴이</th>
<th width="75">조회수</th>
<th width="200">날짜</th>
<th width="75">좋아요</th>
</tr>
<%
while(rs.next()){
String b_idx = rs.getString("b_idx");
String b_title = rs.getString("b_title");
String b_userid = rs.getString("b_userid");
int b_hit = rs.getInt("b_hit");
String b_regdate = rs.getString("b_regdate").substring(0, 10);
int b_like = rs.getInt("b_like");
ResultSet rs1 = null;
sql = "select count(r_idx) as replycount from tb_reply where r_boardidx=?;";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, b_idx);
rs1 = pstmt.executeQuery();
int replycnt = 0;
String replycnt_str ="";
if(rs1.next()){
replycnt = rs1.getInt("replycount");
if(replycnt > 0){
replycnt_str = "[" + replycnt + "]";
}
}
Date from = new Date();
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd");
String to = fm.format(from);
String newDate_str = "";
if(to.equals(b_regdate)){
newDate_str = "<img src='./new.png' alt='새글' width='18'>";
}
%>
<tr align="center">
<th><%=b_idx%></th>
<th><a href="./view.jsp?b_idx=<%=b_idx%>"><%=b_title%> <%=newDate_str%></a><%=replycnt_str%></th>
<th><%=b_userid%></th>
<th><%=b_hit%></th>
<th><%=b_regdate%></th>
<th><%=b_like%></th>
</tr>
<%
}
int pageNums = (int)Math.ceil((double)totalCount/(double)pagePerCount);
%>
<tr>
<td colspan="6"><center>
<%
for(int i = 0 ; i < pageNums; i++){
%>
<a href='./list.jsp?pagenum=<%=(i+1)%>'><%=(i+1)%></a>
<%
}
%>
</center></td>
</tr>
</table>
<p><input type="button" value="글쓰기" onclick="location.href='./write.jsp'">
<input type="button" value="메인" onclick="location.href='../login.jsp'">
</p>
</body>
</html>
<%
}
%>
list.jsp 의 코드 구성중 페이징 처리를 자세히 살펴보자.
// 생략
<%
}
int pageNums = (int)Math.ceil((double)totalCount/(double)pagePerCount);
%>
<tr>
<td colspan="6"><center>
<%
for(int i = 0 ; i < pageNums; i++){
%>
<a href='./list.jsp?pagenum=<%=(i+1)%>'><%=(i+1)%></a>
<%
}
%>
// 생략
이 부분은 페이징을 하기 위한 부분으로 한 페이지에 10개의 게시글(pagePerCount)만 표현하게되고 이후 초과한 게시글들은 페이징 처리가 되어 다음장을 눌렀을 때 보여지게된다.
만약 13개의 게시글이 있다면 페이징 번호는 1번과 2번, 총2개 생성되고 페이징 버튼을 클릭 시 a태그 url를 통해 pagenum의 파라미터에 번호를 담고 보내지게된다.
String pagenum = request.getParameter("pagenum") == null ? "" : request.getParameter("pagenum");
if(!pagenum.equals("")){
start = (Integer.parseInt(pagenum)-1) * pagePerCount;
}
위에서 작성된 코드에서 만약 pagenum이 null, 즉 처음 페이지에 들어오면 글번호 내림차순 기준 10개의 게시글이 보이게된다.
만약 pagenum이 null이 아닌 페이징 a태그를 통해 파라미터의 값을 갖고있다면 (pagenum-1) * 10인 글번호부터 내림차순을 10개의 게시글을 list에 출력하게된다.
다음시간에는 글쓰기 기능을 구현하여 오늘 만든 리스트에 표시되는지 확인해보자.