※실무에서도 DAO와 자바빈은 무조건 생성하게 된다. 중요하다.
Java Resources/src/com.dao/MemberDao.java
package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import javax.naming.Context; import javax.naming.InitialContext; import com.domain.Member; public class MemberDao { /* @싱글턴 패턴 생성자의 접근지정자는 private으로 지정 static한 getInstance()를 메소드를 사용 객체의 주소를 보관하는 static 참조변수 사용 //참조변수 instance에 객체 주소할당 //객체를 한번생성해서 계속가지고있슴 (변경에관한게 아무것도없슴) 객체를 하나만 생성해서 공유하고자 싱글턴 패턴 구현 @멤버변수가 있는 경우에는 절대로 싱글턴 패턴을 구현하면 안된다. //멤버변수를 공유시켜버리면 여러사용자가 멤버변수를 같이 변경하게됨 */ private static MemberDao instance =new MemberDao(); public static MemberDao getInstance(){ return instance; } //생성자 인데 private 외부에서는 생성못하게 막아둔거 //메소드를 static 하게만들어 메서드를 이용해서 //Member.getInstance(); private MemberDao(){ } //커네션풀로 부터 커넥션을 할당 받는 메소드 private Connection getConnection() throws Exception{ Context initCtx= new InitialContext(); Context envCtx=(Context)initCtx.lookup("java:comp/env"); DataSource ds=(DataSource)envCtx.lookup("jdbc/orcl"); return ds.getConnection(); } //회원가입 public void insertMember(Member member)throws Exception{ Connection conn= null; PreparedStatement pstmt = null; String sql=""; int cnt = 0; try{ //커넥션 풀로 부터 커넥션 할당 conn= getConnection(); sql ="insert into MEMBER values(?,?,?,?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(++cnt, member.getId()); pstmt.setString(++cnt, member.getPasswd()); pstmt.setString(++cnt, member.getName()); pstmt.setString(++cnt, member.getJumin1()); pstmt.setString(++cnt, member.getJumin2()); pstmt.setString(++cnt, member.getEmail()); pstmt.setString(++cnt, member.getBlog()); pstmt.setTimestamp(++cnt, member.getReg_date()); pstmt.executeUpdate(); }catch(Exception e){ e.printStackTrace(); }finally{ execClose(null,pstmt,conn); } } //회원 아이디 , 비밀번호 체크 public int userCheck(String id, String passwd)throws Exception{ Connection conn= null; PreparedStatement pstmt = null; ResultSet rs =null; String sql=""; String dbpasswd=""; int x = -1; try{ conn =getConnection(); sql ="select passwd from MEMBER where id = ?"; pstmt =conn.prepareStatement(sql); pstmt.setString(1, id); rs=pstmt.executeQuery(); if(rs.next()){ dbpasswd =rs.getString("passwd"); if(dbpasswd.equals(passwd)) x=1; //인증성공 else x=0; //비밀번호 틀림 }else x=-1; //해당 아이디 없음 }catch(Exception e){ e.printStackTrace(); }finally{ execClose(rs,pstmt,conn); } return x; } //회원 상세정보 public Member getMember(String id)throws Exception{ Connection conn =null; PreparedStatement pstmt = null; ResultSet rs = null; Member member=null; String sql=""; try{ conn=getConnection(); sql="select * from MEMBER where id= ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); rs= pstmt.executeQuery(); if(rs.next()){ member=new Member(); member.setId(rs.getString("id")); member.setPasswd(rs.getString("passwd")); member.setName(rs.getString("name")); member.setJumin1(rs.getString("jumin1")); member.setJumin2(rs.getString("jumin2")); member.setEmail(rs.getString("email")); member.setBlog(rs.getString("blog")); member.setReg_date(rs.getTimestamp("reg_date")); } }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(rs,pstmt,conn); } return member; } //회원정보 수정 public void updateMember(Member member)throws Exception{ Connection conn=null; PreparedStatement pstmt =null; String sql = null; int cnt =0; try{ conn =getConnection(); sql = "update MEMBER set passwd=?,name=?,email=?, blog=? where id=?"; pstmt =conn.prepareStatement(sql); pstmt.setString(++cnt, member.getPasswd()); pstmt.setString(++cnt, member.getName()); pstmt.setString(++cnt, member.getEmail()); pstmt.setString(++cnt, member.getBlog()); pstmt.setString(++cnt, member.getId()); pstmt.executeUpdate(); }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(null,pstmt,conn); } } //회원탈퇴 , 회원정보 삭제 public void deleteMember(String id)throws Exception{ Connection conn=null; PreparedStatement pstmt =null; String sql = null; try{ conn =getConnection(); sql = "delete from MEMBER where id=?"; pstmt =conn.prepareStatement(sql); pstmt.setString(1, id); pstmt.executeUpdate(); }catch(Exception e){ e.printStackTrace(); }finally{ execClose(null,pstmt,conn); } } //ID 중복 체크 public int confirmId(String id)throws Exception{ Connection conn =null; PreparedStatement pstmt = null; ResultSet rs = null; String sql=""; int x=-1; try{ conn=getConnection(); sql="select * from MEMBER where id= ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); rs= pstmt.executeQuery(); if(rs.next()) x=1; //해당아이디 있음 else x=-1;//해당아이디 없음 }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(rs,pstmt,conn); } return x; } //자원 정리를 위한 메소드 //계란노른자 //Connection 를통해서 PreparedStatement 를생성하고 //PreparedStatement 를 통해서 ResultSet 를 생성하기때문에 //종료할때는 ResultSet=>PreparedStatement=>Connection 와같이 생성순서의 역순으로 close 해줘야한다 public void execClose(ResultSet rs, PreparedStatement pstmt, Connection conn)throws Exception{ //자원정리 if(rs !=null) try{rs.close();}catch(SQLException sqle){} if(pstmt !=null) try{pstmt.close();}catch(SQLException sqle){} //커넥션 풀로 반납 if(conn !=null) try{conn.close();}catch(SQLException sqle){} } }
Java Resources/src/com.domain/Member.java
자바빈 : getter setter 이클립스 기능으로 생성
package com.domain; import java.sql.Timestamp; //자바빈 public class Member { //프로퍼티 private String id; private String passwd; private String name; private String jumin1; private String jumin2; private String email; private String blog; private Timestamp reg_date; //getter public String getId() { return id; } //setter public void setId(String id) { this.id = id; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJumin1() { return jumin1; } public void setJumin1(String jumin1) { this.jumin1 = jumin1; } public String getJumin2() { return jumin2; } public void setJumin2(String jumin2) { this.jumin2 = jumin2; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBlog() { return blog; } public void setBlog(String blog) { this.blog = blog; } public Timestamp getReg_date() { return reg_date; } public void setReg_date(Timestamp reg_date) { this.reg_date = reg_date; } @Override public String toString() { return "Member [id=" + id + ", passwd=" + passwd + ", name=" + name + ", jumin1=" + jumin1 + ", jumin2=" + jumin2 + ", email=" + email + ", blog=" + blog + ", reg_date=" + reg_date + "]"; } }
WebContent/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?> <Context> <!-- maxActive="20" //최대 커넥션 수 maxIdle="10" //미리 만들어둘 기본커낵션 수 --> <Resource name="jdbc/orcl" auth="container" type="javax.sql.DataSource" username="hr" password="hr" driverClassName="oracle.jdbc.driver.OracleDriver" factory="org.apache.commons.dbcp.BasicDataSourceFactory" url="jdbc:oracle:thin:@localhost:1521:orcl" maxActive="20" maxIdle="10" /> </Context>
WebContent/view/confirmId.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import = "com.dao.MemberDao" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>ID 중복확인</title> <link href="style.css" rel="stylesheet" type="text/css"> </head> <% request.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); MemberDao manager = MemberDao.getInstance(); int check= manager.confirmId(id); %> <body> <% if(check == 1) { %> <table width="270" border="0" cellspacing="0" cellpadding="5"> <tr> <td height="39" ><%=id%>이미 사용중인 아이디입니다.</td> </tr> </table> <form name="checkForm" method="post" action="confirmId.jsp"> <table width="270" border="0" cellspacing="0" cellpadding="5"> <tr> <td align="center"> 다른 아이디를 선택하세요.<p> <input type="text" size="10" maxlength="12" name="id"> <input type="submit" value="ID중복확인"> </td> </tr> </table> </form> <% } else { %> <table width="270" border="0" cellspacing="0" cellpadding="5"> <tr> <td align="center"> <p>입력하신 <%=id%> 는 사용하실 수 있는 ID입니다. </p> <input type="button" value="닫기" onclick="setid()"> </td> </tr> </table> <% } %> </body> </html> <script type="text/javascript"> <!-- function setid() { opener.document.userinput.id.value="<%=id%>"; self.close(); } //--> </script>
WebContent/view/deletePro.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% if(session.getAttribute("memId") == null){ response.sendRedirect("main.jsp"); }else{ %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>회원탈퇴</title> </head> <body> <form name="myform" action="deletePro.jsp" method="post"> 아이디 : <input type=password name="id" size="15" maxlength="12"><br/> 비밀번호 : <input type=password name="passwd" size="15" maxlength="12"><br/> <input type=submit value="회원탈퇴"> <input type="button" value="취 소" onclick="location.href='main.jsp'"> </form> </body> </html> <%}%>
WebContent/view/deleteForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import ="com.dao.MemberDao" %> <% //로그인이 되었이어야 보여지도록 검증 if(session.getAttribute("memId")==null){ response.sendRedirect("main.jsp"); }else{ %> <% String id =request.getParameter("id"); String passwd = request.getParameter("passwd"); MemberDao manager = MemberDao.getInstance(); int check= manager.userCheck(id, passwd); if(check==1){ manager.deleteMember(id); session.invalidate(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>회원 탈퇴</title> </head> <body> <h4>회원 정보 삭제</h4> <div align="center"> 회원정보가 삭제되었습니다.<br/> <input type= "button" value="확인" onClick="location.href='main.jsp'"> </div> </body> </html> <%}else{%> <!-- 무엇이 틀렸는지 안알려준다 보안! --> <script> alert("id 또는 비밀번호가 맞지 않습니다."); history.go(-1); </script> <%}}%>
WebContent/view/inputForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>회원가입</title> <script type="text/javascript"> /* 하나라도 걸리면 경고창과 포커스를 처리한후 false를 반환한다. */ function checkIt(){ var userinput=document.userinput; if(!userinput.id.value){ alert("ID를 입력하세요"); userinput.id.focus(); return false; } if(!userinput.passwd.value){ alert("비밀번호를 입력하세요"); userinput.passwd.focus(); return false; } /* if(userinput.passwd.value != userinput.passwd2.value){ alert("비밀번호를 동일하게 입력하세요"); userinput.passwd2.focus(); return false; } 우리는 비번한개*/ if(!userinput.name.value){ alert("사용자 이름을 입력하세요"); userinput.name.focus(); return false; } if(!userinput.jumin1.value){ alert("주민등록번호를 입력하세요"); userinput.jumin1.focus(); return false; } if(!userinput.jumin2.value){ alert("주민등록번호를 입력하세요"); userinput.jumin2.focus(); return false; } return true; } //아이디 중복 여부를 판단 function openConfirmid(userinput){ //아이디를 입력했는지 검사 if(userinput.id.value==""){ alert("아이디를입력하세요"); userinput.id.focus(); return; } //url과 사용자 입력 id를 조합합니다. url="confirmId.jsp?id="+userinput.id.value; //새로운 윈도우를 엽니다. open(url,"confirm","toolbar=no,location=no,status=no,menubar=no,scrllbar=no,resizable=no,width=300,height=200"); } </script> </head> <body> <table align="center"> <tr><td> <!-- onSubmit="return checkIt()" : checkIt() 리턴값이 true면 Submit을 실행 false면 실행안함(자바스크립트에서경고창 포커스처리) --> <form method="post" action="inputPro.jsp" name="userinput" onSubmit="return checkIt()"> 사용자 ID : <input type="text" name ="id" size="10" maxlength="12"> <input type="button" name="confirm_id" value="ID중복확인" onClick="openConfirmid(this.form)"><br/> 비밀번호 : <input type="password" name ="passwd" size="15" maxlength="12"><br/> 사용자이름 : <input type="text" name ="name" size="15" maxlength="10"><br/> 주민등록번호 : <input type="text" name ="jumin1" size="7" maxlength="6"> - <input type="text" name ="jumin2" size="7" maxlength="7"><br/> E-Mail : <input type="text" name ="email" size="40" maxlength="30"><br/> Blog : <input type="text" name ="blog" size="60" maxlength="50"><br/> <input type="submit" value="등 록"> <input type="reset" value="다시 입력"> </form> </td></tr> </table> </body> </html>
WebContent/view/inputPro.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import ="com.dao.MemberDao" %> <%@ page import ="java.sql.Timestamp" %> <% request.setCharacterEncoding("utf-8"); %> <jsp:useBean id="member" class="com.domain.Member"> <jsp:setProperty name ="member" property="*"/> </jsp:useBean> <% member.setReg_date(new Timestamp(System.currentTimeMillis())); MemberDao manager = MemberDao.getInstance(); manager.insertMember(member); %> <script> alert("축하"); location.href="main.jsp"; </script>
WebContent/view/login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% //로그인이 되었이어야 보여지도록 검증 if(session.getAttribute("memId") == null){ response.sendRedirect("main.jsp"); }else{ %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>메인입니다..</title> </head> <body> <table width="500" cellpadding="0" cellspacing="0" align="center" border="1" > <tr> <td width="300" height="20">하하하</td> <td rowspan="3" align="center"> <%=session.getAttribute("memId")%>님이 <br> 방문하셨습니다 <form method="post" action="logout.jsp"> <input type="submit" value="로그아웃"> <!-- javascript:window.location='modifyForm.jsp' => location.href--> <input type="button" value="회원정보변경" onclick="location.href='modifyForm.jsp'"> <input type="button" value="회원탈퇴" onclick="location.href='deleteForm.jsp'"> </form> </td> </tr> <tr > <td rowspan="2" width="300" >메인입니다.</td> </tr> </table> </body> </html> <%}%>
WebContent/view/loginForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>로그인</title> </head> <body> <h3>회원로그인</h3> <form action="loginPro.jsp" method="post"> 아이디 : <input type="text" name="id" size="15" maxlength="12"><br/> 비밀번호 : <input type="password" name="passwd" size="15" maxlength="12"><br/> <input type=submit value="로그인"> <input type=reset value="다시입력"> <input type="button" value="회원가입" onclick="location.href='inputForm.jsp'"> </form> </body> </html>
WebContent/view/loginPro.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import ="com.dao.MemberDao" %> <% request.setCharacterEncoding("utf-8"); String id =request.getParameter("id"); String passwd =request.getParameter("passwd"); MemberDao manager =MemberDao.getInstance(); int check=manager.userCheck(id, passwd); //userCheck에서 x를 return 받아서 로긴체크 //history.go(-1); : 전페이지로 (입력창) if(check==1){ //로그인 성공 session.setAttribute("memId",id); response.sendRedirect("main.jsp"); }else if(check==0){ %> <script> alert("비밀번호가 맞지 않습니다."); history.go(-1); </script> <%}else{ %> <script> alert("아이디가 맞지 않습니다."); history.go(-1); </script> <%} %>
WebContent/view/logout.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% session.invalidate(); response.sendRedirect("main.jsp"); %>
WebContent/view/main.jsp
<%@ page contentType="text/html; charset=UTF-8"%> <% if(session.getAttribute("memId")==null){%> <jsp:forward page="loginForm.jsp" /> <%}else{%> <jsp:forward page="login.jsp" /> <%} %>
WebContent/view/modifyForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import ="com.dao.MemberDao,com.domain.Member" %> <% //로그인 체크 if(session.getAttribute("memId")==null){ response.sendRedirect("main.jsp"); }else{ %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>회원 정보 수정</title> </head> <% String memId =(String)session.getAttribute("memId"); MemberDao manager= MemberDao.getInstance(); Member c = manager.getMember(memId); //Email Blog null값일때 공백처리 if(c.getEmail()==null){ c.setEmail(""); } if(c.getBlog()==null){ c.setBlog(""); } %> <body> <form method="post" action="modifyPro.jsp" name="userinput"> <h3>회원정보 수정</h3> 사용자ID : <%=c.getId() %><br/> 비밀번호 : <input type="password" name="passwd" size="10" maxlength="10" value="<%=c.getPasswd()%>"><br/> 사용이름 : <input type="text" name="name" size="15" maxlength="20" value="<%=c.getName()%>"><br/> 주민등록번호 : <%=c.getJumin1() %>-<%=c.getJumin2()%><br/> E-Mail : <input type ="text" name ="email" size="40" maxlength="30" value="<%=c.getEmail() %>"><br/> Blog : <input type ="text" name ="blog" size="60" maxlength="50" value="<%= c.getBlog() %>"><br/> <input type="submit" name="modify" value="수 정"> <input type="button" value="취 소" onclick="location.href='main.jsp'"> </form> </body> </html> <%}%>
WebContent/view/modifyPro.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="com.dao.MemberDao" %> <% if(session.getAttribute("memId")==null){ response.sendRedirect("main.jsp"); }else{ request.setCharacterEncoding("utf-8"); %> <jsp:useBean id="member" class="com.domain.Member"> <jsp:setProperty name="member" property="*"/> </jsp:useBean> <% member.setId((String)session.getAttribute("memId")); MemberDao manager = MemberDao.getInstance(); manager.updateMember(member); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Refresh" content="5; url=main.jsp; charset=UTF-8"> <title>회원정보 수정</title> </head> <body> <h3>회원정보 수정</h3> <div align="center">회원정보가 정상적으로 수정되었습니다</div> </body> </html> <%}%>
WebContent/WEB-INF/lib
commons-collections-3.1.jar / commons-dbcp-1.2.1.jar / commons-pool-1.2.jar
회원가입,로그인 테스트
입력폼 : inputForm.jsp 정보입력
등록 : inputPro.jsp 알림창
Oracle SQL Developer : 등록확인
로그인 테스트 : main.jsp (loginForm.jsp)
로그인 성공 login.jsp //로그아웃 버튼누르면 다시 main.jsp
회원탈퇴 삭제 테스트
회원탈퇴폼 deleteForm.jsp
회원삭제 deletePro.jsp
삭제후 메인페이지 main.jsp(loginForm.jsp)
회원정보 수정테스트
회원정보 수정 폼 modifyForm.jsp
변경전
수정값입력 후 수정
수정완료 : modifyPro.jsp
변경확인
5초후 리플레쉬 대면서 메인으로 이동
회원가입 빈칸체크 modifyForm.jsp ->modifyPro.jsp -> MemberDao
아이디 중복체크 inputForm.jsp -> confirmId.jsp ->MemberDao
'JSP > 기본(Oracle)' 카테고리의 다른 글
파일업로드 라이브러리: cos , 자카르타 (0) | 2012.06.20 |
---|---|
JSP 방명록 (0) | 2012.06.20 |
커넥션 풀 (Connection Pool : 저장소역활) (0) | 2012.06.20 |
JDBC프로그램의 일반적인 실행 순서, DB생성 (0) | 2012.06.20 |
DB에 데이터 insert select update delete 하기 (0) | 2012.06.20 |