4 분 소요

JSP로 게시판 만들기(1)


JSP를 활용하여 게시판를 만들어보자. 게시판은 로그인을 한 유저에 한에서 게시판을 볼 수 있게끔 만들것이다.

앞서 JSP day7와 JSP day8에서 로그인 로직와 연결되는 내용이다.

일단 JSP day7에서 만든 로그인 로직에 커뮤니티라는 버튼을 만들고 클릭시 게시판 페이지로 넘어가게 될 것이다.

<body>
	<h2>로그인</h2>
<%
	if(userid == null){
%>
	<form method="post" action="login_ok.jsp">
		<p>아이디 : <input type="text" name="userid"></p>
		<p>비밀번호 : <input type="password" name="userpw"></p>
		<p><input type="submit" value="로그인"></p>
		<p>회원이 아니신가요? <a href='./2_member.jsp'>회원가입</a></p>
	</form>
<%
	}else{
%>
	<h3><%=userid%>(<%=name%>)님 환영합니다.</h3>
	<p>
		<input type="button" value="커뮤니티" onclick="location.href='./board/list.jsp'">
		<input type="button" value="정보수정" onclick="location.href='info.jsp'">
		<input type="button" value="로그아웃" onclick="location.href='logout.jsp'">
	</p>
<%
	}
%>
</body>


게시판에서 필요한 sql문을 작성하고 JSP파일을 모아놓기 위해 board라는 폴더에 list.jsp 파일을 만들어놓고 거기서 시작해보자.

jsp11_1


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
);

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의 코드 구성을 자세히 보면,

<%
	if(session.getAttribute("userid") == null){
%>
<script>
	alert('로그인 후 이용하세요');
	location.href='../login.jsp';
</script> 
<%		
	}else{
%>

먼저 userid 세션의 유무를 확인하여 세션이 있을 경우 하단 코드를 정상 진행하게 되고 세션이 없는 경우 로그인 alert창과 함께 로그인 페이지로 넘어갈 것이다.


	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();
	}

위 코드는 mysql와 연동하고 윗 sql문은 게시글의 전체 갯수를 받아오고, 아래 sql문은 게시글의 데이터를 받아와 번호, 제목, 작성자, 조회수, 등록일, 좋아요의 정보를 limit 조건을 부여하여 0부터 10개의 행(row) 데이터만 가져오게 된다.


	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'>";
		}

게시글의 데이터를 받아와서 그 결과를 변수에 저장하고 그 안에서 게시글의 글번호를 통해 댓글의 갯수를 알아보는 sql문을 작성하고 그갯수를 html문으로 반환하게된다. 오늘 날짜와 게시글의 등록일이 같으면 새글인 것을 표시해주는 이미지도 넣을 예정이다.


%>	
		<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>		
<% 

그럼 위에서 받아온 데이터를 스크릿틀릿 문법을 이용하여 html에 표출해주게된다.


<% 
	}
	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개의 게시글만 표현하게되고 그 이후의 게시글들은 페이징 처리가 되어 다음장을 눌렀을 때 보여지게된다.

만약 13개의 게시글이 있다면 페이징 번호는 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에 출력하게된다.

일단 이렇게 만든 결과는 아래와 같고 다음시간에는 글쓰기를 하여 정말 오늘 작성한 jsp페이지에서 게시글이 나오는지 확인해보자.

jsp11_2

태그:

카테고리:

업데이트: