본문 바로가기
Web & Mobile/JSP

Lecture 52 - JSP(10) Model1 기반 게시판 파일 업로드 기능 구현

by Bennyziio 2019. 5. 29.
반응형

파일 업로드 기능 구현하기

http://www.servlets.com/cos/

UploadEx01.form

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!-- form.jsp -->

<!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,minimum-scale=1.0,maximum-scale=1.0">
<title>Insert title here</title>
</head>

<body>

<form action="./form_ok.jsp" method="post">
파일 <input type="file" name="upload" />
<input type="submit" value="파일전송" />
</form>


</body>

</html>

<!-- 
	파일 업로드
	1. method - post
	2. 설정
		enctype="multipart/form-data"을 form 태그 안에 추가해야한다
 -->

<form action="./form_ok.jsp" method="post" enctype="multipart/form-data">
파일 <input type="file" name="upload" />
<input type="submit" value="파일전송" />	
</form>

UploadEx01.form_ok

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ page import = "com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import = "com.oreilly.servlet.MultipartRequest" %>

<%
	/*
		1. 업로드 경로
		2. 업로드 제한 용량(byte)
		3. 인코딩
	*/
	String uploadPath = "C:/jQuery/eclipse-workspace/UploadEx01/WebContent/upload";		// 업로드 경로
	int maxFileSize = 1024 * 1024 * 2;	// 업로드 제한 용량 = 2MB
	String encoding = "utf-8";			// 인코딩
	
	MultipartRequest multi = new MultipartRequest(
			request, 
			uploadPath, 
			maxFileSize, 
			encoding, 
			new DefaultFileRenamePolicy());
%>

upload 폴더에 파일전송한 lecense.txt가 전송되었다. 제한 용량이 2MB이므로 용량이 허용하는 파일을 전송해야 한다.

중복된 파일이 전송되면 new DefaultFileRenamePolicy()에 의해서 파일이름 뒤에 숫자가 순차적으로 붙는 알고리즘이 내장되어 있다.

2MB를 초과한 데이터를 전송시 위와 같이 에러가 난다.

위와 같이 설정하면 upload에 파일이 들어오면 알아서 새로고침 됨

UploadEx01.form_ok - 파일 저장되는 프로세스

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ page import = "com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import = "com.oreilly.servlet.MultipartRequest" %>

<%
	/*
		1. 업로드 경로
		2. 업로드 제한 용량(byte)
		3. 인코딩
	*/
	String uploadPath = "C:/jQuery/eclipse-workspace/UploadEx01/WebContent/upload";		// 업로드 경로
	int maxFileSize = 1024 * 1024 * 2;	// 업로드 제한 용량 = 2MB
	String encoding = "utf-8";			// 인코딩
	
	MultipartRequest multi = new MultipartRequest(
			request, 
			uploadPath, 
			maxFileSize, 
			encoding, 
			new DefaultFileRenamePolicy());
	
	out.println(multi.getFilesystemName("upload") + "<br />");		// 실제 저장되는 파일이름
	out.println(multi.getOriginalFileName("upload") + "<br />");	// 원본 파일이름
%>

out.println(multi.getFilesystemName("upload") + "<br />");		// 실제 저장되는 파일이름
out.println(multi.getOriginalFileName("upload") + "<br />");	// 원본 파일이름

실제 저장되는 파일과 원본 파일이름을 동시에 불러오는 프로세스이다.

UploadEx01.form_ok - 파일 크기 출력

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ page import = "com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import = "com.oreilly.servlet.MultipartRequest" %>

<%@ page import = "java.io.File" %>

<%
	/*
		1. 업로드 경로
		2. 업로드 제한 용량(byte)
		3. 인코딩
	*/
	String uploadPath = "C:/jQuery/eclipse-workspace/UploadEx01/WebContent/upload";		// 업로드 경로
	int maxFileSize = 1024 * 1024 * 2;	// 업로드 제한 용량 = 2MB
	String encoding = "utf-8";			// 인코딩
	
	MultipartRequest multi = new MultipartRequest(
			request, 
			uploadPath, 
			maxFileSize, 
			encoding, 
			new DefaultFileRenamePolicy());
	
	out.println(multi.getFilesystemName("upload") + "<br />");		// 실제 저장되는 파일이름
	out.println(multi.getOriginalFileName("upload") + "<br />");	// 원본 파일이름
	
	File file = multi.getFile("upload");
	out.println(file.length() + " byte<br />");
%>

UploadEx01.form2

<%@ 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,minimum-scale=1.0,maximum-scale=1.0">
<title>Insert title here</title>
</head>

