지구정복

[JSP] 12/23 | 게시판 만들기, 이모티콘 추가된 게시판 만들기 본문

데이터 엔지니어링 정복/JAVA & JSP

[JSP] 12/23 | 게시판 만들기, 이모티콘 추가된 게시판 만들기

eeaarrtthh 2020. 12. 23. 19:08
728x90
반응형

ㅇ게시판 만들기

먼저 기본 디자인은 아래의 디자인을 이용한다.

board.zip
0.21MB

 

 

 

먼저 DB를 만든다.

--데이터베이스 및 사용자 만들기
create database project;

create user project identified by '123456';

grant all privileges on project.* to project;

exit;

mysql -u project -p project
123456

--테이블 만들고 데이터 집어넣기
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),
hit int not null,
wip varchar(15) not null,
wdate datetime not null
);

 

다음으로 context.xml과 mariaDB의 jdbc를 이클립스 폴더 안에 넣는다. 아래와 같다.

<?xml version="1.0" encoding="utf-8" ?>
<Context>
	<Resource
		name = "jdbc/mariadb2"
		auth = "Container"
		type = "javax.sql.DataSource"
		driverClassName = "org.mariadb.jdbc.Driver"
		url = "jdbc:mysql://localhost:3307/project"
		username = "project"
		password = "123456"
	/>
</Context>

 

먼저 아래와 같이 design_simple0 폴더를 복사해서 sample1이란 폴더를 만든다.

그리고 데이터베이스와 연결이 되는 밑줄 친 3개의 페이지를 만들어준다.

 

다음 board_write1에서 아래와 같이 코딩한다.

<%@ 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_write.css">

