다음 명령어를 cmd에서 실행해준다
- sqlplus system/1234
- create user [id] identified by [pw];
ex: create user jsp identified by jsp;- grant connect, resource to [id];
ex: grant connect, resource to jsp;
1) cmd
2) DBeaver
Oracle jdbc
오라클에서 제공하는 오라클 DB를 관리할 수 있도록 도와주는 JDBC이다.
Oracle DB를 사용해본 대부분 사람들의 PC에는
>> C:oraclexe:app:oracle:product:11.2.0:server:jdbc:lib
경로에 ojdbc6.jar 파일이 있다
앞선 JSP(2)에 소개했던 servlet.jar파일을 라이브러리에 추가하는 방법과 동일하게 ojdbc6.jar파일을 라이브러리에 추가해준다.
build Path도 동일하게 잡아주면 된다.
select 쿼리 실행 시 executeQuery() 메서드를 사용하여, 실행 결과로 java.sql.resultSet형으로 리턴
ResultSet 메서드
-> next()
-> getInt(int columnIndex)
: columnIndex 번째 컬럼의 값을 가지고 온다.
-> getString(String columnName)
: columnName 값을 가지고 온다.
!!!MemberBean (java) MemberBean member = new MemberBean(); (jsp) <jsp:userBean class="패키지명.MemberBean" id="member">
!!!setter() (java) member.setName("자바학생"); (jsp) <jsp:setProperty name="member"" property="name" value="자바학생"/>
!!!(getter()) (java) member.getName("자바학생"); (jsp) <jsp:getProperty name="member"" property="name"/>
<예제1>
! DB를 연동하여 테이블 값 불러오기
MemberDao.java
package com.codingbox.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.codingbox.vo.MemberBean;
public class MemberDao {
Connection conn;
PreparedStatement pstm;
ResultSet rs; // 전역변수 3개 선언
public int getAge(String name) {
String sql = "SELECT age FROM MEMBER WHERE name=?";
int age = 0;
try {
conn = DBconnection.getConnection();
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1, name);
ResultSet rs = pstm.executeQuery();
if( rs.next() ) {
age = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return age;
}
public ArrayList<MemberBean> selectAll(){
String sql = "SELECT * FROM MEMBER";
ArrayList<MemberBean> result = new ArrayList<>();
try {
conn = DBconnection.getConnection();
PreparedStatement pstm = conn.prepareStatement(sql);
ResultSet rs = pstm.executeQuery();
while(rs.next()) {
MemberBean member = new MemberBean();
member.setName(rs.getString(1) );
member.setAge(rs.getInt(2));
result.add(member);
}
// 여러 건 넘길 때는 ArrayList<>로 넘겨준다.
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
MemberBean.java - getter setter를 통해 값 불러오기
package com.codingbox.vo;
public class MemberBean {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
age_search.jsp - 초기화면
<%@ 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="age_db.jsp">
<label>이름
<input type="text" name="name"/><br>
</label>
<input type="submit" value="검색"/>
</form>
<input type="button" value="전체확인하기" onclick="selectAll();" />
<script>
function selectAll() {
location.href = "age_all.jsp";
}
</script>
</body>
</html>
age_db.jsp
<%@page import="com.codingbox.dao.MemberDao"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="com.codingbox.dao.DBconnection"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ 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>
<%
String name = request.getParameter("name");
MemberDao mdao = new MemberDao();
int age = mdao.getAge(name);
%>
<% if(age != 0){%>
이름 : <%=name %><br>
나이 : <%=age %><br>
<%} else { %>
찾는 이름이 없습니다.
<%} %>
<input type="button" value="다시 검색하기" onclick="location.href='age_search.jsp'">
</body>
</html>
DB에 값이 있는 경우
DB에 값이 없는 경우
age_all.jsp - DB의 모든 자료 불러오기
<%@page import="com.codingbox.vo.MemberBean"%>
<%@page import="java.util.ArrayList"%>
<%@ 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>
<jsp:useBean id="mdao" class="com.codingbox.dao.MemberDao" />
<%
ArrayList<MemberBean> result = mdao.selectAll();
%>
<table border="1">
<tr>
<th>이름</th>
<th>나이</th>
</tr>
<%for( MemberBean member : result ){ %>
<tr>
<td><%=member.getName() %></td>
<td><%=member.getAge() %></td>
</tr>
<%} %>
</table>
<input type="button" value="다시 검색하기" onclick="location.href='age_search.jsp'"/>
</body>
</html>
<예제2>
! 회원가입 폼 만들기
<%@ 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="join_db.jsp" name="joinForm" method="post">
<p id="text">사용할 수 있는 아이디입니다.</p>
<p>
<label>아이디
<input type="text" name="userid">
<input type="button" value="중복확인" onclick="">
</label>
</p>
<p>
<label>비밀번호
<input type="password" name="userpw">
</label>
</p>
<p>
<label>비밀번호 확인
<input type="password" name="userpw_re">
</label>
</p>
<p>
<label>이름
<input type="text" name="username">
</label>
</p>
<p>
<label>휴대폰번호
<input type="text" name="userphone">
</label>
</p>
<p>
우편번호
</p>
<p>
주소
</p>
<p>
상세 주소
</p>
<p>
참고 항목
</p>
<p>
<input type="button" value="가입완료" onclick="sendit()">
</p>
</form>
</body>
<script src="user.js"></script>
</html>
-> join_view.jsp 초기화면
function sendit(){
// 아이디 : "", 5자 이상, 16자 미만
// 비밀번호 : "", 8자 이상, 비밀번호 = 비밀번호 확인
// 이름 : ""
// 휴대폰번호 : ""
let frm = document.joinForm;
let userid = frm.userid;
let userpw = frm.userpw;
let userpw_re = frm.userpw_re;
let username = frm.username;
let userphone = frm.userphone;
if( userid.value == ""){
alert("아이디를 입력하세요");
userid.focus();
return false;
}
if( userid.value.length <= 4 || userid.value.length >= 16){
alert("아이디는 5~16자로 입력하세요");
userid.focus();
return false;
}
if( userpw.value == ""){
alert("비밀번호를 입력하세요");
userid.focus();
return false;
} else {
if( userpw.value.length < 8){
alert("비밀번호는 8자 이상으로 입력하세요");
userpw.focus();
return false;
}
}
if( userpw.value != userpw_re.value){
alert("비밀번호가 일치하지 않습니다");
userpw_re.focus();
return false;
}
if( username.value == ""){
alert("이름을 입력하세요");
username.focus();
return false;
}
if( userphone.value == ""){
alert("휴대폰 번호를 입력하세요");
userphone.focus();
return false;
}
frm.submit();
}
-> user.js validation check
유효성 검사
package com.codingbox.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.codingbox.vo.MemberBean;
public class MemberDao {
Connection conn;
PreparedStatement pstm;
ResultSet rs;
public boolean join(MemberBean member) {
String sql = "INSERT INTO TBL1_MEMBER VALUES (?, ?, ?, ?)";
int result = 0;
try {
conn = DBconnection.getConnection();
pstm = conn.prepareStatement(sql);
pstm.setString(1, member.getUserid());
pstm.setString(2, member.getUserpw());
pstm.setString(3, member.getUsername());
pstm.setString(4, member.getPhone());
result = pstm.executeUpdate();
if ( result != 0 ) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean login(String userid, String userpw) {
String sql = "SELECT * FROM TBL1_MEMBER tm "
+ "WHERE USERID = ?"
+ "AND USERPW = ?";
boolean result = false;
try {
conn = DBconnection.getConnection();
pstm = conn.prepareStatement(sql);
pstm.setString(1, userid);
pstm.setString(2, userpw);
rs = pstm.executeQuery();
if( rs.next() ) {
result = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
-> MemberDao.java
검색되는 값이 있으면 true로, 없으면 로직을 타고 그대로 false로 떨어진다.
package com.codingbox.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBconnection {
public static Connection getConnection() {
Connection conn = null;
try {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "jsp";
String password ="jsp";
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
System.out.println("드라이버 로딩 오류");
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("DB접속 오류");
e.printStackTrace();
} catch (Exception e) {
System.out.println("알 수 없는 에러");
e.printStackTrace();
}
return conn;
// 한 번에 이쪽으로 연결
}
}
-> DBConnection.java
DB연동 코드
<%@page import="com.codingbox.dao.MemberDao"%>
<%@ 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>
<jsp:useBean id="member" class="com.codingbox.vo.MemberBean" />
<jsp:setProperty property="*" name="member" />
<!-- 외부에서 전달된 name 속성과 필드의 이름이 같으면 value가 자동으로 세팅 -->
<%
MemberDao mdao = new MemberDao();
if(mdao.join(member)){
// 회원가입 성공
%>
<script>
alert("회원가입 성공");
location.href = "login_view.jsp";
</script>
<%} else{ // 회원가입 실패 %>
<script>
alert("회원가입 실패");
location.href = "join_view.jsp";
</script>
<%} %>
</body>
</html>
-> join_db.jsp
회원가입 성공시 login_view.jsp로 이동
회원가입 실패시 join_view.jsp 초기화면으로 이동
<%@ 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="Login_db.jsp" method="post" name="frm">
<p>
<label>
아이디 <input type="text" name="userid" />
</label>
</p>
<p>
<label>
패스워드 <input type="text" name="userpw" />
</label>
</p>
<input type="button" value="로그인" onclick="sendit();">
</form>
<script>
function sendit() {
let frm = document.frm;
// validation check
// ...
frm.submit();
}
</script>
</body>
</html>
-> login_view.jsp
join_view.jsp에서 회원가입을 성공하면 데이터 전송
<%@page import="com.codingbox.dao.MemberDao"%>
<%@ 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>
<%
MemberDao mdao = new MemberDao();
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw");
if(mdao.login(userid, userpw)){
// 로그인 성공
session.setAttribute("session_id", userid);
%>
<script>
location.href = "main_view.jsp";
</script>
<%} else { //로그인 실패 %>
<script>
alert("아이디 또는 패스워드를 확인해주세요");
location.href = "login_view.jsp";
</script>
<% } %>
</body>
</html>
-> login_db.jsp
id,pw를 파라미터로 받아와서
로그인 성공시 main_view.jsp로 이동
로그인 실패시 login_view.jsp로 이동
<%@ 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>
<%
String userid = (String)session.getAttribute("session_id");
if(userid != null){
%>
<script>
alert("<%= userid%>님 하이용");
</script>
<p>
<%= userid %>님 바이용<input type="button" value="로그아웃">
</p>
<%} else { %>
<script>
alert("로그인 후 이용하세요");
location.href = "login_view.jsp";
</script>
<% } %>
</body>
</html>
-> main_view.jsp
<%@ 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>
<%
session.removeAttribute("session_id");
//session.invalidate();
response.sendRedirect("login_view.jsp");
%>
</body>
</html>
-> logout_db.jsp
로그아웃, 세션값 다 비우기