<body>
<form action="./form2_ok.jsp" method="post" enctype="multipart/form-data">
아이디 <input type="text" name="id" /><br /><br />
비밀번호 <input type="password" name="password" /><br /><br />
파일 <input type="file" name="upload" /><br /><br />
<input type="submit" value="파일전송" />

</body>

</html>

UploadEx01.form2_ok

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ page import = "com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import = "com.oreilly.servlet.MultipartRequest" %>

<%@ page import = "java.io.File" %>

<%
	/*
		1. 업로드 경로
		2. 업로드 제한 용량(byte)
		3. 인코딩
	*/
	String uploadPath = "C:/jQuery/eclipse-workspace/UploadEx01/WebContent/upload";		// 업로드 경로
	int maxFileSize = 1024 * 1024 * 2;	// 업로드 제한 용량 = 2MB
	String encoding = "utf-8";			// 인코딩
	
	MultipartRequest multi 
		= new MultipartRequest(request, uploadPath, maxFileSize, encoding, new DefaultFileRenamePolicy());
	
	out.println(multi.getFilesystemName("upload") + "<br />");		// 실제 저장되는 파일이름
	out.println(multi.getOriginalFileName("upload") + "<br />");	// 원본 파일이름
	
	out.println(multi.getParameter("id") + "<br />");			// 사용자한테 입력받는 것들은 getParameter로 받음
	out.println(multi.getParameter("password") + "<br />");		// 사용자한테 입력받는 것들은 getParameter로 받음
	
	out.println(request.getRemoteAddr() + "<br />");	// 기존 헤더에 포함된 내용들은 그냥 받아온다
	
%>

BoardEx01.pds1 - 파일 업로드 기능이 포함된 게시판

SQL> create table pds_board1 (
  2  seq                number          not null        primary key,
  3  subject            varchar2(100)   not null,
  4  writer             varchar2(30)    not null,
  5  mail               varchar2(50),
  6  password   varchar2(10)    not null,
  7  content            varchar2(2000),
  8  filename   varchar2(200),
  9  filesize   number,
 10  hit                number          not null,
 11  wip                varchar2(15)    not null,
 12  wdate              date            not null
 13  );

테이블이 생성되었습니다.

.

BoardEx01.pds1.board_list1

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	
<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="javax.sql.DataSource" %>

<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>

<%
	request.setCharacterEncoding("utf-8");

	int cpage = 1;
	if(request.getParameter("cpage") != null
		&& !request.getParameter("cpage").equals("")) {
		cpage = Integer.parseInt(request.getParameter("cpage"));
	}

	int recordPerPage = 10;
	int totalRecord = 0;
	int totalPage = 1;
	int blockPerPage = 5;

	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	StringBuffer sb = new StringBuffer();
	try {
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup("java:comp/env");
		DataSource dataSource = (DataSource)envCtx.lookup("jdbc/oracle1");
		conn = dataSource.getConnection();

		String sql = "select seq, subject, writer, filesize, to_char(wdate, 'YYYY/MM/DD') wdate, hit, trunc(sysdate-wdate) wgap from pds_board1 order by seq desc";
		pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
	
		rs = pstmt.executeQuery();
		
		rs.last();
		totalRecord = rs.getRow();
		rs.beforeFirst();
		
		totalPage = ((totalRecord - 1) / recordPerPage) + 1;
		
		int skip = (cpage - 1) * recordPerPage;
		// absolute - 읽을 위치(커서 위치) 지정
		if (skip != 0) rs.absolute(skip);
		
		for(int i=0 ; i<recordPerPage && rs.next() ; i++) {
			String seq = rs.getString("seq");
			String subject = rs.getString("subject");
			String writer = rs.getString("writer");
			String wdate = rs.getString("wdate");
			String hit = rs.getString("hit");
			int wgap = rs.getInt("wgap");
			
			long filesize = rs.getLong("filesize");
			
			sb.append("<tr>");
			sb.append("	<td>&nbsp;</td>");
			sb.append("	<td>" + seq + "</td>");
			sb.append("	<td class='left'>");
			sb.append("		<a href='./board_view1.jsp?cpage=" + cpage + "&seq=" + seq + "'>" + subject + "</a>");
			if(wgap == 0) {
				sb.append("		&nbsp;<img src='../images/icon_hot.gif'>");
			}
			sb.append("	</td>");
			
			sb.append("	<td>" + writer + "</td>");
			sb.append("	<td>" + wdate + "</td>");
			sb.append("	<td>" + hit + "</td>");
			sb.append("	<td>");			// 이모티콘 표현되는 부분
			if(filesize != 0) {
				sb.append("	<img src='../images/icon_file.gif'/>");
			} else {
				sb.append("&nbsp;");
			}
			sb.append("	</td>");			// 이모티콘 표현되는 부분
			sb.append("</tr>");
		}
	} catch(NamingException e) {
		System.out.println("[에러] " + e.getMessage());
	} catch(SQLException e) {
		System.out.println("[에러] " + e.getMessage());
	} finally {
		if(rs != null) rs.close();
		if(pstmt != null) pstmt.close();
		if(conn != null) conn.close();
	}
