글쓰기버튼
package ch15;
import java.util.*;
public class BoardBean {
int num;
String name;
String subject;
String content;
int pos;
int ref;
int depth;
String regdate;
String pass;
String ip;
int count;
String filename;
int filesize;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getPos() {
return pos;
}
public void setPos(int pos) {
this.pos = pos;
}
public int getRef() {
return ref;
}
public void setRef(int ref) {
this.ref = ref;
}
public int getDepth() {
return depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public int getFilesize() {
return filesize;
}
public void setFilesize(int filesize) {
this.filesize = filesize;
}
}
package ch15;
public class BCommentBean {
int cnum;
int num;
String name;
String comment;
String regdate;
public int getCnum() {
return cnum;
}
public void setCnum(int cnum) {
this.cnum = cnum;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
}
package ch15;
import java.io.File;
import java.text.NumberFormat;
import javax.servlet.http.HttpServletRequest;
public class UtilMgr {
public static String replace(String str, String pattern, String replace) {
int s = 0, e = 0;
StringBuffer result = new StringBuffer();
while ((e = str.indexOf(pattern, s)) >= 0) {
result.append(str.substring(s, e));
result.append(replace);
s = e + pattern.length();
}
result.append(str.substring(s));
return result.toString();
}
public static void delete(String s) {
File file = new File(s);
if (file.isFile()) {
file.delete();
}
}
public static String con(String s) {
String str = null;
try {
str = new String(s.getBytes("8859_1"), "ksc5601");
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public static String monFormat(String b) {
String won;
double bb = Double.parseDouble(b);
won = NumberFormat.getIntegerInstance().format(bb);
return won;
}
public static String monFormat(int b) {
String won;
double bb = b;
won = NumberFormat.getIntegerInstance().format(bb);
return won;
}
public static String intFormat(int i) {
String s = String.valueOf(i);
return monFormat(s);
}
public static String getKBytes(int i) {
i = i/1000;
return monFormat(i);
}
public static int parseInt(HttpServletRequest request,
String name) {
return Integer.parseInt(request.getParameter(name));
}
}
package ch15;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.ssi.SSICommand;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
public class BoardMgr {
private DBConnectionMgr pool;
public static final String SAVEFOLDER = "C:/Jsp/myapp/src/main/webapp/ch15/fileupload/";
public static final String ENCODING = "UTF-8";
public static final int MAXSIZE = 1024*1024*20; //20MB
public BoardMgr() {
pool = DBConnectionMgr.getInstance();
}
// board Insert
public void insertBoard(HttpServletRequest req) {
Connection con = null;
PreparedStatement pstmt = null;
String sql = null;
try {
File dir = new File(SAVEFOLDER);
if(!dir.exists()/*존재하지 않으면*/) {
dir.mkdirs(); // mkdirs는 상위폴더가 없어도 생성
// mkdir은 상위폴더가 없으면 생성 불가
}
MultipartRequest multi =
new MultipartRequest(req, SAVEFOLDER, MAXSIZE, ENCODING
,new DefaultFileRenamePolicy());
String filename = null;
int filesize=0;
if(multi.getFilesystemName("filename")!=null) {
filename = multi.getFilesystemName("filename");
filesize = (int)multi.getFile("filename").length();
}
String content = multi.getParameter("content");
String contentType = multi.getParameter("contentType");
if(contentType.equals("TEXT")) {
content = UtilMgr.replace(content, "<", "%lt;");
}
int ref = getMaxNum()+1; //답변을 위한 ref값 설정
con = pool.getConnection();
sql = "insert tblBoard(name,content,subject,ref,pos,depth,";
sql += "regdate,pass,count,ip,filename,filesize)";
sql += "values(?, ?, ?, ?, 0, 0, now(), ?, 0, ?, ?, ?)";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, multi.getParameter("name"));
pstmt.setString(2, content);
pstmt.setString(3, multi.getParameter("subject"));
pstmt.setInt(4, ref);
pstmt.setString(5, multi.getParameter("pass"));
pstmt.setString(6, multi.getParameter("ip"));
pstmt.setString(7, filename);
pstmt.setInt(8, filesize);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt);
}
}
// board Max Num : num의 현재 최대값
public int getMaxNum() {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
int maxNum = 0;
try {
con = pool.getConnection();
sql = "select max(num) from tblBoard";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()) maxNum = rs.getInt(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return maxNum;
}
// board Total Count : 총 게시물 수
public int getTotalCount(String keyField, String keyWord) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
int totalCount = 0;
try {
con = pool.getConnection();
if(keyWord.trim().equals("")||keyWord==null) {
//검색이 아닌경우
sql = "select count(*) from tblBoard";
pstmt = con.prepareStatement(sql);
}else {
sql = "select count(*) from tblBoard where "
+ keyField + " like ? ";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, "%"+keyWord+"%");
}
rs = pstmt.executeQuery();
if(rs.next())
totalCount = rs.getInt(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return totalCount;
}
// board List : 검색기능, 페이징 및 블록
// limit 시작번호, 가져올 개수
public Vector<BoardBean> getBoardList(String keyField, String keyWord, int start, int cnt) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
Vector<BoardBean> vlist = new Vector<BoardBean>();
try {
con = pool.getConnection();
if(keyWord.trim().equals("")||keyWord==null) {
//검색이 아닌 경우
sql = "select * from tblBoard order by ref desc, pos limit ?, ?";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, start);
pstmt.setInt(2, cnt);
}else {
sql = "select * from tblBoard where "
+ keyField + " like ? order by ref desc, pos limit ?, ? ";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, "%"+keyWord+"%");
pstmt.setInt(2, start);
pstmt.setInt(3, cnt);
}
rs = pstmt.executeQuery();
while(rs.next()) {
BoardBean bean = new BoardBean();
bean.setNum(rs.getInt("num"));
bean.setName(rs.getString("name"));
bean.setSubject(rs.getString("subject"));
bean.setPos(rs.getInt("pos"));
bean.setRef(rs.getInt("ref"));
bean.setDepth(rs.getInt("depth"));
bean.setRegdate(rs.getString("regdate"));
bean.setCount(rs.getInt("count"));
bean.setFilename(rs.getString("filename"));
vlist.addElement(bean);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return vlist;
}
// board Get : 게시물 한개 읽어오기(13개의 컬럼 리턴){
// Count up : 조회수 증가
// board delete : 파일업로드 파일까지 삭제
// board Update : 파일업로드 수정
// board Reply : 답변글 입력
// board Reply Up : 답변글 위치값 수정
// 게시물 1000개 입력
public void post1000(){
Connection con = null;
PreparedStatement pstmt = null;
String sql = null;
try {
con = pool.getConnection();
sql = "insert tblBoard(name,content,subject,ref,pos,depth,regdate,pass,count,ip,filename,filesize)";
sql+="values('aaa', 'bbb', 'ccc', 0, 0, 0, now(), '1234',0, '127.0.0.1', null, 0);";
pstmt = con.prepareStatement(sql);
for (int i = 0; i < 1000; i++) {
pstmt.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt);
}
}
public static void main(String[] args) {
BoardMgr mgr = new BoardMgr();
mgr.post1000();
System.out.println("입력성공");
}
}
package ch15;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ch15/boardPost")
public class BoardPostServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BoardMgr mgr = new BoardMgr();
mgr.insertBoard(request);
response.sendRedirect("list.jsp");
}
}
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP Board</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#FFFFCC">
<div align="center">
<br/><br/>
<table width="600" cellpadding="3">
<tr>
<td bgcolor="84F399" height="25" align="center">글쓰기</td>
</tr>
</table>
<br/>
<form name="postFrm" method="post" action="boardPost"
enctype="multipart/form-data">
<table width="600" cellpadding="3" align="center">
<tr>
<td align=center>
<table align="center">
<tr>
<td width="10%">성 명</td>
<td width="90%">
<input name="name" size="10" maxlength="8" value="aaa"></td>
</tr>
<tr>
<td>제 목</td>
<td>
<input name="subject" size="50" maxlength="30" value="테스트"></td>
</tr>
<tr>
<td>내 용</td>
<td><textarea name="content" rows="10" cols="50">내용테스트</textarea></td>
</tr>
<tr>
<td>비밀 번호</td>
<td><input type="password" name="pass" size="15" maxlength="15" value="1234"></td>
</tr>
<tr>
<tr>
<td>파일찾기</td>
<td><input type="file" name="filename" size="50" maxlength="50"></td>
</tr>
<tr>
<td>내용타입</td>
<td> HTML<input type=radio name="contentType" value="HTTP" >
TEXT<input type=radio name="contentType" value="TEXT" checked>
</td>
</tr>
<tr>
<td colspan="2"><hr/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="등록">
<input type="reset" value="다시쓰기">
<input type="button" value="리스트" onClick="javascript:location.href='list.jsp'">
</td>
</tr>
</table>
</td>
</tr>
</table>
<input type="hidden" name="ip" value="<%=request.getRemoteAddr()%>">
</form>
</div>
</body>
</html>
<%@page import="ch15.BoardBean"%>
<%@page import="java.util.Vector"%>
<%@page import="ch15.UtilMgr"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<jsp:useBean id="mgr" class="ch15.BoardMgr"/>
<%
int totalRecord = 0; // 총 게시물 수
int numPerPage = 10; // 페이지 당 게시물 개수(5,10,20,30)
int pagePerBlock = 15; // 페이지 모음 블록
int totalPage = 0; // 총 페이지 개수
int totalBlock = 0; // 총 블럭 개수
int nowPage = 1; // 현재 페이지
int nowBlock = 1; // 현재 블록
// 요청된 numPerPage 처리
// 검색에 필요한 변수
String keyField = "", keyWord = "";
if(request.getParameter("keyWord")!=null){
keyField = request.getParameter("keyField");
keyWord = request.getParameter("keyWord");
}
// 검색 후에 다시 reset 요청
totalRecord = mgr.getTotalCount(keyField, keyWord);
//out.print(totalRecord);
if(request.getParameter("nowPage")!=null){
nowPage = UtilMgr.parseInt(request, "nowPage");
}
// sql문에 들어가는 start, cnt선언
int start = (nowPage*numPerPage)-numPerPage;
int cnt = numPerPage;
// 전체 페이지 개수
totalPage = (int)Math.ceil((double)totalRecord/numPerPage);
// 전체 블록 개수
totalBlock = (int)Math.ceil((double)totalRecord/pagePerBlock);
// 현재 블럭 개수
nowBlock = (int)Math.ceil((double)nowPage/pagePerBlock);
//out.println("totalPage : "+totalPage+"<br>");
//out.println("totalBlock : "+totalBlock+"<br>");
//out.println("nowBlock : "+nowBlock+"<br>");
%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Board</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
function block(block){
document.readFrm.nowPage.value = <%=pagePerBlock%>*(block-1)+1;
document.readFrm.submit();
}
function paging(page){
document.readFrm.nowPage.value = page;
document.readFrm.submit();
}
</script>
</head>
<body bgcolor="#FFFFCC" >
<div align="center"><br/>
<h2>JSP Board</h2><br/>
<table>
<tr>
<td width="600">
Total : <%=totalRecord%>Articles(<font color="red">
<%=nowPage+"/"+totalPage%>Pages</font>)
</td>
</tr>
</table>
<table>
<tr>
<td align="center" colspan="2">
<%
Vector<BoardBean> vlist = mgr.getBoardList(keyField, keyWord, start, cnt);
int listSize = vlist.size();
if(vlist.isEmpty()){
out.println("등록된 게시물이 없습니다.");
}else{
%>
<table cellspacing="0">
<tr align="center" bgcolor="#D0D0D0">
<td width="100">번 호</td>
<td width="250">제 목</td>
<td width="100">이 름</td>
<td width="150">날 짜</td>
<td width="100">조회수</td>
</tr>
<%
for(int i=0;i<numPerPage;i++){
if(i==listSize)break;
BoardBean bean = vlist.get(i);
int num = bean.getNum();
String subject = bean.getSubject();
String name = bean.getName();
String regdate = bean.getRegdate();
int depth = bean.getDepth();
int count = bean.getCount();
String filename = bean.getFilename();
%>
<tr align="center">
<td><%=totalRecord-start-i %></td>
<td align="left"><%=subject %></td>
<td><%=name %></td>
<td><%=regdate %></td>
<td><%=count %></td>
</tr>
<% }//--for%>
</table>
<% }//--if-else%>
</td>
</tr>
<tr>
<td colspan="2"><br><br></td>
</tr>
<tr>
<td>
<!-- 페이징 및 블럭 Start -->
<!-- 이전블럭 -->
<%if(nowBlock>1){ %>
<a href="javascript:block('<%=nowBlock-1 %>')">prev...</a>
<%} %>
<!-- 페이징 -->
<%
int pageStart = (nowBlock-1)*pagePerBlock+1;
int pageEnd = (pageStart+pagePerBlock)<totalPage ?
pageStart+pagePerBlock:totalPage+1;
for(;pageStart<pageEnd;pageStart++){
%>
<a href="javascript:paging('<%=pageStart %>')">
<%if(nowPage==pageStart){ %><font color="blue"><%} %>
[<%=pageStart %>]
<%if(nowPage==pageStart){ %></font><%} %>
</a>
<% }%>
<!-- 다음블럭 -->
<%if(totalBlock>nowBlock){ %>
<a href="javascript:block('<%=nowBlock+1 %>')">...next</a>
<%} %>
<!-- 페이징 및 블럭 End -->
</td>
<td align="right">
<a href="post.jsp" >[글쓰기]</a>
<a href="javascript:list()">[처음으로]</a>
</td>
</tr>
</table>
<form name="listFrm" method="post">
<input type="hidden" name="reload" value="true">
<input type="hidden" name="nowPage" value="1">
</form>
<form name="readFrm">
<input type="hidden" name="nowPage" value="<%=nowPage%>">
<input type="hidden" name="numPerPage" value="<%=numPerPage%>">
<input type="hidden" name="keyField" value="<%=keyField%>">
<input type="hidden" name="keyWord" value="<%=keyWord%>">
<input type="hidden" name="num">
</form>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>페이징 & 블럭 처리 테스트</title>
</head>
<link href="style.css" rel="stylesheet" type="text/css">
<body bgcolor="#FFFFCC">
<div align="center"><br/><br/>
<h2>페이징 & 블럭 처리 테스트</h2>
<form action="pageView.jsp">
총 레코드 값 : <input name="totalRecord">
<input type="submit" value="보내기">
</form>
</div>
</body>
</html>
<!-- pageView.jsp -->
<%@page import="ch15.UtilMgr"%>
<%@page contentType="text/html; charset=UTF-8"%>
<%
int totalRecord = UtilMgr.parseInt(request, "totalRecord");//총게시물수
int numPerPage = 10;//페이지당 레코드 개수
int pagePerBlock = 15;//블럭당 페이지 개수
int totalPage = 0;//총 페이지 개수
int totalBlock =0;//총 블럭 개수
int nowPage = 1;//현재 페이지
int nowBlock = 1;//현재 블럭
if(request.getParameter("nowPage")!=null){
nowPage = UtilMgr.parseInt(request, "nowPage");
}
int start = (nowPage*numPerPage)-numPerPage;
totalPage = (int)Math.ceil((double)totalRecord/numPerPage);
totalBlock = (int)Math.ceil((double)totalPage/pagePerBlock);
nowBlock = (int)Math.ceil((double)nowPage/pagePerBlock);
%>
<!DOCTYPE html>
<html>
<head>
<title>페이징 & 블럭 처리 테스트</title>
</head>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
function pageing(page){
document.readFrm.nowPage.value=page;
document.readFrm.submit();
}
function block(block){
document.readFrm.nowPage.value=
<%=pagePerBlock%>*(block-1)+1;
document.readFrm.submit();
}
</script>
<body bgcolor="#FFFFCC">
<div align="center"><br/>
<h2>페이징 & 블럭 처리 테스트</h2>
<table>
<tr>
<td width="700" align="center">
Total : <%=totalRecord%>Articles(
<font color="red"><%=nowPage+"/"+totalPage%>Pages</font>
)
</td>
</tr>
</table>
<!-- 게시물 번호 Start -->
<table>
<tr>
<td>게시물번호 : </td>
<%
int listSize = totalRecord - start;
for(int i =0; i<numPerPage;i++){
if(i==listSize) break;
%>
<td align="center"><%=totalRecord-start-i%> </td>
<% }//--for%>
</tr>
</table>
<!-- 게시물 번호 End -->
<!-- 페이징 및 블럭 번호 Start -->
<table>
<tr>
<td>
<!-- 이전블럭 -->
<%if(nowBlock>1) {%>
<a href="javascript:block('<%=nowBlock-1 %>')">prev...</a>
<% }%>
<!-- 페이징 -->
<%
int pageStart = (nowBlock-1)*pagePerBlock+1;
int pageEnd = (pageStart+pagePerBlock)<totalPage?
pageStart+pagePerBlock:totalPage+1;
for(;pageStart<pageEnd;pageStart++){
%>
<a href="javascript:pageing('<%=pageStart%>')">
<%if(nowPage==pageStart){%><font color="blue"><%}%>
[<%=pageStart%>]
<%if(nowPage==pageStart){%></font><%}%>
</a>
<%
}//--for
%>
<!-- 다음블럭 -->
<%if(totalBlock>nowBlock){ %>
<a href="javascript:block('<%=nowBlock+1 %>')">...next</a>
<% }%>
</td>
</tr>
</table>
<!-- 페이징 및 블럭 번호 End -->
<form name="readFrm">
<input type="hidden" name="totalRecord" value="<%=totalRecord%>">
<input type="hidden" name="nowPage" value="<%=nowPage%>">
</form>
<hr width="60%"/>
<b>
totalRecord : <%=totalRecord%>
numPerPage : <%=numPerPage%>
pagePerBlock : <%=pagePerBlock%>
totalPage : <%=totalPage%> <br/>
totalBlock : <%=totalBlock%>
nowPage : <%=nowPage%>
nowBlock : <%=nowBlock%>
</b>
<p/>
<input type="button" value="TotalRecord 입력폼"
onClick="javascript:location.href='pageView.html'">
</div>
</html>