<script type="text/javascript">
	window.onload = function() {
		document.getElementById( 'submit1' ).onclick = function() {
			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_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" 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>
				</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="submit1" value="쓰기" class="btn_write btn_txt01" style="cursor: pointer;" />
				</div>
			</div>
			<!--//게시판-->
		</div>
	</form>
</div>
<!-- 하단 디자인 -->

</body>
</html>

 

이제 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" );
	String wip = request.getRemoteAddr();

	Connection conn = null;
	PreparedStatement pstmt = null;
	
	//정상처리인지 비정상처리인지를 구분하는 변수 -> 결과를 한 군데에서 통합처리하기 위한 변수
	int flag = 1;
	
	try {
		//커넥션 풀로 DB에 연결하기
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
		DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb2" );
		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;
		}
	} catch(NamingException e) {
		System.out.println( "error: " + e.getMessage() );
	} catch(SQLException e) {
		System.out.println( "error: " + 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> " );
	

%>

 

이제 board_list1를 코딩한다.

-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;
	int totalRecord = 0;
	
	StringBuffer sbHtml = new StringBuffer();
	
	try {
		//커넥션 풀로 DB에 연결하기
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
		DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb2" );
		conn = dataSource.getConnection();
		
		String sql = "select seq, subject, writer, date_format(wdate, '%Y-%m-%d') wdate, hit from 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();
		
		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> " );
			sbHtml.append( "	<td class='left'><a href='board_view1.jsp?seq=" + seq + "'>" + subject + "</a>&nbsp;<img src='../../images/icon_hot.gif' alt='HOT'></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( "error: " + e.getMessage() );
	} catch(SQLException e) {
		System.out.println( "error: " + 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">총 <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 %>
			<!-- 행 시작  -->
			<!-- 
			<tr>
				<td>&nbsp;</td>
				<td>1</td>
				<td class="left"><a href="board_view1.jsp">adfas</a>&nbsp;<img src="../../images/icon_hot.gif" alt="HOT"></td>
				<td>asdfa</td>
				<td>2017-01-31</td>
				<td>6</td>
				<td>&nbsp;</td>
			</tr>
			 -->
			<!-- 행 끝 -->
			</table>
		</div>	
		<!--//게시판-->

		<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>
<!--//하단 디자인 -->

</body>
</html>

 

이제 board_view1.jsp를 코딩하는데 이때 글번호를 링크형식으로 가지고 가야한다.

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

<%
	request.setCharacterEncoding( "utf-8" );
	
	String seq = request.getParameter( "seq" );
	String subject = "";
	String writer = "";
	String mail = "";
	String wip = "";
	String wdate = "";
	String hit = "";
	String content = "";
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	try {
		//커넥션 풀로 DB에 연결하기
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
		DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb2" );
		conn = dataSource.getConnection();
		
		//board_view.jsp에 들어오면 조회수 증가를 위한 update문을 사용한다.
		String sql = "update board1 set hit = hit+1 where seq = ?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString( 1, seq );
		rs = pstmt.executeQuery();
		
		sql = "select subject, writer, mail, wip, wdate, hit, content from board1 where seq = ?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString( 1, seq );
		rs = pstmt.executeQuery();
		
		//데이터를 하나만 가져오니깐 while문 대신 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" ).replaceAll( "\n", "<br>");
		}

		
	} catch(NamingException e) {
		System.out.println( "error: " + e.getMessage() );
	} catch(SQLException e) {
		System.out.println( "error: " + 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 %>)(<%= 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>

 

이제 board_delete1.jsp를 코딩한다.

-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.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 {
		//커넥션 풀로 DB에 연결하기
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
		DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb2" );
		conn = dataSource.getConnection();
		
		String sql = "select subject, writer from board1 where seq = ?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString( 1, seq );
		rs = pstmt.executeQuery();
		
		//데이터를 하나만 가져오니깐 while문 대신 if문을 사용한다.
		if ( rs.next() ) {
			subject = rs.getString( "subject" );
			writer = rs.getString( "writer" );
		}

		
	} catch(NamingException e) {
		System.out.println( "error: " + e.getMessage() );
	} catch(SQLException e) {
		System.out.println( "error: " + 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.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">
		<input type="hidden" name="seq" value="<%= seq %>">
		<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">
					<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="submit1" value="삭제" class="btn_write btn_txt01" style="cursor: pointer;" />
				</div>
			</div>
			<!--//게시판-->
		</div>
	</form>
</div>
<!-- 하단 디자인 -->

</body>
</html>

 

다음으로 board_delete1_ok.jsp를 코딩한다.

- 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" );
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	
	//정상처리인지 비정상처리인지를 구분하는 변수 -> 결과를 한 군데에서 통합처리하기 위한 변수
	int flag = 2;
	
	try {
		//커넥션 풀로 DB에 연결하기
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
		DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb2" );
		conn = dataSource.getConnection();
		
		//개인의 비밀번호는 db안쪽에서 검색되도록 해야 한다.
		String sql = "delete from board1 where seq = ? and password = ?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString( 1, seq );
		pstmt.setString( 2, password );
		
		int result = pstmt.executeUpdate();
		
		//seq는 정상적으로 알아서 잘 넘어가기때문에 비밀번호 오류만 잡아준다.
		if ( result == 0 ) {
			//result 0일 때는 비밀번호 오류
			flag = 1;
		} else if ( result == 1 ) {
			//정상일 때
			flag = 0;
		}
	} catch(NamingException e) {
		System.out.println( "error: " + e.getMessage() );
	} catch(SQLException e) {
		System.out.println( "error: " + 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(); " );
	} else {
		out.println( " alert('글삭제에 실패했습니다.'); " );
		out.println( " history.back(); " );
	}
	out.println( " </script> " );
	
%>

 

이번에는 수정페이지를 바꿔주자

-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" );
	
	String writer = "";
	String subject = "";
	String content = "";
	String mail1 = "";
	String mail2 = "";
	//String mail[] = null;
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	try {
		//커넥션 풀로 DB에 연결하기
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
		DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb2" );
		conn = dataSource.getConnection();
		
		String sql = "select writer, subject, content, if(mail is not null, substr(mail, 1, instr(mail, '@')-1), '' ) as mail1, if(mail is not null, substr(mail, instr(mail, '@')+1 , length(mail) ), '' ) as mail2  from board1 where seq = ?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString( 1, seq );
		rs = pstmt.executeQuery();
		
		//데이터를 하나만 가져오니깐 while문 대신 if문을 사용한다.
		if ( rs.next() ) {
			subject = rs.getString( "subject" );
			writer = rs.getString( "writer" );
			content = rs.getString( "content" );
			//mail 배열일때 코드
			/*
			if ( rs.getString("mail").equals("") ) {
				mail = new String[] {"", ""};
			} else {
				mail = rs.getString( "mail" ).split("@");
			}
			*/
			mail1 = rs.getString( "mail1" );
			mail2 = rs.getString( "mail2" );
		}

		
	} catch(NamingException e) {
		System.out.println( "error: " + e.getMessage() );
	} catch(SQLException e) {
		System.out.println( "error: " + 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( 'submit2' ).onclick = function() {
 			if ( document.mfrm.subject.value.trim() == '' ) {
 				alert( '제목을 입력해주세요' );
 				return false;
 			}
 			if ( document.mfrm.password.value.trim() == '' ) {
 				alert( '비밀번호를 입력해주세요' );
 				return false;
 			}
 			if ( document.mfrm.content.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" 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="<%= mail1 %>" class="board_view_input_mail"/> @ <input type="text" name="mail2" value="<%= mail2 %>" 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="submit2" 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 password = request.getParameter( "password" );
	String subject = request.getParameter( "subject" );
	String content = request.getParameter( "content" );
	String mail = "";
	if ( !request.getParameter( "mail1" ).equals("") && !request.getParameter( "mail2" ).equals("") ) {
		mail = request.getParameter( "mail1" ) + "@" + request.getParameter( "mail2" );
	}
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	
	//정상처리인지 비정상처리인지를 구분하는 변수 -> 결과를 한 군데에서 통합처리하기 위한 변수
	int flag = 2;
	
	try {
		//커넥션 풀로 DB에 연결하기
		Context initCtx = new InitialContext();
		Context envCtx = (Context)initCtx.lookup( "java:comp/env" );
		DataSource dataSource = (DataSource)envCtx.lookup( "jdbc/mariadb2" );
		conn = dataSource.getConnection();
		
		//개인의 비밀번호는 db안쪽에서 검색되도록 해야 한다.
		String sql = "update board1 set subject = ?, content = ?, mail = ? where seq = ? and password = ?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString( 1, subject );
		pstmt.setString( 2, content );
		pstmt.setString( 3, mail );
		pstmt.setString( 4, seq );
		pstmt.setString( 5, password );
		
		int result = pstmt.executeUpdate();
		
		//seq는 정상적으로 알아서 잘 넘어가기때문에 비밀번호 오류만 잡아준다.
		if ( result == 0 ) {
			//result 0일 때는 비밀번호 오류
			flag = 1;
		} else if ( result == 1 ) {
			//정상일 때
			flag = 0;
		}
		
	} catch(NamingException e) {
		System.out.println( "error: " + e.getMessage() );
	} catch(SQLException e) {
		System.out.println( "error: " + 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_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> " );
	
%>

 

실습) 이번에는 이모티콘이 추가된 게시판을 만들어보자.

-데이터베이스 테이블 

create table board2 (
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
);

 

-디자인 파일

design_emoticon0.zip
0.01MB

 

 

 

 

-내 코드

sample2.zip
0.01MB

 

728x90
반응형
Comments