%>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../css/board_list.css">
</head>

<body>
<!-- 상단 디자인 -->
<div class="con_title">
	<h3>게시판</h3>
	<p>HOME &gt; 게시판 &gt; <strong>게시판</strong></p>
</div>
<div class="con_txt">
	<div class="contents_sub">
		<div class="board_top">
			<div class="bold">
				<p>총 <span class="txt_orange"><%=totalRecord %></span>건</p>
			</div>
		</div>

		<!--게시판-->
		<div class="board">
			<table>
			<tr>
				<th width="3%">&nbsp;</th>
				<th width="5%">번호</th>
				<th>제목</th>
				<th width="10%">글쓴이</th>
				<th width="17%">등록일</th>
				<th width="5%">조회</th>
				<th width="3%">&nbsp;</th>
			</tr>
			<%=sb %>
			</table>
		</div>
		<!--//게시판-->
		
		<div class="align_right">
			<button type="button" class="btn_write btn_txt01" style="cursor: pointer;" onclick="location.href='board_write1.jsp'">쓰기</button>
		</div>

		<!--페이지넘버-->
		<div class="paginate_regular">
			<div align="absmiddle">
<%
	int startBlock = ((cpage -1) / blockPerPage)*blockPerPage + 1;
	int endBlock = ((cpage -1) / blockPerPage)*blockPerPage + blockPerPage;
	if(endBlock >= totalPage) {
		endBlock = totalPage;
	}

	if(startBlock == 1) {
		out.println("<span class='on'>&lt;&lt;</span>");		
	} else {
		out.println("<span class='off'><a href='./board_list1..println("&nbsp;&nbsp;");
	if(cpage == totalPage) {
		out.println("<span class='on'>&gt;</span>");
	} else {
		out.println("<span class='off'><a href='./board_list1.jsp?cpage=" + (cpage+1)+ "'>&gt;</a></span>");
	}
	out.println("&nbsp;");
	if(endBlock == totalPage) {
		out.println("<span class='on'>&gt;&gt;</span>");
	} else {
		out.println("<span class='off'><a href='./board_list1.jsp?cpage=" + (startBlock + blockPerPage) + "'>&gt;&gt;</a></span>");
	}
%>
			</div>
		</div>
		<!--//페이지넘버-->
	</div>
</div>
<!--//하단 디자인 -->

</body>
</html>

BoardEx01.pds1.board_view1

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="javax.sql.DataSource" %>

<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>

<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="java.io.File" %>

<%
	request.setCharacterEncoding("utf-8");
	
	String cpage = request.getParameter("cpage");
	String seq = request.getParameter("seq");
	
	String subject = "";
	String writer = "";
	String mail = "";
	String wip = "";
	String wdate = "";
	String hit = "";
	String content = "";
	String file = "";
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	StringBuffer sb = new StringBuffer();
	try {
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup("java:comp/env");
		DataSource datasource = (DataSource)envCtx.lookup("jdbc/oracle1");
		conn = datasource.getConnection();
		
		// 조회수
		String sql = "update pds_board1 set hit = hit + 1 where seq=?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, seq);
		
		pstmt.executeUpdate();
		
		// 조회
		sql = "select subject, writer, mail, wip, wdate, hit, content, filename, filesize from pds_board1 where seq=?";
		
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, seq);
				
		rs = pstmt.executeQuery();
		if(rs.next()) {
			subject = rs.getString("subject");
			writer = rs.getString("writer");
			mail = rs.getString("mail").equals("@") ? "" : rs.getString("mail");
			wip = rs.getString("wip"); 
			wdate = rs.getString("wdate");
			hit = rs.getString("hit");
			content = rs.getString("content") == null ? "" : rs.getString("content").replaceAll("\n", "<br />");
			if(rs.getLong("filesize") != 0) {
				//file = "<a href='../upload/" + rs.getString("filename") + "'>" + rs.getString("filename") + "</a>" + "(" + rs.getLong("filesize") + " byte)";
				file = "<a href='./download.jsp?filename=" + rs.getString("filename") + "'>" + rs.getString("filename") + "</a>" + "(" + rs.getLong("filesize") + " byte)";
			}
		}
	} catch(NamingException e) {
		System.out.println("[에러] " + e.getMessage());
	} catch(SQLException e) {
		System.out.println("[에러] " + e.getMessage());
	} finally {
		if(rs != null) rs.close();
		if(pstmt != null) pstmt.close();
		if(conn != null) conn.close();
	}
%>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../css/board_view.css">
</head>

<body>
<!-- 상단 디자인 -->
<div class="con_title">
	<h3>게시판</h3>
	<p>HOME &gt; 게시판 &gt; <strong>게시판</strong></p>
</div>
<div class="con_txt">
	<div class="contents_sub">
		<!--게시판-->
		<div class="board_view">
			<table>
			<tr>
				<th width="10%">제목</th>
				<td width="60%"><%= subject %></td>
				<th width="10%">등록일</th>
				<td width="20%"><%= wdate %></td>
			</tr>
			<tr>
				<th>글쓴이</th>
				<td><%= writer %><%= '(' + mail + ')' %></td>
				<th>조회</th>
				<td><%= hit %></td>
			</tr>
			<tr>
				<th>첨부 파일</th>
				<td><%=file %></td>
				<th></th>
				<td></td>
			</tr>
			<tr>
				<td colspan="4" height="200" valign="top" style="padding: 20px; line-height: 160%"><%= content %></td>
			</tr>
			</table>
		</div>

		<div class="btn_area">
			<div class="align_left">
				<button type="button" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp?cpage=<%=cpage %>'">목록</button>
			</div>
			<div class="align_right">
				<button type="button" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_modify1.jsp?cpage=<%=cpage %>&seq=<%= seq %>'">수정</button>
				<button type="button" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_delete1.jsp?cpage=<%=cpage %>&seq=<%= seq %>'">삭제</button>
				<button type="button" class="btn_write btn_txt01" style="cursor: pointer;" onclick="location.href='board_write1.jsp?cpage=<%=cpage %>'">쓰기</button>
			</div>
		</div>	
		<!--//게시판-->
	</div>
</div>
<!-- 하단 디자인 -->

</body>
</html>

BoardEx01.pds1.board_write1

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<% 
	request.setCharacterEncoding("utf-8");
	String cpage =  request.getParameter("cpage");
%>	

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../css/board_write.css">
<script type="text/javascript">
	window.onload = function() {
		document.getElementById('submit1').onclick = function() {
			//alert('click');
			if(document.frm.info.checked == false) {
				alert('동의하셔야 합니다.');
				return;
			}
			
			if(document.frm.writer.value.trim() == "") {
				alert('이름을 입력하셔야 합니다.');
				return;
			}
			
			if(document.frm.password.value.trim() == "") {
				alert('비밀번호를 입력하셔야 합니다.');
				return;
			}
			
			if(document.frm.subject.value.trim() == "") {
				alert('제목을 입력하셔야 합니다.');
				return;
			}
			
			document.frm.submit();
		};
	};
</script>
</head>

<body>
<!-- 상단 디자인 -->
<div class="con_title">
	<h3>게시판</h3>
	<p>HOME &gt; 게시판 &gt; <strong>게시판</strong></p>
</div>
<div class="con_txt">
	<form action="./board_write1_ok.jsp" method="post" name="frm" enctype="multipart/form-data">
		<div class="contents_sub">	
			<!--게시판-->
			<div class="board_write">
				<table>
				<tr>
					<th class="top">글쓴이</th>
					<td class="top" colspan="3">
						<input type="text" name="writer" value="" class="board_view_input_mail" maxlength="5" />
					</td>
				</tr>
				<tr>
					<th>제목</th>
					<td colspan="3"><input type="text" name="subject" value="" class="board_view_input" /></td>
				</tr>
				<tr>
					<th>비밀번호</th>
					<td colspan="3"><input type="password" name="password" value="" class="board_view_input_mail"/></td>
				</tr>
				<tr>
					<th>내용</th>
					<td colspan="3"><textarea name="content" class="board_editor_area"></textarea></td>
				</tr>
				<tr>
					<th>이메일</th>
					<td colspan="3">
						<input type="text" name="mail1" value="" class="board_view_input_mail"/> @ <input type="text" name="mail2" value="" class="board_view_input_mail"/>
					</td>
				</tr>
				<tr>
					<th>첨부파일</th>
					<td colspan="3">
						<input type="file" name="upload" value="" class="board_view_input" />
					</td>
				</tr>
				</table>
				
				<table>
				<tr>
					<br />
					<td style="text-align:left;border:1px solid #e0e0e0;background-color:f9f9f9;padding:5px">
						<div style="padding-top:7px;padding-bottom:5px;font-weight:bold;padding-left:7px;font-family: Gulim,Tahoma,verdana;">※ 개인정보 수집 및 이용에 관한 안내</div>
						<div style="padding-left:10px;">
							<div style="width:97%;height:95px;font-size:11px;letter-spacing: -0.1em;border:1px solid #c5c5c5;background-color:#fff;padding-left:14px;padding-top:7px;">
								1. 수집 개인정보 항목 : 회사명, 담당자명, 메일 주소, 전화번호, 홈페이지 주소, 팩스번호, 주소 <br />
								2. 개인정보의 수집 및 이용목적 : 제휴신청에 따른 본인확인 및 원활한 의사소통 경로 확보 <br />
								3. 개인정보의 이용기간 : 모든 검토가 완료된 후 3개월간 이용자의 조회를 위하여 보관하며, 이후 해당정보를 지체 없이 파기합니다. <br />
								4. 그 밖의 사항은 개인정보취급방침을 준수합니다.
							</div>
						</div>
						<div style="padding-top:7px;padding-left:5px;padding-bottom:7px;font-family: Gulim,Tahoma,verdana;">
							<input type="checkbox" name="info" value="1" class="input_radio"> 개인정보 수집 및 이용에 대해 동의합니다.
						</div>
					</td>
				</tr>
				</table>
			</div>
			
			<div class="btn_area">
				<div class="align_left">
					<button type="button" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp?cpage=<%=cpage %>'">목록</button>
				</div>
				<div class="align_right">
					<button type="button" id="submit1" class="btn_write btn_txt01" style="cursor: pointer;">등록</button>
				</div>
			</div>
			<!--//게시판-->
		</div>
	</form>
</div>
<!-- 하단 디자인 -->

</body>
</html>

BoardEx01.pds1.board_write1_ok

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="javax.sql.DataSource" %>
    
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.SQLException" %>

<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="java.io.File" %>

<%
	String uploadPath = "C:/jQuery/eclipse-workspace/BoardEx01/WebContent/upload";
	int maxFileSize = 1024 * 1024 * 2;
	String encoding = "utf-8";
	
	MultipartRequest multi
		= new MultipartRequest(request, uploadPath, maxFileSize, new DefaultFileRenamePolicy());

	String subject = multi.getParameter("subject");
	String writer = multi.getParameter("writer");
	String mail = "@";
	if(!multi.getParameter("mail1").equals("") && !multi.getParameter("mail2").equals("")) { 
		mail = multi.getParameter("mail1") + "@" + multi.getParameter("mail2");
	}
	String password = multi.getParameter("password");
	String content = multi.getParameter("content");
	
	String filename = multi.getFilesystemName("upload");
	long filesize = 0;
	File file = multi.getFile("upload");
	if(file != null) {
		filesize = file.length();
	}

	String wip = request.getRemoteAddr();

	Connection conn = null;
	PreparedStatement pstmt = null;
	
	int flag = 1;
	
	try {
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup("java:comp/env");
		DataSource datasource = (DataSource)envCtx.lookup("jdbc/oracle1");
		conn = datasource.getConnection();		
		
		String sql = "insert into pds_board1 values (board_seq.nextval, ?, ?, ?, ?, ?, ?, ?, 0, ?, sysdate)";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, subject);
		pstmt.setString(2, writer);
		pstmt.setString(3, mail);
		pstmt.setString(4, password);
		pstmt.setString(5, content);
		pstmt.setString(6, filename);
		pstmt.setLong(7, filesize);
		pstmt.setString(8, wip);
	
		int result = pstmt.executeUpdate();
		if(result == 1) {
			flag = 0;
		}
		
	} catch(NamingException e) {
		System.out.println("[에러] " + e.getMessage());
	} catch(SQLException e) {
		System.out.println("[에러] " + e.getMessage());
	} finally {
		if(pstmt != null) pstmt.close();
		if(conn != null) conn.close();
	}
	
	out.println("<script type='text/javascript'>");
	if(flag == 0) {
		out.println("alert('글쓰기에 성공했습니다.');");
		out.println("location.href='./board_list1.jsp';");
	} else if(flag == 1) {
		out.println("alert('글쓰기에 실패했습니다.');");
		out.println("history.back();");
	}
	out.println("</script>");
