본문 바로가기
WEB Archive

[JSP] Web - Java - DB 연결, 회원 추가 액션처리 실습

by universedevelope 2024. 8. 22.

DBConn.java ▼▼▼

/* =================================
   DBConn.java
   - 데이터베이스 연결 전용 객체(Singleton)
   - 예외처리 : throws 
 ================================= */

package com.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConn
{
	private static Connection dbConn;
	
	public static Connection getConnection() throws SQLException, ClassNotFoundException
	{
		
		if (dbConn == null)
		{
			String url = "jdbc:oracle:thin:@localhost:1521:XE";
			String user = "scott";
			String pwd = "tiger";
			
			Class.forName("oracle.jdbc.driver.OracleDriver");
			dbConn = DriverManager.getConnection(url, user, pwd);
			
		}
		return dbConn;
		
	}
	
	public static Connection getConnection(String url, String user, String pwd) throws ClassNotFoundException, SQLException
	{
		if(dbConn==null)
		{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			dbConn = DriverManager.getConnection(url, user, pwd);
		}
		return dbConn;
	}
	
	public static void close() throws SQLException
	{
		if (dbConn!=null)
		{
			if (!dbConn.isClosed())
			{
				dbConn.close();
			}
			
		}
		dbConn = null;
	}
	
}

 

Test001.jsp ▼▼▼ DB 연결 테스트

<%@page import="java.sql.Connection"%>
<%@page import="com.util.DBConn"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%
	String str = "";
	
	try
	{
		Connection conn = DBConn.getConnection();
		
		if(conn != null)
			str += "데이터베이스 연결 성공~!!";
		
	}
	catch(Exception e)
	{
		//System.out.println(e.toString());
		str += e.toString();
	}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test001.jsp</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>

<div>
	<h1>데이터베이스 연결 실습</h1>
	<hr>
</div>

<div>
	<h2>연결 결과 : <%=str %></h2>
</div>
	

</body>
</html>

 

Test002.jsp ▼▼▼

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="com.util.DBConn"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%
	// 결과값 변수
	String str = "";

	// 데이터베이스 연결
	Connection conn = DBConn.getConnection();
	
	// 쿼리문 준비
	String sql = "SELECT SID, NAME, TEL FROM TBL_MEMBER ORDER BY SID";
	
	//작업객체 생성 및 준비된 쿼리문 실행
	Statement stmt = conn.createStatement();
	
	ResultSet rs = stmt.executeQuery(sql);
	
	// 결과 ResultSet 에 대한 처리 → 반복문 처리
	str += "<table class='table'>";
	str += "<tr>";
	str += "<th id='numTitle'>번호</th>";			
	str += "<th id='nameTitle'>이름</th>";			
	str += "<th id='telTitle'>전화번호</th>";			
	str += "</tr>";
	while(rs.next())
	{
		str+="<tr>";
		str += "<td class='list'>" + rs.getString("SID")+ "</td>";		
		str += "<td class='list'>" + rs.getString("NAME")+ "</td>";		
		str += "<td class='list'>" + rs.getString("TEL")+ "</td>";		
		str+="</tr>";
	}
			
	str += "</table>";
	rs.close();
	stmt.close();
	DBConn.close();

%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test002.jsp</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<style type="text/css">
	input{width: 200px;}
	button{width: 208px; height: 50px; font-weight: bold;}
	.errMsg{font-size: small; color: red; display: none;}
	#numTitle{width: 50px;}
	#nameTitle{width: 100px;}
	#telTitle{width: 160px;}
	.list{text-align: center;}
	
</style>
<script type="text/javascript">

	function formCheck()
	{
		// 확인
		alert("1!");
		var uName = document.getElementById("userName");
		var nErr = document.getElementById("nameErr");
		
		nErr.style.display = "none";
		
		if(uName.value=="")
		{
			nErr.style.display = "inline";
			return false;
		}
		
		return true;
	}
	
</script>

</head>
<body>

<div>
	<h1>데이터베이스 연결 및 데이터 처리</h1>
	<hr>
</div>

<div>
	<form action="MemberInsert.jsp" method="post" onsubmit="return formCheck()">
		<table>
			<tr>
				<th>이름(*)</th>
				<td>
					<input type="text" id="userName" name="userName" class="txt">
					<span class="errMsg" id="nameErr">이름을 입력해야합니다.</span>
				</td>
			</tr>
			<tr>
				<th>전화번호</th>
				<td>
					<input type="text" id="userTel" class="txt" name="userTel">
				</td>
			</tr>
			<tr>
				<th></th>
				<td>
					<button type="submit" id="btnAdd" class="btn">데이터추가</button>
				</td>
			</tr>
		</table>
	</form>
</div>
<br />
<br />

<div>
	<!-- 처리 결과 -->
	<%=str %>
</div>











</body>
</html>

MemberInsert.jsp ▼▼▼

<%@page import="java.sql.Statement"%>
<%@page import="com.util.DBConn"%>
<%@page import="java.sql.Connection"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%
	//MemberInsert.jsp
	//이전 페이지로부터(Test002.jsp) 데이터 수신
	//한글데이터 깨짐 방지
	request.setCharacterEncoding("UTF-8");
	String uName = request.getParameter("userName");
	String uTel = request.getParameter("userTel");
	
	// 데이터베이스 연결
	Connection conn = DBConn.getConnection();
	
	// 쿼리문 준비
	String sql = String.format("INSERT INTO TBL_MEMBER(SID, NAME, TEL)"
			                 + "VALUES(MEMBERSEQ.NEXTVAL, '%s', '%s')", uName, uTel);
	
	// DB액션 처리 작업객체 생성 및 쿼리문 수행
	Statement stmt = conn.createStatement();
	
	int result = 0;
	result = stmt.executeUpdate(sql);
	stmt.close();
	DBConn.close();
	
	if(result < 1)
	{
		// 내가 잘 아는 에러 페이지를 소개시켜줄게~
		response.sendRedirect("Error.jsp");
	}
	else
	{
		// 이 페이지로 오기 전에 네가 머물던 리스트 페이지 주소를 다시 요청해서 찾아가봐~
		// 네가 입력하려는 내용이 추가도니 상태로 리스트의 내용이 바뀌어 있을거야
		response.sendRedirect("Test002.jsp");
	}
		 
	
	
%>
728x90

댓글