JDBC를 활용하여 데이터베이스를 연동함.
create table member(
name varchar2(20) not null, //이름
id varchar2(20) not null, //아이디
pw varchar2(20) not null, //비밀번호
phone1 varchar2(20), //010
phone2 varchar2(20), //1234
phone3 varchar2(20), //5678
gender varchar2(20) //성별
);
<form action="JoinOk" method="post">
이름 : <input type="text" name="name" size="10"><br />
아이디 : <input type="text" name="id" size="10"><br />
비밀번호 : <input type="text" name="pw" size="10"><br />
전화번호 : <select name="phone1">
<option value="010">010</option>
<option value="016">016</option>
<option value="017">017</option>
<option value="018">018</option>
<option value="019">019</option>
<option value="011">011</option>
</select> -
<input type="text" name="phone2" size="5"> - <input type="text" name="phone3" size="5"> <br />
성별구분 : <input type="radio" name="gender" value="man">남 <input type="radio" name="gender" value="woman">여 <br />
<input type="submit" value="회원가입"> <input type="reset" value="취소">
</form>
private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("EUC-KR");
name = request.getParameter("name");
id = request.getParameter("id");
pw = request.getParameter("pw");
phone1 = request.getParameter("phone1");
phone2 = request.getParameter("phone2");
phone3 = request.getParameter("phone3");
gender = request.getParameter("gender");
String query = "insert into member values('" + name + "', '" + id + "', '" + pw + "', '" + phone1 + "', '" + phone2 + "', '"+ phone3 + "', '" + gender + "')";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl" , "members" , "m1234");
stmt = connection.createStatement();
int i = stmt.executeUpdate(query);
if(i == 1){
System.out.println("insert success");
response.sendRedirect("joinResult.jsp");
} else {
System.out.println("insert fail");
response.sendRedirect("join.html");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null) stmt.close();
if(connection != null) connection.close();
} catch (Exception e) {}
}
}
<body>
회원가입이 정상 처리 되었습니다.<br />
<a href="login.html">로그인</a>
</body>
<form action="LogInOk" method="post">
아이디 : <input type="text" name="id"><br />
비밀번호 : <input type="text" name="pw"><br />
<input type="submit" value="로그인">
</form>
private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
id = request.getParameter("id");
pw = request.getParameter("pw");
String query = "select * from member where id = '" + id + "' and pw = '" + pw + "'";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl" , "members" , "m1234");
stmt = connection.createStatement();
resultSet = stmt.executeQuery(query);
while (resultSet.next()) {
name = resultSet.getString("name");
id = resultSet.getString("id");
pw = resultSet.getString("pw");
phone1 = resultSet.getString("phone1");
phone2 = resultSet.getString("phone2");
phone3 = resultSet.getString("phone3");
gender = resultSet.getString("gender");
}
HttpSession httpSession = request.getSession();
httpSession.setAttribute("name", name);
httpSession.setAttribute("id", id);
httpSession.setAttribute("pw", pw);
response.sendRedirect("loginResult.jsp");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(resultSet != null) resultSet.close();
if(stmt != null) stmt.close();
if(connection != null) connection.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
<body>
<%
name = (String)session.getAttribute("name");
id = (String)session.getAttribute("id");
pw = (String)session.getAttribute("pw");
%>
<%= name %>님 안녕하세요 <br />
<a href="modify.jsp">회원정보 수정</a>
</body>
<body>
<%
id = (String)session.getAttribute("id");
String query = "select * from member where id = '" + id + "'";
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl" , "members" , "m1234");
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
while(resultSet.next()) {
name = resultSet.getString("name");
pw = resultSet.getString("pw");
phone1 = resultSet.getString("phone1");
phone2 = resultSet.getString("phone2");
phone3 = resultSet.getString("phone3");
gender = resultSet.getString("gender");
}
%>
<form action="ModifyOk" method="post">
이름 : <input type="text" name="name" size="10" value=<%=name %>><br />
아이디 : <%=id %><br />
비밀번호 : <input type="text" name="pw" size="10"><br />
전화번호 : <select name="phone1">
<option value="010">010</option>
<option value="016">016</option>
<option value="017">017</option>
<option value="018">018</option>
<option value="019">019</option>
<option value="011">011</option>
</select> -
<input type="text" name="phone2" size="5" value=<%=phone2 %>> - <input type="text" name="phone3" size="5" value=<%=phone3 %>> <br />
<%
if(gender.equals("man")) {
%>
성별구분 : <input type="radio" name="gender" value="man" checked="checked">남 <input type="radio" name="gender" value="woman">여 <br />
<%
} else {
%>
성별구분 : <input type="radio" name="gender" value="man" >남 <input type="radio" name="gender" value="woman" checked="checked">여 <br />
<%
}
%>
<input type="submit" value="정보수정"> <input type="reset" value="취소">
</form>
</body>
private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("EUC-KR");
httpSession = request.getSession();
name = request.getParameter("name");
id = request.getParameter("id");
pw = request.getParameter("pw");
phone1 = request.getParameter("phone1");
phone2 = request.getParameter("phone2");
phone3 = request.getParameter("phone3");
gender = request.getParameter("gender");
if(pwConfirm()){
System.out.println("OK");
String query = "update member set name ='" + name + "', phone1= '" + phone1 + "', phone2 = '" + phone2 + "', phone3 = '" + phone3 + "', gender = '" + gender + "'";
// System.out.println(query);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl" , "members" , "m1234");
stmt = connection.createStatement();
int i = stmt.executeUpdate(query);
if(i ==1 ){
System.out.println("update success");
httpSession.setAttribute("name", name);
response.sendRedirect("modifyResult.jsp");
} else {
System.out.println("update fail");
response.sendRedirect("modify.jsp");
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null) stmt.close();
if(connection != null) connection.close();
} catch (Exception e) {}
}
} else {
System.out.println("NG");
}
}
private boolean pwConfirm() {
boolean rs = false;
String sessionPw = (String)httpSession.getAttribute("pw");
if(sessionPw.equals(pw)) {
rs = true;
} else {
rs = false;
}
return rs;
}
<body>
<%= session.getAttribute("name") %>님의 회원정보 수정이 정상 처리 되었습니다.<br />
<a href="logout.jsp">로그아웃</a> <a href="modify.jsp">정보수정</a>
</body>
<body>
<%
session.invalidate();
response.sendRedirect("login.html");
%>
</body>
전체적인 흐름도
package com.javalec.daotoex;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class MemberDAO {
private String url = "jdbc:oracle:thin:@localhost:1521:xe";
private String uid = "scott";
private String upw = "tiger";
public MemberDAO() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<MemberDTO> memberSelect() {
ArrayList<MemberDTO> dtos = new ArrayList<MemberDTO>();
Connection con =null;
Statement stmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(url, uid, upw);
stmt = con.createStatement();
rs = stmt.executeQuery("select * from member");
while (rs.next()) {
String name = rs.getString("name");
String id = rs.getString("id");
String pw = rs.getString("pw");
String phone1 = rs.getString("phone1");
String phone2 = rs.getString("phone2");
String phone3 = rs.getString("phone3");
String gender = rs.getString("gender");
MemberDTO dto = new MemberDTO(name, id, pw, phone1, phone2, phone3, gender);
dtos.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return dtos;
}
}
package com.javalec.daotoex;
public class MemberDTO {
private String name;
private String id;
private String pw;
private String phone1;
private String phone2;
private String phone3;
private String gender;
public MemberDTO(String name, String id, String pw, String phone1, String phone2, String phone3, String gender) {
this.name = name;
this.id = id;
this.pw = pw;
this.phone1 = phone1;
this.phone2 = phone2;
this.phone3 = phone3;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public String getPhone1() {
return phone1;
}
public void setPhone1(String phone1) {
this.phone1 = phone1;
}
public String getPhone2() {
return phone2;
}
public void setPhone2(String phone2) {
this.phone2 = phone2;
}
public String getPhone3() {
return phone3;
}
public void setPhone3(String phone3) {
this.phone3 = phone3;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
Statement객체의 경우 중복코드가 많아지는 단점이 있다. 그걸 보완하기 위해 나온것이다.
예제 코드
<%
try{
Class.forName(driver);
connection = DriverManager.getConnection(url, uid, upw);
int n;
String query = "insert into memberforpre (id, pw, name, phone) values (?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, "abc");
preparedStatement.setString(2, "123");
preparedStatement.setString(3, "홍길동");
preparedStatement.setString(4, "010-1234-5678");
n = preparedStatement.executeUpdate();
preparedStatement.setString(1, "def");
preparedStatement.setString(2, "456");
preparedStatement.setString(3, "홍길자");
preparedStatement.setString(4, "010-9012-3456");
n = preparedStatement.executeUpdate();
if(n == 1) {
out.println("insert success");
} else {
out.println("insert fail");
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try{
if(resultSet != null) resultSet.close();
if(preparedStatement != null) preparedStatement.close();
if(connection != null) connection.close();
} catch(Exception e){}
}
%>
<br />
<a href="memberDateView.jsp">회원정보 보기</a>
클라이언트에서 다수의 요청이 발생하면 DB에 부하가 발생한다. 이런 문제를 해결하기 위해서 커넥션 풀 기법을 사용한다.
tomcat 컨테이너가 DB인증을 하도록 context.xml 파일을 열어 코드를 추가해야 한다.
<Resource
auth = "Container"
driverClassName = "oracle.jdbc.driver.OracleDriver"
url = "jdbc.oracle.thin:@localhost:1521:orcl"
username = "scott"
password = "tiger"
name = "jdbc/Oracle11g"
type = "javax.sql.DataSource"
maxActive = "50"
maxWait = "1000"
/>
사용하는 법
//연결에 필요했던 driver, userid, userpw와 같은 변수가 커넥션 풀에
//저장이 되있기 때문에 변수하나로 대신할 수 있다.
private DataSource dataSource;
Context context = new InitialContext();
dataSource = (DataSource)context.lookup("java:comp/env/jdbc/Oracle11g");
con = dataSource.getConnection();