23.04.25

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

get : a 태그에서 주로 사용하는 방식으로 개발자가 의도한 방식으로 데이터 전송한다.

post : form 태그에서 주로 사용하는 방식으로 사용자 입력 후에 그에 맞게 전송한다.

웹 프로그램

UI 제작 -> 웹 디자이너(psd : 포토샵, ai) / 퍼블리셔(html) -> front-end programmer(js)

back-end programmer

디자인 시안 ---------(↓)-------------> 웹사이트 프로그램

1. page 흐름 + 데이터 흐름

-기획-
2. UML
3. ERD
4. DFD(Date Flow Diagram) : 프로세스나 시스템 흐름을 나타낸 것(새로운 프로그램 기획할 때)

DFD 종류
1. 페이지간 흐름
2. 페이지 내부에 흐름(알고리즘)


https://terms.naver.com/entry.naver?docId=3532935&cid=58528&categoryId=58528
참고



게시판 만들기


1. DB 작업

ERD - 1개,, 테이블에 대한 컬럼 한글로 적기(logical diagram뽑기)

테이블 설정(만들기)
create table board ( 
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); 


데이터베이스명 : boaard
사용자명 board
암호 1234

정한 후, 사용자, 데이터베이스, 테이블까지 만들고 insert로 컬럼 하나 넣어주기! (확인용이)

나중에 비밀번호 암호화도 생각해주기!

2. 페이지 흐름(page navigation) 과 데이터 흐름 잡기

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

리스트 실행하면 목록과 쓰기가 나오고 목록 클릭시 수정, 삭제가 추가로 나오는 게시판 구조

  1. 글쓰기(board_write1.jsp)(데이터 필요 x) -> board_write1_ok.jsp(입력할 내용 전체 데이터 필요)에 가서 db에 넣는 작업 하고 다시 리스트(board_list1.jsp) (데이터 필요 x)로 간다.

--중간에 리스트 작업하기(글 쓴 목록 보여주기 위함)--

-- view는 list쪽에서 seq의 번호값 가지기 위해 작업을 한 후에 view 작업(리스트 목록에서 특정 게시물 클릭시 그 게시물이 나오기 위한 작업)--

  1. 글자세히보기(board_view1.jsp)
    수정(board_modify1.jsp) (seq 필요, view에서 작업) -> board_modify1_ok.jsp(seq / 수정 내용 필요)으로 가서 수정 -> 자세히보기(board_view1.jsp) (데이터 필요 x)감

  2. 삭제(board_delete1.jsp) (seq 필요, view에서 작업) -> board_delete1_ok.jsp(seq / 비밀번호 필요)으로 가서 삭제시 -> 리스트(board_list1.jsp) (데이터 필요 x)로 감


3. jsp file

각 jsp file만들고 db 연동 준비(예시는 풀링으로 함, context.xml에 내용 쓰고 연동 준비)


4. 쓰기 부분 작업

board_write1.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>

  1. board_write1_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");
	
    //ip 얻기 위한 코드
	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;
	
	//  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 board 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;
		}
		else {
			System.out.println("실패");			
		}
		
		} catch(NamingException e) {
			System.out.println("[에러] : " + e.getMessage());		
		} catch(SQLException e) {
			System.out.println("[에러] : " + e.getMessage());
		} finally {
			if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
			if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
}
	//jsp코드로 자바스크립트로 만들기 위함
	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>");
	
	
	
	
%>


5. 리스트(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" %>

<%
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	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();
		
		//order by ~ desc 써서 최신글이 위로 나오게끔 유도
		String sql = "select seq, subject, writer, wdate, hit from board order by seq desc";
		
		pstmt = conn.prepareStatement(sql);
		
		rs = pstmt.executeQuery();
		
		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");
			
			//db에서 데이터를 받아서 쓸 때마다 리스트 목록에서 그대로 보여주는 코드
			sbHtml.append("<tr>");
			sbHtml.append("<td>&nbsp;</td>");
			sbHtml.append("<td>" + seq + "</td>");
			sbHtml.append("<td class='left'><a href='board_view1.jsp'>" + 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) try { rs.close(); } catch(SQLException e) {} 
		if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
		if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
	}
	
%>
<!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">1</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>

게시글을 쓰고 확인을 누르면 해당 쓴 게시물이 테이블 안에 뜬다.

tip1 : 등록일의 시간을 없애고 년도 날짜만 나오게 하고 싶을 경우

1. 자바 (문자열 사용) : substring 사용

2. db 문법 사용 : String sql = "select seq, subject, writer, date_format(wdate, '%Y-%m-%d') wdate, hit from board order by seq desc";


tip2 : 총 갯수 설정 방법

1. db select count(*) 이용

2. resultset 커서 조절

		int totalRecord = 0;
    	//맨 마지막으로 rs커서 이동
		rs.last();
		//그 행 값을 얻음
		totalRecord = rs.getRow();
		//다시 커서를 돌려놓음
		rs.beforeFirst();
    <%=totalRecord %> <--총 갯수 부분에 적기


6. board_view 작업하기

board_view는 board_list 파일에서 거쳐서 실행하는 것(view에서 실행하면 에러남, list에서 실행할 것)

board_list1.jsp

			//board 쪽 해석 : a기능의 board 부분을 클릭했을 때 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>");