%>

BoardEx01.pds1.board_delete1

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="javax.sql.DataSource" %>

<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>

<%
	request.setCharacterEncoding("utf-8");

	String seq = request.getParameter("seq");
	String cpage = request.getParameter("cpage");
	
	String subject = "";
	String writer = "";
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	StringBuffer sb = new StringBuffer();
	try {
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup("java:comp/env");
		DataSource datasource = (DataSource)envCtx.lookup("jdbc/oracle1");
		conn = datasource.getConnection();
		String sql = "select subject, writer from pds_board1 where seq = ?";
		
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, seq);
				
		rs = pstmt.executeQuery();
		if(rs.next()) {
			subject = rs.getString("subject");
			writer = rs.getString("writer");
		}
	} catch(NamingException e) {
		System.out.println("[에러] " + e.getMessage());
	} catch(SQLException e) {
		System.out.println("[에러] " + e.getMessage());
	} finally {
		if(rs != null) rs.close();
		if(pstmt != null) pstmt.close();
		if(conn != null) conn.close();
	}
%>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../css/board_write.css">
<script type="text/javascript">
	window.onload = function() {
		document.getElementById('submit1').onclick = function() {
			if(document.frm.password.value.trim() == "") {
				alert('비밀번호를 입력하셔야 합니다.');
				return;
			}
			
			document.frm.submit();
		};
	};
