게시판 - simple

준동이·2023년 4월 25일
0
post-thumbnail

get / post

get => a태그
=> 개발자가 의도한 방식으로 데이터 전송

post => form태그
=> 사용자 입력 대기

웹 프로그래머
게시판이 시작이자 끝
=> CRUD
(CRUD는 대부분의 컴퓨터 소프트웨어가 가지는 기본적인 데이터 처리 기능인 Create(생성), Read(읽기), Update(갱신), Delete(삭제)를 묶어서 일컫는 말이다)

웹 프로그램
UI 제작 - 웹디자이너(psd, ai) / 퍼블리셔(산출물 - html) 에서 발전한게 => front - end programmer(js) 이렇게 완성된 것을 => back - end programmer한테 넘긴다.

디자인 시안을 가지고 -> 웹 사이트 프로그램
1.페이지의 흐름 + 데이터의 흐름

*기획
2.UML
3.ERD
4.DFD (data flow diagram) - 새로운 프로그램이나 (기획)
데이터 흐름도(DFD)는 프로세스나 시스템의 정보 흐름을 나타낸다
4-1.page간 흐름
4-2.page 내부에 흐름(알고리즘)



DFD



세팅

프로젝트생성 -> board폴더 webapp에 넣기 -> META-INF에 context.xml 설정 -> lib에 mariadb 넣기

새로 만든 사용자와 데이터베이스 이름으로 설정 ( 밑에서 새로 만드는 작업 함 )



1.ERD - 1개...테이블에 대한 컬럼(어떤 컬럼이 있으면 프로그램이 돌아갈지)을 .. 한글로 정의

테이블명	board1
번호		seq			int				not null	primary key		auto_increment
제목		subject 	varchar(150)  	not null	
글쓴이	writer		varchar(12)	  	not null
이메일	mail 		varchar(50)  
비밀번호	password	varchar(12)		not null
내용		content 	varchar(2000)
조회수	hit 		int 			not null
아이피	wip 		varchar(15) 	not null
등록일	wdate 		datetime 		not null
=> 로지컬 다이어그램

*암호화
평문 -> 비문
기법 -> md5, sha 
java
mariadb

create 구문 만들기
create table board1 (
seq int not null primary key auto_increment,
subject varchar(150) not null,
writer varchar(12) not null,
mail varchar(50),
password varchar(12) not null,
content varchar(2000) not null,
hit int not null,
wip varchar(15) not null,
wdate datetime not null
);
    
데이터베이스명 : board
사용자명 : board
암호 : 1234

insert into board1 values(0,'제목','이름','test@test.com','1234','내용',0,'000,000,000,000', now());


페이지 흐름 + 데이터의 흐름

글 목록		board_list1.jsp
글 쓰기 		board_write1.jsp
글자세히보기	board_view1.jsp
글 수정		board_modify1.jsp
글 삭제 		board_delete1.jsp


페이지의 흐름(page navigation)
board_list1.jsp
		(데이터x)넘어갈 때	->	(입력내용) 넘어갈 때 	-> 	(x)	
		board_write1.jsp 	-> board_write_ok1.jsp	-> board_list1.jsp
        (seq)
        board_view1.jsp
        		(seq)		  ->		(seq 수정내용)
        		board_modify1.jsp	-> board_modify_ok1.jsp		-> 수정하면 board_view1.jsp
                (seq)		  ->		(seq, 비밀번호)		->		(x)
                board_delete1.jsp	-> board_delete1_ok.jsp 	-> board_list
                
                



writer

게시판 정보 입력한 것 데이터베이스에 저장

프로그램 제작은 write쪽 하고 view로 넘어가는것이 좋다.
board_writer1.jsp

<%@ 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 &gt; 게시판 &gt; <strong>게시판</strong></p>
</div>
<div class="con_menu"></div>
<div class="con_txt">
	<form action="board_write1_ok.jsp" method="post" name="wfrm">
		<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>
				</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>

