하드코딩
.jsp
(mvc)model1
.jsp + class
client가 요청 -> jsp가 응답 -> model로 처리 -> 데이터(DB/file/기타..)
controller(요청제어)
view(결과)
(mvc)model2
model1의 상휘호환
조건
: 라이브러리
: 업로드
!파일은 데이터 베이스에 입력하지 않음 -> 파일명 / 경로 등 부수적인 걸 입력함
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 파일 업로드 기본 설정 -->
<form action="upload_ok.jsp" method="post" enctype="multipart/form-data">
파일 <input type="file" name="upload1" />
<input type="submit" value="파일업로드" />
</form>
</body>
</html>
<%@ 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:/Java/jsp-workspace/UploadEx01/src/main/webapp/upload";
int maxFileSize = 2 * 1024 * 1024; // 2메가
String encType = "utf-8";
MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encType , new DefaultFileRenamePolicy());
out.println("전송완료");
%>
: 파일이 중복되지 않게 처리해줌
<%@ 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:/Java/jsp-workspace/UploadEx01/src/main/webapp/upload";
int maxFileSize = 2 * 1024 * 1024; // 2메가
String encType = "utf-8";
MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encType , new DefaultFileRenamePolicy());
// new DefaultFileRenamePolicy() : 중복되지 않게 처리해줌
out.println("전송완료<br>");
out.println("파일명 + " + multi.getFilesystemName("upload1") + "<br>"); // 업로드 되었을 때의 파일이름
out.println("파일명 + " + multi.getOriginalFileName("upload1") + "<br>"); // 원래 파일 이름
%>
<%@ 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:/Java/jsp-workspace/UploadEx01/src/main/webapp/upload";
int maxFileSize = 2 * 1024 * 1024; // 2메가
String encType = "utf-8";
MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encType , new DefaultFileRenamePolicy());
// new DefaultFileRenamePolicy() : 중복되지 않게 처리해줌
out.println("전송완료<br>");
out.println("파일명 + " + multi.getFilesystemName("upload1") + "<br>"); // 업로드 되었을 때의 파일이름
out.println("파일명 + " + multi.getOriginalFileName("upload1") + "<br>"); // 원래 파일 이름
// 단위 : byte / retrun : long
java.io.File file = multi.getFile("upload1");
out.println("사이트 : " + file.length() + "<br>");
%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 파일 업로드 기본 설정 -->
<form action="upload_ok2.jsp" method="post" enctype="multipart/form-data">
파일1 <input type="file" name="upload1" /><br><br>
파일2 <input type="file" name="upload2" /><br><br>
<input type="submit" value="파일업로드" />
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 파일 업로드 기본 설정 -->
<form action="upload_ok3.jsp" method="post" enctype="multipart/form-data">
파일 <input type="file" name="upload3" /><br><br>
아이디 <input type="text" name="id" /><br><br>
비밀번호 <input type="password" name="password" /><br><br>
<input type="submit" value="파일업로드" />
</form>
</body>
</html>
<%@ 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:/Java/jsp-workspace/UploadEx01/src/main/webapp/upload";
int maxFileSize = 2 * 1024 * 1024; // 2메가
String encType = "utf-8";
MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encType , new DefaultFileRenamePolicy());
// new DefaultFileRenamePolicy() : 중복되지 않게 처리해줌
out.println("전송완료<br>");
out.println("파일명 : " + multi.getFilesystemName("upload3") + "<br>"); // 업로드 되었을 때의 파일이름
out.println("파일명 : " + multi.getOriginalFileName("upload3") + "<br>"); // 원래 파일 이름
out.println("아이디 : " + multi.getParameter("id") + "<br>");
out.println("비밀번호 : " + multi.getParameter("password") + "<br>");
%>
다운로드
: 브라우저 해석 가능한 파일 -> 브라우저가 view
: 브라우저가 해석 불가능한 파일 -> 다운로드
테이블 명 : pds_board1
번호 seq int not null primary key auto_increment
제목 subject varchar(150), not null
글쓴이 wirter varchar(12), not null
이메일 mail varchar(50), null
비밀번호 password varchar(12), not null
내용 content varchar(2000), null
파일명 filename varchat(50), null
파일크기 filesize int, null
조회수 hit int, not null
아이피 wip varchar(15), not null
등록일 wdate date, not null
create table pds_board1(
seq int auto_increment primary key,
subject varchar(150) not null,
writer varchar(12) not null,
mail varchar(50),
password varchar(12) not null,
content varchar(2000),
filename varchar(50),
filesize int,
hit int not null,
wip varchar(15) not null,
wdate datetime not null
);
insert into pds_board1 values (0, '제목', '이름', 'test@test.com', '1234', '내용', 'text.txt', 0, 0, '000.000.000.000', now() );
<%@ 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" %>
<%
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int totalRecord = 0;
StringBuilder sbHtml = new StringBuilder();
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb3" );
conn = dataSource.getConnection();
String sql = "select seq, subject, writer, filesize, date_format(wdate, '%Y-%m-%d') wdate, hit, datediff(now(), wdate) wgap from pds_board1 order by seq desc";
pstmt = conn.prepareStatement( sql );
rs = pstmt.executeQuery();
rs.last();
totalRecord = rs.getRow();
rs.beforeFirst();
while( rs.next() ) {
String seq = rs.getString( "seq" );
String subject = rs.getString( "subject" );
String writer = rs.getString( "writer" );
long filesize = rs.getLong( "filesize" );
String wdate = rs.getString( "wdate" );
String hit = rs.getString( "hit" );
int wgap = rs.getInt( "wgap" );
sbHtml.append( "<tr>" );
sbHtml.append( "<td> </td>" );
sbHtml.append( "<td>" + seq + "</td>" );
sbHtml.append( "<td class='left'>" );
sbHtml.append( "<a href='board_view1.jsp?seq=" + seq + "'>" + subject + "</a>" );
if( wgap == 0 ) {
sbHtml.append( " <img src='../../images/icon_new.gif' alt='NEW'>" );
}
sbHtml.append( "</td>" );
sbHtml.append( "<td>" + writer + "</td>" );
sbHtml.append( "<td>" + wdate + "</td>" );
sbHtml.append( "<td>" + hit + "</td>" );
sbHtml.append( "<td>" );
if( filesize != 0 ) {
sbHtml.append( "<img src='../../images/icon_file.gif' />" );
}
sbHtml.append( "</td>" );
sbHtml.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.css">
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<div class="contents_sub">
<div class="board_top">
<div class="bold">
<p>총 <span class="txt_orange">1</span>건</p>
</div>
</div>
<!--게시판-->
<div class="board">
<table>
<tr>
<th width="3%"> </th>
<th width="5%">번호</th>
<th>제목</th>
<th width="10%">글쓴이</th>
<th width="17%">등록일</th>
<th width="5%">조회</th>
<th width="3%"> </th>
</tr>
<%=sbHtml %>
</table>
</div>
<div class="btn_area">
<div class="align_right">
<input type="button" value="쓰기" class="btn_write btn_txt01" style="cursor: pointer;" onclick="location.href='board_write1.jsp'" />
</div>
</div>
<!--//게시판-->
</div>
</div>
<!--//하단 디자인 -->
</body>
</html>
<%@ 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" );
//System.out.println( seq );
String subject = "";
String writer = "";
String mail = "";
String wip = "";
String wdate = "";
String hit = "";
String content = "";
String filename = "";
long filesize = 0;
String file = "";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb3" );
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" );
wip = rs.getString( "wip" );
wdate = rs.getString( "wdate" );
hit = rs.getString( "hit" );
content = rs.getString( "content" ).replaceAll( "\n", "<br />" );
filename = rs.getString( "filename" );
filesize = rs.getLong( "filesize" );
if( filesize != 0 ) {
file = "<a href='../../upload/" + filename + "'>" + filename + "</a>(" + 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.css">
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <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 %>)(<%=wip %>)</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">
<input type="button" value="목록" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp'" />
</div>
<div class="align_right">
<input type="button" value="수정" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_modify1.jsp?seq=<%=seq %>'" />
<input type="button" value="삭제" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_delete1.jsp?seq=<%=seq %>'" />
<input type="button" value="쓰기" class="btn_write btn_txt01" style="cursor: pointer;" onclick="location.href='board_write1.jsp'" />
</div>
</div>
<!--//게시판-->
</div>
</div>
<!-- 하단 디자인 -->
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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.css">
<script type="text/javascript">
window.onload = function() {
document.getElementById('wbtn').onclick = function() {
//alert('click');
if(document.wfrm.info.checked == false) {
alert('동의하셔야 합니다.');
return false;
}
if(document.wfrm.writer.value.trim() == '') {
alert('글쓴이를 입력하세요.');
return false;
}
if(document.wfrm.subject.value.trim() == '') {
alert('제목을 입력하세요.');
return false;
}
if(document.wfrm.password.value.trim() == '') {
alert('비밀번호를 입력하세요.');
return false;
}
document.wfrm.submit();
};
};
</script>
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<form action="board_write1_ok.jsp" method="post" name="wfrm" enctype="multipart/form-data">
<div class="contents_sub">
<!--게시판-->
<div class="board_write">
<table>
<tr>
<th class="top">글쓴이</th>
<td class="top">
<input type="text" name="writer" value="" class="board_view_input_mail" maxlength="5" />
</td>
</tr>
<tr>
<th>제목</th>
<td><input type="text" name="subject" value="" class="board_view_input" /></td>
</tr>
<tr>
<th>비밀번호</th>
<td><input type="password" name="password" value="" class="board_view_input_mail"/></td>
</tr>
<tr>
<th>내용</th>
<td><textarea name="content" class="board_editor_area"></textarea></td>
</tr>
<tr>
<th>이메일</th>
<td>
<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>
<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">
<input type="button" value="목록" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp'" />
</div>
<div class="align_right">
<input type="button" id="wbtn" value="쓰기" class="btn_write btn_txt01" style="cursor: pointer;" />
</div>
</div>
<!--//게시판-->
</div>
</form>
</div>
<!-- 하단 디자인 -->
</body>
</html>
<%@ 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:/Java/jsp-workspace/BoardEx01/src/main/webapp/upload";
int maxFileSize = 2 * 1024 * 1024;
String encType = "utf-8";
MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encType, new DefaultFileRenamePolicy());
// write 구문
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");
}
// board_write1.jsp의 name을 ()에 적는다.
String password = multi.getParameter("password");
String content = multi.getParameter("content");
String wip = request.getRemoteAddr();
String filename = multi.getFilesystemName("upload");
long filesize = 0;
if(multi.getFile("upload") != null) { // null : 업로드 되었으면
filesize = multi.getFile("upload").length();
}
// DB연동
Connection conn = null;
PreparedStatement pstmt = null;
// 0 : 정상 / 1 : 비정상
int flag = 1;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb3" );
conn = dataSource.getConnection();
String sql = "insert into pds_board1 values (0, ?, ?, ?, ?, ?, ?, ?, 0, ?, now() );";
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) {
//System.out.println("성공");
flag = 0;
} else {
//System.out.println("실패");
}
} 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 {
out.println("alert('글 쓰기 실패');");
out.println("history.back();");
}
out.println("</script>");
%>
<%@ 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 subject = "";
String writer = "";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb3" );
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.css">
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'dbtn' ).onclick = function() {
if( document.dfrm.password.value.trim() == '' ) {
alert( '비밀번호를 입력하셔야 합니다.' );
return false;
}
document.dfrm.submit();
};
};
</script>
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<form action="board_delete1_ok.jsp" method="post" name="dfrm">
<input type="hidden" name="seq" value="<%=seq %>" />
<div class="contents_sub">
<!--게시판-->
<div class="board_write">
<table>
<tr>
<th class="top">글쓴이</th>
<td class="top">
<input type="text" name="writer" value="<%=writer %>" class="board_view_input_mail" maxlength="5" readonly/>
</td>
</tr>
<tr>
<th>제목</th>
<td><input type="text" name="subject" value="<%=subject %>" class="board_view_input" readonly/></td>
</tr>
<tr>
<th>비밀번호</th>
<td><input type="password" name="password" value="" class="board_view_input_mail"/></td>
</tr>
</table>
</div>
<div class="btn_area">
<div class="align_left">
<input type="button" value="목록" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp'" />
<input type="button" value="보기" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_view1.jsp?seq=<%=seq %>'" />
</div>
<div class="align_right">
<input type="button" id="dbtn" value="삭제" class="btn_write btn_txt01" style="cursor: pointer;" />
</div>
</div>
<!--//게시판-->
</div>
</form>
</div>
<!-- 하단 디자인 -->
</body>
</html>
<%@ 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" );
String uploadPath = "C:/Java/jsp-workspace/BoardEx01/src/main/webapp/upload";
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/mariadb3" );
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( uploadPath, 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( rs != null ) rs.close();
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();" );
} else {
out.println( "alert('글삭제에 실패');" );
out.println( "history.back();" );
}
out.println( "</script>" );
%>
<%@ 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" );
//System.out.println( seq );
String subject = "";
String writer = "";
String[] mail = null;
String content = "";
String filename = "";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb3" );
conn = dataSource.getConnection();
String sql = "select subject, writer, mail, filename, content 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" );
if( rs.getString( "mail").equals("") ) {
mail = new String[] { "", "" };
} else {
mail = rs.getString( "mail" ).split( "@" );
}
filename = rs.getString("filename") == null ? "" : rs.getString("filename");
content = rs.getString( "content" );
}
} 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.css">
<script type="text/javascript">
window.onload = function() {
document.getElementById('mbtn').onclick = function() {
if(document.mfrm.subject.value.trim() == '') {
alert('제목을 입력하세요.');
return false;
}
if(document.mfrm.password.value.trim() == '') {
alert('비밀번호를 입력하세요.');
return false;
}
document.mfrm.submit();
};
};
</script>
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<form action="board_modify1_ok.jsp" method="post" name="mfrm" enctype="multipart/form-data">
<input type="hidden" name="seq" value="<%=seq %>" />
<div class="contents_sub">
<!--게시판-->
<div class="board_write">
<table>
<tr>
<th class="top">글쓴이</th>
<td class="top">
<input type="text" name="writer" value="<%=writer %>" class="board_view_input_mail" maxlength="5" readonly/>
</td>
</tr>
<tr>
<th>제목</th>
<td><input type="text" name="subject" value="<%=subject %>" class="board_view_input" /></td>
</tr>
<tr>
<th>비밀번호</th>
<td><input type="password" name="password" value="" class="board_view_input_mail"/></td>
</tr>
<tr>
<th>내용</th>
<td><textarea name="content" class="board_editor_area"></textarea></td>
</tr>
<tr>
<th>이메일</th>
<td>
<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>
기존 파일명 : <%=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">
<input type="button" value="목록" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp'" />
<input type="button" value="보기" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_view1.jsp'" />
</div>
<div class="align_right">
<input type="button" id="mbtn" value="수정" class="btn_write btn_txt01" style="cursor: pointer;" />
</div>
</div>
<!--//게시판-->
</div>
</form>
</div>
<!-- 하단 디자인 -->
</body>
</html>
새로운 첨부파일 있는 경우
기본 파일 유 -> 파일 삭제
기존 파일 무 -> 파일 삭제x
=> update 테이블명 set ... filename=?, filesize=? where ...
새로운 첨부파일 없는 경우
-> 파일 삭제x
=> update 테이블명 set ... where ...
<%@ 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:/Java/jsp-workspace/BoardEx01/src/main/webapp/upload";
int maxFileSize = 2 * 1024 * 1024;
String encType = "utf-8";
MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encType, new DefaultFileRenamePolicy());
String seq = multi.getParameter("seq");
// write 구문
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;
if(multi.getFile("upload") != null) { // null : 업로드 되었으면
filesize = multi.getFile("upload").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/mariadb3" );
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(filename != null) { // 파일 O
sql = "update pds_board1 set subject=?, mail=?, content=?, filename=?, filesize=? where seq=? and password=?";
pstmt = conn.prepareStatement( sql );
pstmt.setString(1, subject);
pstmt.setString(2, mail);
pstmt.setString(3, content);
pstmt.setString(4, filename);
pstmt.setLong(5, filesize);
pstmt.setString(6, seq);
pstmt.setString(7, password);
} else { // 파일 X
sql = "update pds_board1 set subject=?, mail=?, content=? where seq=? and password=?";
pstmt = conn.prepareStatement( sql );
pstmt.setString(1, subject);
pstmt.setString(2, mail);
pstmt.setString(3, content);
pstmt.setString(4, seq);
pstmt.setString(5, password);
}
int result = pstmt.executeUpdate();
if(result == 1) {
flag = 0;
if(filename != null && oldFilename != null) {
// 기존 파일 삭제
File file = new File(uploadPath, oldFilename);
file.delete();
}
} else if(result == 0) {
flag = 1;
if(filename != null) {
// 비밀번호가 잘 못된 경우/새 파일 삭제
File file = new File(uploadPath, filename);
file.delete();
}
}
} 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_view1.jsp?seq=" + seq + "';");
} else if(flag == 1){
out.println("alert('비밀번호 오류');");
out.println("history.back();");
} else {
out.println("alert('글 수정 실패');");
out.println("history.back();");
}
out.println("</script>");
%>
결과는 직접 해보면서 확인하기