</script>
</head>

<body>
<!-- 상단 디자인 -->
<div class="con_title">
	<h3>게시판</h3>
	<p>HOME &gt; 게시판 &gt; <strong>게시판</strong></p>
</div>
<div class="con_txt">
	<form action="./board_delete1_ok.jsp" method="post" name="frm">
	<input type="hidden" name="seq" value="<%=seq %>" />	<!-- delete할 때 seq를 받아오기 위해 hidden으로해서 작성 / 브라우저에서 소스보기 하면 값 확인가능 -->
	<input type="hidden" name="cpage" value="<%=cpage %>" />
		<div class="contents_sub">	
			<!--게시판-->
			<div class="board_write">
				<table>
				<tr>
					<th class="top">글쓴이</th>
					<td class="top" colspan="3"><input type="text" name="writer" value="<%= writer %>" class="board_view_input_mail" maxlength="5" readonly/></td>
				</tr>
				<tr>
					<th>제목</th>
					<td colspan="3"><input type="text" name="subject" value="<%= subject %>" class="board_view_input" readonly/></td>
				</tr>
				<tr>
					<th>비밀번호</th>
					<td colspan="3"><input type="password" name="password" value="" class="board_view_input_mail"/></td>
				</tr>
				</table>
			</div>
			
			<div class="btn_area">
				<div class="align_left">
					<button type="button" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp?cpage=<%=cpage %>'">목록</button>
					<button type="button" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_view1.jsp?cpage=<%=cpage %>&seq=<%=seq %>'">보기</button>
				</div>
				<div class="align_right">
					<button type="button" id="submit1" class="btn_write btn_txt01" style="cursor: pointer;">삭제</button>
				</div>
			</div>
			<!--//게시판-->
		</div>
	</form>