board_writer1_ok.jsp

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

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

String subject = request.getParameter("subject");
String writer = request.getParameter("writer");

String mail = "";
if(!request.getParameter("mail1").equals("") && !request.getParameter("mail2").equals("")) {
	mail = request.getParameter("mail1") + "@" + request.getParameter("mail2");
}

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


// request.getRemoteAeer() : JAVA, jsp 에서 클라이언트의 ip주소를 얻기 위해 사용하는 코드
// 0:0:0:0:0:0:0:1로 얻는데, IPV6 체계로 얻어오는것이라서 그렇다.
String wip = request.getRemoteAddr();

/* 잘 출력되는지 꼭 확인해보기
System.out.println(subject);
System.out.println(writer);
System.out.println(mail);
System.out.println(password);
System.out.println(content);
System.out.println(wip);
*/

Connection conn = null;
PreparedStatement pstmt = 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 = "insert into 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, wip);
	
int result = pstmt.executeUpdate();
	
	if(result == 1) {
		flag = 0;
		System.out.println("성공");
	} else {
		flag = 1;
		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>" );
%>

각 부분에 내용 적고 쓰기 클릭하기

데이터베이스에 입력이 된다.



list 리스트 생성

board_list1.jsp

<%@ 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="java.sql.ResultSet"%>

<%
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();
	
	// seq를 내림차순으로 만듦
	String sql = "select seq, subject, writer, date_format(wdate,'%Y-%m-%d')wdate, hit from board1 order by seq desc";
	pstmt = conn.prepareStatement(sql);
	
	rs = pstmt.executeQuery();
	
	// 커서 맨 마지막으로 이동
	rs.last();
	
	// getRow가 갯수 읽어줌
	totalRecord = rs.getRow();
	
	// 다시 돌려놓기
	rs.beforeFirst();
	while(rs.next()) {
		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");
		
		sbHtml.append("<tr>");
		sbHtml.append("<td>&nbsp;</td>");
		sbHtml.append("<td>" + seq + "</td>");
        
        /*
        list를 통하여 board_view1를 눌렀을 때 seq값을 갖고 가라는 의미
		"<td class='left'><a href='board_view1.jsp?seq=" + seq + "'>"
        */
		sbHtml.append("<td class='left'><a href='board_view1.jsp?seq=" + seq + "'>" + subject + "</a>&nbsp;<img src='../../images/icon_new.gif' alt='NEW'></td>");
        
		sbHtml.append("<td>" + writer  + "</td>");
		sbHtml.append("<td>" + wdate + "</td>");
		sbHtml.append("<td>" + hit + "</td>");
		sbHtml.append("<td>&nbsp;</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 &gt; 게시판 &gt; <strong>게시판</strong></p>
</div>
<div class="con_txt">
	<div class="contents_sub">
		<div class="board_top">
			<div class="bold"><span class="txt_orange"><%=totalRecord %></span></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>
<!--  내용 시작 -->
<%=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>



등록일을 년 월 일만 나오게 하기

java적으로 처리

db적으로 처리 :

date_format(wdate,'%Y-%m-%d')wdate

총 건수 (데이터건수) 설정


// 데이터 건수 집어넣기
int totalRecord = 0; 

// 이 코드 이후에 코드 작성
rs = pstmt.executeQuery();
	
// 커서 맨 마지막으로 이동
rs.last();
	
// getRow가 갯수 읽어줌
totalRecord = rs.getRow();
	
// 다시 돌려놓기
rs.beforeFirst();
    
    
//
<div class="bold"><span class="txt_orange"><%=totalRecord %></span></div>



view

list를 통해서 확인이 가능하다.
바로 view 실행하면 확인 안됨.
seq를 통해(담아서) 간다.

list를 통하여 board_view1를 눌렀을 때 seq값을 갖고 가라는 의미

"<td class='left'><a href='board_view1.jsp?seq=" + seq + "'>"

board_view1.jsp

<%@ 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="java.sql.ResultSet"%>

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

String seq = request.getParameter("seq");
//System.out.println(seq);

// try ~ catch를 지나서도 사용할 변수라서 바깥에 선언
String subject = "";
String writer = "";
String mail = "";
String wip = "";
String wdate = "";
String hit = "";
String content = "";

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, wip, date_format(wdate,'%Y-%m-%d')wdate, hit, content from board1 where seq=?";
	pstmt = conn.prepareStatement(sql);
	pstmt.setString(1, seq);
	
	rs = pstmt.executeQuery();
	
	// view에서는 데이터를 하나만 가져오기때문에 if문을 사용
	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");
	}
} 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 &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%>)(<%=wip %>)</td>
				<th>조회</th>
				<td><%=hit %></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>

