[JSP] 게시판 ② - 게시글 작성
05 Jan 2022 -
4 minute read
bbs/Post.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>글쓰기 페이지</title>
<link rel="stylesheet" href="/Proj_BBS/style/Style.css">
</head>
<body>
<div id="wrap">
<h1>글쓰기 페이지</h1>
<header id="header">
<nav>
<ul>
<li><a href="/Proj_BBS/Index.jsp">메인</a></li>
<li><a href="#">로그인</a></li>
<li><a href="/Proj_BBS/bbs/Post.jsp">글쓰기</a></li>
<li><a href="/Proj_BBS/bbs/List.jsp">자유게시판</a></li>
</ul>
</nav>
</header>
<!-- header#header -->
<main id="main">
<h3>글쓰기</h3>
<form action="PostProc.jsp" name="postFrm" id="postFrm" method="post" enctype="multipart/form-data">
<table class="postTbl">
<tbody>
<tr>
<th>이름</th>
<td>
<input type="text" name="uName" id="uName">
</td>
</tr>
<tr>
</tr>
<tr>
<th>제목</th>
<td>
<input type="text" name="subject" id="subject">
</td>
</tr>
<tr>
<th>내용</th>
<td>
<textarea name="content" id="content" cols="60" rows="10" wrap="hard"></textarea>
</td>
</tr>
<tr>
<th>비밀번호</th>
<td>
<input type="password" name="uPw" id="uPw">
</td>
</tr>
<tr>
<th>파일첨부</th>
<td>
<input type="file" name="fileName" id="fileName">
</td>
</tr>
<tr>
<th>내용타입</th>
<td>
<label>
<input type="radio" name="contentType" value="HTML"> HTML
</label>
<label>
<input type="radio" name="contentType" value="TEXT" checked> TEXT
</label>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<hr>
</td>
</tr>
<tr>
<td colspan="2">
<button type="button" id="regBtn">등록</button>
<button type="reset">다시쓰기</button>
<button type="button" id="listBtn">리스트</button>
</td>
</tr>
</tfoot>
</table>
<input type="hidden" name="ip" value="<%=request.getRemoteAddr() %>">
<!-- IP 주소 IPv4 형식으로 설정
: 프로젝트 > Run as configuration > Tomcat > VM arguments
> 마지막에 -Djava.net.preferIPv4Stack=true 입력 -->
</form>
</main>
<!-- main#main -->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="/Proj_BBS/script/Script.js"></script>
</body>
</html>
bbs/PostProc.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8"); %>
<jsp:useBean id="boardMgr" class="pack_BBS.BoardMgr" scope="page" />
<%
boardMgr.insertBoard(request);
response.sendRedirect("List.jsp");
%>
style/Style.css
@charset "UTF-8";
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.flex-container { display: flex; }
div#wrap {
width: 800px;
border: 1px solid #000;
margin: 10px auto;
padding: 20px;
}
#header, #main { margin: 10px 0; }
#main { padding: 40px; }
h1 { text-align: center; }
ul {
list-style: none;
display: flex;
}
li {
width: 170px;
border: 1px solid #000;
text-align: center;
}
li:hover{ background-color: #ddd; }
a {
font-size: 20px;
text-decoration: none;
color: #000;
}
tfoot>tr>td {
text-align: center;
}
::-webkit-file-upload-button {
cursor:pointer;
}
.postTbl td, .postTbl th {
border-bottom: 1px solid #eee;
padding: 8px 10px;
}
.postTbl th {
background-color: #eee;
width: 100px;
}
.postTbl input, .postTbl textarea {
border: 1px solid #ccc;
}
script/Script.js
$(function(){
// 게시글 등록 유효성 검사
$("#regBtn").click(function(){
let uName = $("#uName").val().trim();
let subject = $("#subject").val().trim();
let uPw = $("#uPw").val().trim();
if (uName == "") {
alert("이름을 입력해주세요.");
$("#uName").focus();
}
else if (subject == "") {
alert("제목을 입력해주세요.");
$("#subject").focus();
}
else if (uPw == "") {
alert("비밀번호를 입력해주세요.");
$("#uPw").focus();
}
else {
$("#postFrm").submit();
}
});
});
pack_BBS/BoardMgr.java
package pack_BBS;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.http.HttpServletRequest;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
public class BoardMgr {
private DBConnectionMgr pool;
private static final String SAVEFOLDER = "D:/ezen/silsp/jsp_Model1/Proj_BBS/src/main/webapp/fileupload";
private static String encType = "UTF-8";
private static int maxSize = 5 * 1024 * 1024;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
public BoardMgr() {
try {
pool = DBConnectionMgr.getInstance();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// 글 입력 (PostProc.jsp)
public void insertBoard(HttpServletRequest req) {
MultipartRequest multi = null;
int fileSize = 0;
String fileName = null;
try {
conn = pool.getConnection();
//게시글은 고유 등록번호가 있어야한다
// (1 2 3 4 번 글 중 3번글 지워도 4번은 그대로 4번)
sql = "select max(num) from tblBoard";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
int ref = 1;
if (rs.next()) ref = rs.getInt(1) + 1;
File file = new File(SAVEFOLDER);
if (!file.exists()) file.mkdirs();
//폴더(fileupload)가 존재하면 false 존재하지 않으면 true
multi = new MultipartRequest(req, SAVEFOLDER, maxSize, encType, new DefaultFileRenamePolicy());
if (multi.getFilesystemName("fileName") != null) {
fileName = multi.getFilesystemName("fileName");
fileSize = (int)multi.getFile("fileName").length();
}
String content = multi.getParameter("content");
if (multi.getParameter("contentType").equalsIgnoreCase("TEXT")) {
// .equalsIgnoreCase : 대소문자상관없음
content = UtilMgr.replace(content, "<", "<");
// < = < / > = >
}
sql = "insert into tblBoard (";
sql += "uName, subject, content, ref, pos, depth, ";
sql += "regDate, uPw, ip, count, fileName, fileSize) values(";
sql += "?, ?, ?, ?, 0, 0, now(), ?, ?, 0, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, multi.getParameter("uName"));
pstmt.setString(2, multi.getParameter("subject"));
pstmt.setString(3, content);
pstmt.setInt(4, ref);
pstmt.setString(5, multi.getParameter("uPw"));
pstmt.setString(6, multi.getParameter("ip"));
pstmt.setString(7, fileName);
pstmt.setInt(8, fileSize);
pstmt.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
pool.freeConnection(conn, pstmt, rs);
}
}
}
pack_BBS/UtilMgr.java
package pack_BBS;
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) {
//지역변수 e의 값이 0보다 크면 true
result.append(str.substring(s, e));
result.append(replace);
s = e + pattern.length();
}
result.append(str.substring(s));
return result.toString();
}
}