</div>
<!-- 하단 디자인 -->

</body>
</html>

BoardEx01.pds1.board_delete1_ok

<%@page import="java.sql.ResultSet"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="javax.sql.DataSource" %>

<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>

<%@ page import="java.io.File" %>

<%
	request.setCharacterEncoding("utf-8");

	String seq = request.getParameter("seq");
	String password = request.getParameter("password");

	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	int flag = 2;
	
	try {
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup("java:comp/env");
		DataSource datasource = (DataSource)envCtx.lookup("jdbc/oracle1");
		conn = datasource.getConnection();
		
		String sql = "select filename from pds_board1 where seq = ?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, seq);
		
		rs = pstmt.executeQuery();
		String filename = null;
		if(rs.next()) {
			filename = rs.getString("filename");
		}
		
		sql = "delete from pds_board1 where seq = ? and password = ?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, seq);
		pstmt.setString(2, password);
	
		int result = pstmt.executeUpdate();
		if(result == 1) {
			// 정상
			flag = 0;
			if(filename != null) {
				File file = new File("C:/jQuery/eclipse-workspace/BoardEx01/WebContent/upload/" + filename);
				file.delete();		// 파일 삭제
			}
		} else if (result == 0) {
			// 비밀번호 오류
			flag = 1;
		}
	} catch(NamingException e) {
		System.out.println("[에러] " + e.getMessage());
	} catch(SQLException e) {
		System.out.println("[에러] " + e.getMessage());
	} finally {
		if(pstmt != null) pstmt.close();
		if(conn != null) conn.close();
		if(rs != null) rs.close();
	}
	
	out.println("<script type='text/javascript'>");
	if(flag == 0) {
		out.println("alert('글 삭제에 성공했습니다.');");
		out.println("location.href='./board_list1.jsp?seq=" + seq +"'");
	} else if(flag == 1) {
		out.println("alert('비밀번호 오류입니다.');");
		out.println("history.back();");
	} else if(flag == 2) {
		out.println("alert('글 삭제에 실패했습니다.');");
		out.println("history.back();");
	}
	out.println("</script>");