아까는 목록을 눌러도 빈 공백으로 나왔지만 리스트를 통해 뷰를 들어가면 이렇게 저장돼 있는 정보들이 나온다.



내용란에 글을 쓸 때 줄바꿈을 하여도 줄바꿈이 안돼서 replaceAll 해줘야 줄바꿈 인식 해줌

content = rs.getString("content").replaceAll("\n","<br>");



삭제 - delete

// view에서 밑의 코드에 삭제부분에  넣어줘서 버튼 누르면 seq값 가져가게 한다.
<div class="align_right">
				<input type="button" value="수정" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_modify1.jsp'" />
				<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> 

view에서 클릭하고 seq를 가져옴 board_delete1.jsp
<%@ 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="java.sql.ResultSet"%>
<%
	request.setCharacterEncoding("utf-8");

	String seq = request.getParameter("seq");
	// System.out.println(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 board1 where seq=?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, seq);
		
		rs = pstmt.executeQuery();
		
		// view에서는 데이터를 하나만 가져오기때문에 if문을 사용
		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 &gt; 게시판 &gt; <strong>게시판</strong></p>
</div>
<div class="con_txt">
	<form action="board_delete1_ok.jsp" method="post" name="dfrm">
		<!--hiddne은 디자인에 안보이고싶을 때 사용한다-->
		<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'" />
				</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>

board_delete1_ok.jsp

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

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

	String seq = request.getParameter("seq");
	String password = request.getParameter("password");
	
	// System.out.println(seq);
	// System.out.println(password);
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	
	// 2 : 시스템 오류
	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 = "delete from board1 where seq=? and password=?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, seq);
		pstmt.setString(2, password);
		
		// result가 0이면 비밀번호 틀린 것 / 0 : 비밀번호 오류, 1 : 정상
		int result = pstmt.executeUpdate();
		if(result == 1) {
			flag = 0; // 정상
		} 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();
	}	
    
    // 자바스크립트로 출력 / JSP 코드로 javascript 만듦
        // 오류 났을때 알림창을 띄우기 위한 것.
		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>");
%>

삭제시킴



modify

seq를 가져와야함.

board_modify1.jsp

<%@ 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 = "";
	
	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, content from 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( "@" );
			}

			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 &gt; 게시판 &gt; <strong>게시판</strong></p>
</div>
<div class="con_txt">
	<form action="board_modify1_ok.jsp" method="post" name="mfrm">
		<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"><%=content %></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>
				</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>


board_modify1_ok.jsp

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

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

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

String subject = request.getParameter("subject");
String mail = "";
if (!request.getParameter("mail1").equals("") && !request.getParameter("mail2").equals("")) {
	mail = request.getParameter("mail1") + "@" + request.getParameter("mail2");
}
String password = request.getParameter("password");
String content = request.getParameter("content");

Connection conn = null;
PreparedStatement pstmt = 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 = "update 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;
	} 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();
}

	// 자바스크립트로 출력 / JSP 코드로 javascript 만듦
	out.println("<script type='text/javascript'>");
	if (flag == 0) {
		out.println("alert('글수정 성공');");
		out.println("location.href='board_modify1.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>");
%>

profile
개발자 꿈나무

0개의 댓글