반응형

회원가입 페이지 만들기

 

회원가입을 구현하기 위해 다음에 나오는 준비 작업을 먼저 완료한다.

< 준비작업 >

1.  회원가입에 필요한 데이터베이스 생성

2. 간단한 디자인을 위한 CSS작성(선택 사항)

 

먼저 데이터베이스 테이블을 생성

 

회원정보 데이터베이스 스키마

1
2
3
4
5
6
7
8
create table "MEMBER" (
    "ID"         varchar2(12not null,
    "PASS"       varchar2(12not null,
    "EMAIL"      varchar2(30not null,
    "REGDATE"      timestamp,
    constraint  "MEMBER_PK" primary key ("ID")
)
 
cs



다음으로 화면을 꾸며줄 css파일을 작성해둔다.

- 간단한 css파일 생성

/WebContent/memberone/css/style.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@CHARSET "UTF-8";
body{
    background-color:#d1d3fc;
    font-size:15px;
    color: #ce16e9;
    text-align: center;
}
a:link {
    text-decoration:nonecolor:#696969;
}
a:hover{
    text-decoration:yescolor:#66ccff;
}
a:visited {
    text-decoration:noncolor:#330066;
}
 
cs

회원가입 실습 준비 완료!


1.     로그인 화면 만들기
/WebContent/memberone/login.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<%-- 로그인 폼 --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Login</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<link href="css/loginstyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<section>
    <article class="login">
        <form method="post" action="#">
            <table class="loginTable">
                <tr>
                    <th colspan="2">회원 로그인</th
                </tr>
                <tr>
                    <td><input type="text" class="id" name="id" placeholder="아이디 입력"/></td>
                </tr>
                <tr>
                    <td><input type="password" class="pass" name="pass" placeholder="비밀번호 입력"></td>
                </tr>
                <tr>
                    <td colspan="2" class="loginsubmit">
                        <input type="submit" value="로그인"/>
                        <input type="button" value="회원가입" 
                        onclick="javascript:window.location='regForm.jsp'"/>
                    </td>
                </tr>
            </table>
        </form>
    </article>
</section>
</body>
</html>
 
cs

- CSS 적용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@CHARSET "UTF-8";
section{
    width:200px;
    margin: auto;
    left:0; top:0; right:0; bottom:0;
}
.loginTable{
    width:200px;
    text-align:center;
    border-collapse:collapse;
}
.loginTable td {
    text-align:left;
    width:200px;    
    height:40px;
}
.loginTable td .id{
    width:97%;
}
.loginTable td .pass{
    width:97%;
}
.loginTable .loginsubmit{
    height:40px;
    border: none;
    text-align:center;
}
 
cs

요청결과> 로그인페이지



2. 회원가입 폼 만들기
/WebContent/memberone/regForm.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!-- 회원가입 폼 -->
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!doctype html>
<html>
<head>
<title>Register Form</title>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<link href="css/regFormstyle.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<section>
<form method="post" action="regProc.jsp" name="regForm">
<table class="regtable">
    <tr>
        <th colspan="2">회원 가입 정보 입력</th>
    </tr>
    <tr>
        <td>아이디 : </td><td><input type="text" name="id" required/>
        <input type="button" value="중복확인" onClick="#"/></td>
    </tr>
    <tr>
        <td>패스워드 : </td>
        <td><input type="password" name="pass" required/></td>
    </tr>
    <tr>
        <td>패스워드 확인 : </td>
        <td><input type="password" name="repass" required/></td>
    </tr>
    <tr>
        <td>이메일 : </td>
        <td><input type="email" name="email" required/></td>
    </tr>
    <tr>
        <td colspan="2" class="regsubmit">
        <input type="button" value="회원가입" onclick="#"/>&nbsp;&nbsp;
        <input type="reset" value="다시 입력"/>
        </td>
    </tr>
</table>
</form>
</section>
</body>
</html>
 
cs

- CSS 적용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@CHARSET "UTF-8";
section{
    width:350px;
    margin: auto;
    left:0; top:0; right:0; bottom:0;
}
.regtable{
    width:350px;
    text-align:center;
    border-collapse:collapse;
}
.regtable th{
    height:50px;
}
.regtable td {
    text-align:left;
    height:40px;
}
.regtable .regsubmit{
    height:30px;
    border: none;
    text-align:right;
}
 
cs

요청결과> 회원가입 정보 입력 페이지



3. 아이디 중복확인 구현

 아이디를 입력 후 중복확인을 클릭하면 아이디 중복에 대한 동작을 할 수 있도록 추가

 중복확인 이동을 javascript로 처리하도록 한다.


regForm.jsp의 중복확인 버튼을 구현하고 있는 부분에서 

onClick=”#”부분을 onClick="idCheck(this.form.id.value)”로 변경


다음 처리하는 기능의 javascript작성

/WebContent/memberone/script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function idCheck(id){
    if(id == ""){
        alert("아이디를 입력해주세요.");
        document.regForm.id.focus();
    }
    else{
        var popWidth = 300;
        var popHeight = 200;
        var winHeight = document.body.clientHeight;    // 현재창의 높이
        var winWidth = document.body.clientWidth;    // 현재창의 너비
        var winX = window.screenLeft;    // 현재창의 x좌표
        var winY = window.screenTop;    // 현재창의 y좌표
        var popX = winX + (winWidth - popWidth)/2;
        var popY = winY + (winHeight - popHeight)/2;
        url="idCheck.jsp?id="+id;
        window.open(url, "post"
                "left="+popX+",top="+popY+",width="+popWidth+", height="+popHeight);
    }
}
 
cs



- 스크립트 파일 작성 후 regForm.jsp 에서 idCheck함수를 알아야 하므로 <head>태그 안에 부분 밑에 다음 코드 삽입

<script src="script.js"></script>


 위의 작업에 이어서 idCheck()함수를 보면 id를 받아 idCheck.jsp 페이지로 이동하도록 만들었으므로 idCheck.jsp페이지 작성을 할 것이다.
 idCheck.jsp에서는 입력한 ID와 데이터 베이스에 저장된 ID를 가져와 서로 비교하여 처리하게 된다. 그래서 데이터베이스에 접근, 조작하는 객체(DAO)와 저장하는 객체(DTO)가 필요하다. 
 먼저 데이터베이스의 정보를 담을 수 있는 객체(DTO)를 정의하고 데이터베이스에 접근하고 조작하는 객체(DAO)를 만든다. (이 실습에서는 JavaBeans의 개념을 사용)

- 회원정보를 담는 DTO작성
/src/memberone/memberDto.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package memberone;
 
import java.sql.Timestamp;
 
public class MemberDto {
    private String id;
    private String pass;
    private String email;
    private Timestamp regdate;
    
    public MemberDto(){}
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Timestamp getRegdate() {
        return regdate;
    }
    public void setRegdate(Timestamp regdate) {
        this.regdate = regdate;
    }
}
 
cs


- ID중복체크 기능을 포함하여 DAO작성
/src/memberone/MemberDao.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package memberone;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
public class MemberDao {
    
    public static String ID = "scott"//사용할 DB 계정
    public static String PASSWORD = "tiger"//위 계정의 비밀번호
    public static String IP = "localhost";
    static {
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
        }
        catch(ClassNotFoundException e){
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws SQLException{
        return DriverManager.getConnection(
                "jdbc:oracle:thin:@"+IP+":1521:xe", ID, PASSWORD);
    }
    public boolean idCheck(String id){
        boolean result = true;
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try{
            conn = getConnection();
            pstmt = conn.prepareStatement(
                    "select * from MEMBER where id = ?");
            pstmt.setString(1, id);
            rs = pstmt.executeQuery();
            if(!rs.next()) result = false;
        }
        catch(SQLException sqle){
            sqle.printStackTrace();
        }
        finally{
            if(rs != null
                try{
                    rs.close();
                }catch(SQLException sqle1){}
            if(pstmt != null
                try{
                    pstmt.close();
                }catch(SQLException sqle2){}
            if(conn != null
                try{
                    conn.close();
                }catch(SQLException sqle3){}
        }
        return result;
    }
}
 
cs

여기까지 idCheck.jsp 에서 필요한 내용 작성완료
이어서 위 클래스를 활용하는 idCheck.jsp 페이지 작성
/WebContent/memberone/idCheck.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:useBean id="dao" class="memberone.MemberDao" />
<%
    String id = request.getParameter("id");
    boolean check = dao.idCheck(id);
%>
<html>
<head>
<title>ID 중복체크</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="script.js"></script>
<style>
a{ text-decoration: none; }
</style>
</head>
    <body>
    <br><b><%= id %></b>
    <%
        if(check){ out.println("는 이미 존재하는 ID입니다.<br/></br/>"); }
        else{    out.println("는 사용가능합니다.<br/><br/>"); }
    %>
        <a href="#" onClick="javascript:self.close()">닫기</a>
    </body>
</html>
 
cs

- 작성이 끝나면 실행하여 중복처리 버튼을 눌러 동작 확인
 아이디를 입력하지 않은 경우


 아이디가 사용 가능한 경우


4. 회원가입 처리

실제 회원의 데이터를 데이터베이스에 넣기 위해 다음 메서드를 DAO에 삽입

/src/memberone/MemberDao.java 클래스에 import와 memberInsert메서드 추가
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.sql.Timestamp;
import java.time.LocalDateTime;
…중간 생략
    public boolean memberInsert(MemberDto dto){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean flag = false;
        try{
            conn = getConnection();
            String strQuery = "insert into MEMBER values(?,?,?,?)";
            pstmt = conn.prepareStatement(strQuery);
            pstmt.setString(1, dto.getId());
            pstmt.setString(2, dto.getPass());
            pstmt.setString(3, dto.getEmail());
            pstmt.setTimestamp(4, Timestamp.valueOf(LocalDateTime.now()));
            int count = pstmt.executeUpdate();
            if(count>0) flag = true;
        }
        catch(Exception e){
            System.out.println("Exception " + e);
        }
        finally{
          if(rs != nulltry{rs.close();}catch(SQLException sqle1){}
          if(pstmt != nulltry{pstmt.close();}catch(SQLException sqle2){}
          if(conn != nulltry{conn.close();}catch(SQLException sqle3){}
        }
        return flag;
    }
 
cs


- 실제 memberInsert() 메서드를 호출하여 가입 처리를 해줄 regProc.jsp 페이지 작성

/WebContent/memberone/regProc.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8"); %>
<jsp:useBean id="dao" class="memberone.MemberDao"/>
<jsp:useBean id="dto" class="memberone.MemberDto"/>
<jsp:setProperty name="dto" property="*"/>
<%
    boolean flag = dao.memberInsert(dto);
%>
<!doctype html>
<html>
<head>
<title>회원 가입 확인</title>
</head>
<link href="css/style.css" rel="stylesheet" type="text/css">
<body>
<br/><br/>
<%
    if(flag){
        out.println("<b>회원 가입을 축하드립니다.</b><br/>");
        out.println("<a href=login.jsp>로그인</a>");
    }else{
        out.println("<b>다시 입력하여 주십시오.</b><br/>");
        out.println("<a href=regForm.jsp>다시가입</a>");
    }
%>
</body>
</html>
 
cs

- regForm.jsp코드의 [회원가입] 버튼의 onClick="#"을 onClick="inputCheck()"로 변경

- WebContent/memberone/script.js 파일에 inputCheck()함수 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function inputCheck(){
    if(document.regForm.id.value==""){
        alert("아이디를 입력해 주세요.");
        document.regForm.id.focus();
        return;
    }
    if(document.regForm.pass.value==""){
        alert("비밀번호를 입력해 주세요.");
        document.regForm.pass.focus();
        return;
    }
    if(document.regForm.repass.value==""){
        alert("비밀번호를 확인해 주세요.");
        document.regForm.repass.focus();
        return;
    }
    if(document.regForm.pass.value != document.regForm.repass.value){
        alert("비밀번호가 일치하지 않습니다.");
        document.regForm.repass.focus();
        return;
    }
    if(document.regForm.email.value==""){
        alert("이메일을 입력해 주세요.");
        document.regForm.email.focus();
        return;
    }
    
    var str=document.regForm.email.value;
    var atPos = str.indexOf('@');
    var atLastPos = str.lastIndexOf('@');
    var dotPos = str.indexOf('.');
    var spacePos = str.indexOf(' ');
    var commaPos = str.indexOf(',');
    var eMailSize = str.length;
    if(        atPos > 1 && 
            atPos == atLastPos && 
            dotPos > 3 && 
            spacePos == -1 && 
            commaPos == -1 && 
            atPos + 1 < dotPos && 
            dotPos + 1 < eMailSize
        );
    else{
        alert('E-mail주소 형식이 잘못 되었습니다.\n\r다시 입력해 주세요!');
        document.regForm.email.focus();
        return;
    }
    document.regForm.submit();
}
 
cs

작성이 완료 되었으니 실행하여 회원가입 시 동작들을 확인한다.

 회원 가입 정보 입력 페이지


 회원 가입 성공


 회원 정보 중복


전체 흐름을 이해하는 것이 중요하다.
그래서 나중에 개발할 때 미리 고려사항들을 생각할 수 있어야 한다.
반응형

+ Recent posts