%>

BoardEx01.pds1.board_modify1

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="javax.sql.DataSource" %>

<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>

<%
	request.setCharacterEncoding("utf-8");

	String seq = request.getParameter("seq");
	String cpage = request.getParameter("cpage");
	
	String subject = "";
	String writer = "";
	String content = "";
	String mail[] = null;
	String filename = "";
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	StringBuffer sb = new StringBuffer();
	try {
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup("java:comp/env");
		DataSource datasource = (DataSource)envCtx.lookup("jdbc/oracle1");
		conn = datasource.getConnection();
		String sql = "select writer, subject, content, mail, filename from pds_board1 where seq = ?";
		
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, seq);
				
		rs = pstmt.executeQuery();
		if(rs.next()) {
			writer = rs.getString("writer");
			subject = rs.getString("subject");
			content = rs.getString("content") == null ? "" : rs.getString("content").replaceAll("\n", "<br />");
			mail = rs.getString("mail").split("@");
			if(mail.length == 0) {
				mail = new String[] {"", ""};
			}
			filename = rs.getString("filename");
			
		}
	} catch(NamingException e) {
		System.out.println("[에러] " + e.getMessage());
	} catch(SQLException e) {
		System.out.println("[에러] " + e.getMessage());
	} finally {
		if(rs != null) rs.close();
		if(pstmt != null) pstmt.close();
		if(conn != null) conn.close();
	}
%>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../css/board_write.css">
<script type="text/javascript">
	window.onload = function() {
		document.getElementById('submit1').onclick = function() {
			if(document.frm.writer.value.trim() == "") {
				alert('이름을 입력하셔야 합니다.');
				return;
			}
			
			if(document.frm.password.value.trim() == "") {
				alert('비밀번호를 입력하셔야 합니다.');
				return;
			}
			
			if(document.frm.subject.value.trim() == "") {
				alert('제목을 입력하셔야 합니다.');
				return;
			}
			
			document.frm.submit();
		};
	};
</script>
</head>

<body>
<!-- 상단 디자인 -->
<div class="con_title">
	<h3>게시판</h3>
	<p>HOME &gt; 게시판 &gt; <strong>게시판</strong></p>
</div>
<div class="con_txt">
	<form action="./board_modify1_ok.jsp" method="post" name="frm" enctype="multipart/form-data">
	<input type="hidden" name="seq" value="<%=seq %>" />
	<input type="hidden" name="cpage" value="<%=cpage %>" />
		<div class="contents_sub">	
			<!--게시판-->
			<div class="board_write">
				<table>
				<tr>
					<th class="top">글쓴이</th>
					<td class="top" colspan="3"><input type="text" name="writer" value="<%=writer %>" class="board_view_input_mail" maxlength="5" readonly/></td>
				</tr>
				<tr>
					<th>제목</th>
					<td colspan="3"><input type="text" name="subject" value="<%=subject %>" class="board_view_input" /></td>
				</tr>
				<tr>
					<th>비밀번호</th>
					<td colspan="3"><input type="password" name="password" value="" class="board_view_input_mail"/></td>
				</tr>
				<tr>
					<th>내용</th>
					<td colspan="3"><textarea name="content" class="board_editor_area"><%=content %></textarea></td>
				</tr>
				<tr>
					<th>이메일</th>
					<td colspan="3"><input type="text" name="mail1" value="<%=mail[0] %>" class="board_view_input_mail"/> @ <input type="text" name="mail2" value="<%=mail[1] %>" class="board_view_input_mail"/></td>
				</tr>
				<tr>
					<th>첨부파일</th>
					<td colspan="3">
						기존 파일명 : <%=filename %><br /><br />
						<input type="file" name="upload" value="" class="board_view_input" />
					</td>
				</tr>
				</table>
			</div>
			
			<div class="btn_area">
				<div class="align_left">
					<button type="button" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp?cpage=<%=cpage %>'">목록</button>
					<button type="button" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_view1.jsp?cpage=<%=cpage %>&seq=<%=seq %>'">보기</button>
				</div>
				<div class="align_right">
					<button type="button" id="submit1" class="btn_write btn_txt01" style="cursor: pointer;">수정</button>
				</div>
			</div>
			<!--//게시판-->
		</div>
	</form>