첫번째 게시물 클릭시에 seq = 1 넘어간 값 확인

board_view.jsp

<%@page import="org.mariadb.jdbc.internal.com.read.dao.Results"%>
<%@ 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);
	
	//view에 필요한 데이터(쓸 수 있는 경우를 늘리기 위해 위에다 선언)
	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, wdate, hit, content from board where seq = ?";
		
		pstmt = conn.prepareStatement(sql);
		
        //seq의 값에 따라 나오는 뷰가 달라진다.
		pstmt.setString(1, seq);
		
		rs = pstmt.executeQuery();
		
		//view는 데이터를 하나 가지고 오기 때문에 while문 낭비가 됨
        //다 선언하고 밑에 상단 디자인 쪽으로 가서 작업 마무리해주기
		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) try { rs.close(); } catch(SQLException e) {} 
		if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
		if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
	}
%>
<!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 %></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'" />
				<input type="button" value="삭제" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_delete1.jsp'" />
				<input type="button" value="쓰기" class="btn_write btn_txt01" style="cursor: pointer;" onclick="location.href='board_write1.jsp'" />
			</div>
		</div>	
		<!--//게시판-->
	</div>
</div>
<!-- 하단 디자인 -->

</body>
</html>

tip : 내용 엔터키 적용 방법 (replaceAll 사용하여 \n을 br(엔터키)로 치환

	if(rs.next()) 부분 수정 :
    content = rs.getString("content").replaceAll("\n", "<br>");


7. 삭제(delete.jsp) 작업하기

작업 방향
1. 삭제 클릭시, 글쓴이, 제목 나오게끔 하기
2. 삭제를 누르면 삭제하는 코드

7_1
board.view 에서

				<input type="button" value="삭제" class="btn_list btn_txt02" style="cursor: pointer;" 
                onclick="location.href='board_delete1.jsp />  <-- 이 부분에서 jsp 뒤에

				<input type="button" value="삭제" class="btn_list btn_txt02" style="cursor: pointer;" 
                onclick="location.href='board_delete1.jsp?seq=<%=seq %>'" />
 <-- 이렇게 변경(아까처럼 seq 값을 가져오기 위함)

board_delete1.jsp

<%@page import="org.mariadb.jdbc.internal.com.read.dao.Results"%>
<%@ 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 = "";
	
	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 board where seq = ?";
		
		pstmt = conn.prepareStatement(sql);
		
		pstmt.setString(1, seq);
		
		rs = pstmt.executeQuery();
		
		//view는 데이터를 하나 가지고 오기 때문에 while문 낭비가 됨
		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) try { rs.close(); } catch(SQLException e) {} 
		if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
		if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
	}
%>	
<!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.frm.password.value.trim() == "") {
			alert('비밀번호를 입력하세요!');
			return false;
		}
		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="delete1_ok.jsp" method="post" name="frm">
		<!-- hidden : 디자인에서는 안뜨고 페이지 원본에서만 볼 수 있는 것 -->
		<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>


비밀번호 입력 안하고 삭제 버튼 누를 시 경고창 발생 화면

7_2 . delete1_ok.jsp 작업 ( 삭제 버튼 누를 시에 삭제)

<%@page import="org.mariadb.jdbc.internal.com.read.dao.Results"%>
<%@ 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;
	
	//flag 통하여 조건문 수행
	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 board where seq = ? and password = ?";
		
		pstmt = conn.prepareStatement(sql);
		
		pstmt.setString(1, seq);
		pstmt.setString(2, password);
		
		//result = 0이면 비밀번호 오류, 1이면 정상 실행
		//내부적으로 seq password에 따라 delete 함
		//시스템적 오류 or 비밀번호 틀릴 시 오류 2가지 -> delete1.jsp로 돌아감
		// 정상 실행 -> 삭제 후 list1.jsp로 이동
		int result = pstmt.executeUpdate();
		
		//1이면 flag = 0(정상), 0이면 flag = 1(오류)
		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) try { pstmt.close(); } catch(SQLException e) {} 
		if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
	}
	
	//jsp코드로 자바스크립트로 만들기 위함
		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>");
	
	
%>


비밀번호 누르고 삭제버튼 클릭시 삭제 성공됨


8. 수정(modify1.jsp) 작업

  1. modify1.jsp 작업 후 (mail 분리 작업 주의)
  2. modift1_ok.jsp 작업
<%@page import="org.mariadb.jdbc.internal.com.read.dao.Results"%>
<%@ 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 board 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 {
				 //@ 중심으로 mail1 과 2를 분리
				 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) try { rs.close(); } catch(SQLException e) {} 
		if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
		if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
	}
%>
<!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>


수정 창 디자인 부분

8_2. modify1_ok.jsp 작업

<%@page import="org.mariadb.jdbc.internal.com.read.dao.Results"%>
<%@ 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 board 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 == 0) {
			flag = 1;
		}
		else 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) try { pstmt.close(); } catch(SQLException e) {} 
		if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
	}
	
	//jsp코드로 자바스크립트로 만들기 위함
			out.println("<script type='text/javascript'>");
			if(flag == 0) {
				out.println("alert('수정 성공')");
				//modify 창으로 가기
				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>");

수정 성공시, 창 뜨고 해당 글 창으로 돌아감


profile
끄적끄적

0개의 댓글