</div>
<!-- 하단 디자인 -->

</body>
</html>

BoardEx01.pds1.board_modify1_ok

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="javax.sql.DataSource" %>

<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>

<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="java.io.File" %>

<%
	String uploadPath = "C:/jQuery/eclipse-workspace/BoardEx01/WebContent/upload";
	int maxFileSize = 1024 * 1024 * 2;
	String encoding = "utf-8";
	
	MultipartRequest multi
		= new MultipartRequest(request, uploadPath, maxFileSize, new DefaultFileRenamePolicy());

	//request.setCharacterEncoding("utf-8");

	String seq = multi.getParameter("seq");
	String subject = multi.getParameter("subject");
	String mail = multi.getParameter("mail1") + "@" + request.getParameter("mail2");
	String password = multi.getParameter("password");
	String content = multi.getParameter("content");
	String wip = request.getRemoteAddr();
	String cpage = multi.getParameter("cpage");
	
	String newFilename = multi.getFilesystemName("upload");
	long newFilesize = 0;
	File newFile = multi.getFile("upload");
	if(newFile != null) {
		newFilesize = newFile.length();
	}

	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	int flag = 2;
	
	try {
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup("java:comp/env");
		DataSource datasource = (DataSource)envCtx.lookup("jdbc/oracle1");
		conn = datasource.getConnection();
		
		String sql = "select filename from pds_board1 where seq =?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, seq);
		rs = pstmt.executeQuery();
		String oldFilename = null;
		if(rs.next()) {
			oldFilename = rs.getString("filename");
		}
		
		if(newFilename != null) {
			sql = "update pds_board1 set subject=?, mail=?, password=?, content=?, filename=?, filesize=? where seq = ? and password = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, subject);
			pstmt.setString(2, mail);
			pstmt.setString(3, password);
			pstmt.setString(4, content);
			pstmt.setString(5, newFilename);
			pstmt.setLong(6, newFilesize);
			pstmt.setString(7, seq);
			pstmt.setString(8, password);
		} else {
			sql = "update pds_board1 set subject=?, mail=?, password=?, content=? where seq = ? and password = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, subject);
			pstmt.setString(2, mail);
			pstmt.setString(3, password);
			pstmt.setString(4, content);
			pstmt.setString(5, seq);
			pstmt.setString(6, password);
		}
	
		int result = pstmt.executeUpdate();
		if(result == 1) {
			// 정상
			flag = 0;
			if(newFilename != null && oldFilename != null) {
				File file = new File("C:/jQuery/eclipse-workspace/BoardEx01/WebContent/upload/" + oldFilename);
				file.delete();		// 파일 삭제
			}
		} else if (result == 0) {
			// 비밀번호 오류
			flag = 1;
		}
		
	} catch(NamingException e) {
		System.out.println("[에러] " + e.getMessage());
	} catch(SQLException e) {
		System.out.println("[에러] " + e.getMessage());
	} finally {
		if(pstmt != null) pstmt.close();
		if(conn != null) conn.close();
		if(rs != null) rs.close();
	}
	
	out.println("<script type='text/javascript'>");
	if(flag == 0) {
		out.println("alert('글 수정에 성공했습니다.');");
		out.println("location.href='./board_list1.jsp?cpage=" + cpage + "&seq=" + seq +"'");
	} else if(flag == 1) {
		out.println("alert('비밀번호 오류입니다.');");
		out.println("history.back();");
	} else if(flag == 2) {
		out.println("alert('글 수정에 실패했습니다.');");
		out.println("history.back();");
	}
	out.println("</script>");
%>

BoardEx01.pds1.download

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ page import="java.io.File" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.net.URLEncoder" %>

<%
	String fileName = request.getParameter("filename");
	String downPath = "C:/jQuery/eclipse-workspace/BoardEx01/WebContent/upload/" + fileName;
	
	out.clearBuffer();
	response.setContentType("application/octet-stream");
	// 응답용 헤더 변경
	response.setHeader("Content-Disposition", "attachment;filename="
		//+ URLEncoder.encode("filename", "utf-8"));
		+ URLEncoder.encode("테스트.jpg", "utf-8"));
	FileInputStream fis = new FileInputStream(downPath);
	ServletOutputStream sos = response.getOutputStream();
	
	int data;
	byte readByte[] = new byte[4096];
	while((data = fis.read(readByte, 0, readByte.length)) != -1) {
		sos.write(readByte, 0, data);
	}
	sos.flush();
	sos.close();
	fis.close();
	
%>

 

반응형

댓글