1. 다음 우편번호 api 사용 -> 예제->사용자 지정 예제 복사 -> 스크립트 부분에 붙여넣기 -> input type  id 만 교체 

2. 비밀번호 확인 및 아이디 개수 체크


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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.1.0.js">
    
</script>
 
 
 
<script>
    $(document).ready(function() {
        //아이디 중복체크
 
        $("#userid").keyup(function() {
            //사용자가 입력한 아이디
 
            var userid = $("#userid").val();
 
            var param = "userid=" + userid;
 
            if (userid.length >= 4) { //최소 글자수 이상
 
                //아이디 체크
 
                $.ajax({
                    type : "post",
                    url : "/web02/member_servlet/idcheck.do",
                    data : param,
                    success : function(result) {
 
                        $("#span_id").html(result);
 
                    }
 
                })
 
            }
 
        });
 
        //버튼클릭 이벤트
        $("#btnJoin").click(function() {
            var userid = $("#userid").val();
            var name = $("#name").val();
            var passwd = $("#passwd").val();
            var passwd2 = $("#passwd2").val();
 
            
            if(userid.length<4){
                
                alert("아이디를 입력하세요");
                $("#userid").focus();
                return;
            }
            
            if (name == "") {
 
                alert("이름을 입력하세요");
                $("#name").focus();
                return;
            }
 
            if (passwd != passwd2) {
 
                alert("비밀번호가 일치하지 않습니다.");
                $("#passwd2").val("");
 
                return;
            }
 
            //폼데이터를 서버에 제출
            document.form1.submit();
 
        });
 
    });
</script>
 
<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>
    function sample6_execDaumPostcode() {
        new daum.Postcode(
                {
                    oncomplete : function(data) {
                        // 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
 
                        // 각 주소의 노출 규칙에 따라 주소를 조합한다.
                        // 내려오는 변수가 값이 없는 경우엔 공백('')값을 가지므로, 이를 참고하여 분기 한다.
                        var fullAddr = ''// 최종 주소 변수
                        var extraAddr = ''// 조합형 주소 변수
 
                        // 사용자가 선택한 주소 타입에 따라 해당 주소 값을 가져온다.
                        if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
                            fullAddr = data.roadAddress;
 
                        } else { // 사용자가 지번 주소를 선택했을 경우(J)
                            fullAddr = data.jibunAddress;
                        }
 
                        // 사용자가 선택한 주소가 도로명 타입일때 조합한다.
                        if (data.userSelectedType === 'R') {
                            //법정동명이 있을 경우 추가한다.
                            if (data.bname !== '') {
                                extraAddr += data.bname;
                            }
                            // 건물명이 있을 경우 추가한다.
                            if (data.buildingName !== '') {
                                extraAddr += (extraAddr !== '' ? ', '
                                        + data.buildingName : data.buildingName);
                            }
                            // 조합형주소의 유무에 따라 양쪽에 괄호를 추가하여 최종 주소를 만든다.
                            fullAddr += (extraAddr !== '' ? ' (' + extraAddr
                                    + ')' : '');
                        }
 
                        // 우편번호와 주소 정보를 해당 필드에 넣는다.
                        document.getElementById('sample6_postcode').value = data.zonecode; //5자리 새우편번호 사용
                        document.getElementById('sample6_address').value = fullAddr;
 
                        // 커서를 상세주소 필드로 이동한다.
                        document.getElementById('sample6_address2').focus();
                    }
                }).open();
    }
</script>
 
</head>
<body>
 
 
    <h2>회원가입</h2>
 
 
    <form name="form1" method="post" action="/web02/member_servlet/join.do">
 
        <table border="1" width="700px">
            <tr>
                <td>이름</td>
                <td><input type="text" name="name" id="name"></td>
            </tr>
 
 
            <tr>
                <td>아이디</td>
                <td><input type="text" name="userid" id="userid"> <span
                    id="span_id"></span></td>
            </tr>
 
 
            <tr>
                <td>비밀번호</td>
                <td><input type="password" name="passwd" id="passwd"></td>
            </tr>
 
 
            <tr>
                <td>비밀번호확인</td>
                <td><input type="password" name="passwd2" id="passwd2"></td>
            </tr>
 
 
            <tr>
                <td>이메일</td>
                <td><input type="email" name="email" id="email"></td>
            </tr>
 
 
            <tr>
                <td>폰번호</td>
                <td><input type="text" name="hp" id="hp"></td>
            </tr>
 
 
            <tr>
                <td>우편번호</td>
                <!-- readonly 읽기만전용 -->
                <td><input type="text" name="zipcode" id="sample6_postcode"
                    readonly> <input type="button"
                    onclick="sample6_execDaumPostcode()" value="우편번호 찾기"></td>
            </tr>
 
 
            <tr>
                <td>주소</td>
                <td><input type="text" name="address1" id="sample6_address"
                    readonly></td>
            </tr>
 
 
            <tr>
                <td>주소상세</td>
                <td><input type="text" name="address2" id="sample6_address2"></td>
            </tr>
 
 
            <tr>
 
                <td align="center" colspan="2"><input type="button"
                    value="회원가입" id="btnJoin"> <input type="reset" value="취소">
 
                </td>
            </tr>
 
        </table>
    </form>
 
</body>
</html>
cs


1. 회원가입 페이지 아이디 옆에 스펜테그 입력 , 위에 스크립트로 keyup 함수 작성


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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.1.0.js">
    
</script>
 
<script>
    $(document).ready(function() {
        //아이디 중복체크
 
        $("#userid").keyup(function() {
            //사용자가 입력한 아이디
 
            var userid = $("#userid").val();
 
            var param = "userid=" + userid;
 
            if (userid.length >= 4) { //최소 글자수 이상
 
                //아이디 체크
 
                $.ajax({
                    type : "post",
                    url : "/web02/member_servlet/idcheck.do",
                    data : param,
                    success : function(result) {
 
                        $("#span_id").html(result);
 
                    }
 
                })
 
            }
 
        });
        
        
        //버튼클릭 이벤트
        $("#btnJoin").click(function() {
        
            //폼데이터를 서버에 제출
            document.form1.submit();
 
        });
 
    });
</script>
 
</head>
<body>
 
 
    <h2>회원가입</h2>
 
 
    <form name="form1" method="post" action="/web02/member_servlet/join.do">
 
        <table border="1" width="700px">
            <tr>
                <td>이름</td>
                <td><input type="text" name="name" id="name"></td>
            </tr>
 
 
            <tr>
                <td>아이디</td>
                <td><input type="text" name="userid" id="userid"> <span id="span_id"></span></td>
            </tr>
 
 
            <tr>
                <td>비밀번호</td>
                <td><input type="password" name="passwd" id="passwd"></td>
            </tr>
 
 
            <tr>
                <td>비밀번호확인</td>
                <td><input type="password" name="passwd2" id="passwd2"></td>
            </tr>
 
 
            <tr>
                <td>이메일</td>
                <td><input type="email" name="email" id="email"></td>
            </tr>
 
 
            <tr>
                <td>폰번호</td>
                <td><input type="text" name="hp" id="hp"></td>
            </tr>
 
 
            <tr>
                <td>우편번호</td>
                <td><input type="text" name="zipcode" id="zipcode"></td>
            </tr>
 
 
            <tr>
                <td>주소</td>
                <td><input type="text" name="address1" id="address1"></td>
            </tr>
 
 
            <tr>
                <td>주소상세</td>
                <td><input type="text" name="address2" id="address2"></td>
            </tr>
 
 
            <tr>
 
                <td  align="center" colspan="2">
                <input type="button" value="회원가입" id="btnJoin"> 
                <input type="reset" value="취소">
 
                </td>
            </tr>
 
        </table>
    </form>
 
</body>
</html>
cs



2.컨트롤 

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
        //아이디 체크
        } else if (url.indexOf("idcheck.do"!= -1) {
 
            String userid = request.getParameter("userid");
 
            
            System.out.println("userid"+userid);
            
            int idcheck = dao.idcheck(userid);
 
            System.out.println("idcheck"+idcheck);
            
            String message = "";
 
            if (idcheck==0) {
 
                message = userid + "는 사용가능한 아이디 입니다.";
 
            } else {
 
                message = userid + "는 사용할 수 없는 아이디 입니다.";
            }
            request.setAttribute("message", message);
            // 페이지 이동
 
            String page = "/member/idcheck.jsp";
            RequestDispatcher rd = request.getRequestDispatcher(page);
            rd.forward(request, response);
        }
 
    }
cs



3.dao


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
60
61
62
63
// idcheck
    public int idcheck(String userid) {
 
    
        
        
        Connection conn = null// db접속
        PreparedStatement pstmt = null// sql 실행
        ResultSet rs = null// select 결과 처리
        int result =1;
        try {
 
            conn = DB.dbConn(); // db접속 성공
 
            String sql = "select count(*) from member where userid=?";
 
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userid);
 
            rs = pstmt.executeQuery(); // rs에 실행결과 리턴
 
            
            if (rs.next()) { // 레코드가 존재하면
 
                    result = rs.getInt(1);
            }
 
        } catch (Exception e) {
 
            e.printStackTrace();
        } finally {
            
            try {
                if (rs != null) {
                    rs.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
            try {
                if (conn != null) {
                    conn.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
        }
 
        return result;
 
    }
cs



4. 아이디 사용여부 표시 


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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
    <%
        String message = (String) request.getAttribute("message");
 
        if (message.indexOf("사용가능한"!= -1) {
    %>
 
    <span style="color: blue;"><%=message%> </span>
 
    <%
        } else {
    %>
 
    <span style="color: red;"><%=message%></span>
 
    <%
        }
    %>
 
 
</body>
</html>
cs


1.회원가입 페이지


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    <script>
    $(document).ready(function() {
 
        
        //회원가입
        $("#btnJoin").click(function (){
            
            
            location.href="/web02/member/join.jsp";
            
            
        });
 
 
<input type="button" value="회원가입" id="btnJoin">
 
 
cs




2.회원가입 페이지


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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.1.0.js">
    
</script>
 
<script>
    $(document).ready(function() {
 
        //버튼클릭 이벤트
        $("#btnJoin").click(function() {
        
            //폼데이터를 서버에 제출
            document.form1.submit();
 
        });
 
    });
</script>
 
</head>
<body>
 
 
    <h2>회원가입</h2>
 
 
    <form name="form1" method="post" action="/web02/member_servlet/join.do">
 
        <table border="1" width="700px">
            <tr>
                <td>이름</td>
                <td><input type="text" name="name" id="name"></td>
            </tr>
 
 
            <tr>
                <td>아이디</td>
                <td><input type="text" name="userid" id="userid"></td>
            </tr>
 
 
            <tr>
                <td>비밀번호</td>
                <td><input type="password" name="passwd" id="passwd"></td>
            </tr>
 
 
            <tr>
                <td>비밀번호확인</td>
                <td><input type="password" name="passwd2" id="passwd2"></td>
            </tr>
 
 
            <tr>
                <td>이메일</td>
                <td><input type="email" name="email" id="email"></td>
            </tr>
 
 
            <tr>
                <td>폰번호</td>
                <td><input type="text" name="hp" id="hp"></td>
            </tr>
 
 
            <tr>
                <td>우편번호</td>
                <td><input type="text" name="zipcode" id="zipcode"></td>
            </tr>
 
 
            <tr>
                <td>주소</td>
                <td><input type="text" name="address1" id="address1"></td>
            </tr>
 
 
            <tr>
                <td>주소상세</td>
                <td><input type="text" name="address2" id="address2"></td>
            </tr>
 
 
            <tr>
 
                <td  align="center" colspan="2">
                <input type="button" value="회원가입" id="btnJoin"> 
                <input type="reset" value="취소">
 
                </td>
            </tr>
 
        </table>
    </form>
 
</body>
</html>
cs



3. 컨트롤





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
} else if (url.indexOf("join.do"!= -1) {
 
            String userid = request.getParameter("userid");
            String passwd = request.getParameter("passwd");
            String name = request.getParameter("name");
            String email = request.getParameter("email");
            String hp = request.getParameter("hp");
            String zipcode = request.getParameter("zipcode");
            String address1 = request.getParameter("address1");
            String address2 = request.getParameter("address2");
 
            // form 태그의 name속성
            MemberDTO dto = new MemberDTO(userid, passwd, name, email, hp, zipcode, address1, address2);
 
            // insert요청
            int result=dao.memberInsert(dto);
 
            
            // if 문
            
            String message= result=="fail""success";
 
            
            
            // 페이지 이동
 
            String page = path + "/member/main.jsp?message="+message;
            response.sendRedirect(page);
 
        }
 
    }
cs



4. main 페이지


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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
    <%
        String message = request.getParameter("message");
 
        String str = "";
 
        //자바에서는 이퀄스 사용
        if (message.equals("success")) {
 
            str = "회원가입이 완료";
 
        } else {
 
            str = "회원가입 실패 ";
 
        }
    %>
 
    <h2><%=str%></h2>
 
</body>
</html>
cs

1.로그인 페이지 


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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
 
<script src="http://code.jquery.com/jquery-3.1.0.js">
    
</script>
 
 
<script>
    $(document).ready(function() {
 
        
        alert("오잉");
        
        $("#btnLogin").click(function() {
 
            var userid = $("#userid").val();
            var passwd = $("#passwd").val();
 
            if (userid == "") {
 
                alert("아이디를 입력해주세요");
                $("#userid").focus();
                return;
            }

//$반복 var exp = /[a-z0-9]$/; //영문자와 숫자 //정규표현식. test(입력값) 규칙에 맞으면 true if(!exp.test(userid)){ alert("영문자와 숫자만 입력가능합니다."); $("#userid").focus(); return; }
 
            if (passwd == "") {
 
                alert("비밀번호를 입력해주세요");
 
                $("#passwd").focus();
                return;
            }
 
            //비동기 ajax 방식으로 데이터 주고 받기 방버버
 
            var data = "userid=" + userid + "&passwd=" + passwd;
 
            alert(userid+passwd);
            
            $.ajax({
                
                type : "post",
                data : data,
                url : "/web02/member_servlet/login.do",
                success : function(value) {
 
                    $("#result").html(value);
 
                }
 
            });
 
            /*             
             document.form1.action=""
             document.from1.submit();
             */
        });
 
    });
</script>
 
 
</head>
<body>
 
 
    <table border="1">
 
 
 
        <tr>
            <td>아이디</td>
            <td><input type="text" id="userid"></td>
        </tr>
 
        <tr>
            <td>비밀번호</td>
            <td><input type="password" id="passwd"></td>
        </tr>
 
 
 
        <tr>
            <td colspan="2" align="center"><input type="button" value="로그인"
                id="btnLogin"></td>
        </tr>
 
 
 
 
    </table>
    <div id="result">로그인 결과 출력 영역</div>
 
 
 
</body>
</html>
cs




2.컨트롤러



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 member;
 
import java.io.IOException;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet("/member_servlet/*")
public class MemberController extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("멤버서블릿 호출");
        String path = request.getContextPath();
        String url = request.getRequestURI().toString();
 
        MemberDAO dao = new MemberDAO();
 
        // url 분석
        // 로그인 이면
        if (url.indexOf("login.do"!= -1) {
 
            String userid = request.getParameter("userid");
            String passwd = request.getParameter("passwd");
            String name = dao.loginCheck(userid, passwd);
            String message = "";
 
            if (name == null) { // 로그인 실패
 
                message = "아이디 또는 비밀번호가 일치하지 않습니다.";
            } else { // 로그인 성공
 
                message = name + "님 환영합니다.";
            }
            // 데이터 저장
            request.setAttribute("message", message);
            // 포워딩
 
            String page = "/member/login_result.jsp";
 
            RequestDispatcher rd = request.getRequestDispatcher(page);
            rd.forward(request, response);
        }
 
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        doGet(request, response);
    }
 
}
 
cs





3.다오



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
60
61
62
63
64
package member;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
 
import config.DB;
 
public class MemberDAO {
 
    public String loginCheck(String userid, String passwd) {
 
        String name = null;
        Connection conn = null// db접속
        PreparedStatement pstmt = null// sql 실행
        ResultSet rs = null// select 결과 처리
 
        try {
 
            conn = DB.dbConn(); // db접속 성공
 
            String sql = "select name from member where userid=? and passwd=password(?)";
 
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userid);
            pstmt.setString(2, passwd);
            rs = pstmt.executeQuery(); // rs에 실행결과 리턴
 
            if (rs.next()) { // 레코드가 존재하면
 
                name = rs.getString("name"); // 이름 저장
            }
 
        } catch (Exception e) {
 
            e.printStackTrace();
        } finally {
 
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
            try {
                if (conn != null) {
                    conn.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
        }
 
        return name;
 
    }
 
}
 
cs



4.결과 페이지  AJAX


1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
${message}
 
</body>
</html>
cs




5.DTO


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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package member;
 
public class MemberDTO {
 
    private String userid;
    private String passwd;
    private String name;
    private String email;
    private String hp;
    private String zipcode;
    private String address1;
    private String address2;
    private String join_date;
 
    public MemberDTO() {
        // TODO Auto-generated constructor stub
    }
 
 
 
    public MemberDTO(String userid, String passwd, String name, String email, String hp, String zipcode,
            String address1, String address2) {
        super();
        this.userid = userid;
        this.passwd = passwd;
        this.name = name;
        this.email = email;
        this.hp = hp;
        this.zipcode = zipcode;
        this.address1 = address1;
        this.address2 = address2;
    }
 
 
 
    public String getUserid() {
        return userid;
    }
 
    public void setUserid(String userid) {
        this.userid = userid;
    }
 
    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 getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public String getHp() {
        return hp;
    }
 
    public void setHp(String hp) {
        this.hp = hp;
    }
 
    public String getZipcode() {
        return zipcode;
    }
 
    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }
 
    public String getAddress1() {
        return address1;
    }
 
    public void setAddress1(String address1) {
        this.address1 = address1;
    }
 
    public String getAddress2() {
        return address2;
    }
 
    public void setAddress2(String address2) {
        this.address2 = address2;
    }
 
    public String getJoin_date() {
        return join_date;
    }
 
    public void setJoin_date(String join_date) {
        this.join_date = join_date;
    }
 
    @Override
    public String toString() {
        return "MemberDTO [userid=" + userid + ", passwd=" + passwd + ", name=" + name + ", email=" + email + ", hp="
                + hp + ", zipcode=" + zipcode + ", address1=" + address1 + ", address2=" + address2 + ", join_date="
                + join_date + "]";
    }
 
}
 
cs






6테이블 생성 및 삽입


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
 
-- 회원가입과 로그인
 
create table member(
userid varchar(20not null primary key,
passwd varchar(100not null,
name varchar(50not null,
email varchar(50),
hp varchar(50),
zipcode varchar(20),
address1 varchar(200),
address2 varchar(200),
join_date datetime default now()
);
 
 
-- 회원추가 쿼리
 
insert into member (userid,passwd,name)
values('kim1',password('1234'),'강영균');
 
-- 암호화
-- password('값') 암호화 되어 저장됨
 
--복호화
 
-- sql injection attack
 userid 에  ' or 1=1#을 입력
-- 선택
select * from member;
-- 삭제
delete from member;
--로그인 
select * from member
where userid='kim'
and passwd=password('1234');
cs


1. 화면에서 수정삭제 버튼 클릭하면


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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
 
 
<%
    String path = request.getContextPath();
%>
<script src="http://code.jquery.com/jquery-3.1.0.js"> </script>
<script>
 
    $(document).ready(function() {
 
        //삭제
        
        $("#btnDelete").click(function(){
            
        if(    confirm("정말 삭제 하시겠습니까?")){
            //주소 이동
            //수정과 삭제의 주소가 달라서 form 태그 안에 적어주지 않고 이곳에 적어준다.
            var idx = $("#idx").val();
            document.form1.action="<%=path%>/memo_servlet/delete.do?idx=" + idx;
            document.form1.submit();        //서버에 제출
        }
            
        });
        
        
    
        
        //업데이트
        $("#btnUpdate").click(function() {
 
            //var writer = $("#writer").val();  id로 조회
            //name으로 조회 
            var writer = document.form1.writer;
            var memo = document.form1.memo;
 
            if (writer.value == "") { //빈 값 체크
 
                alert("이름을 입력하세요");
                writer.focus();
                return;
 
            }
 
            if (memo.value == "") {
 
                alert("메모를 입력하세요");
                memo.focus();
                return;
            }
            //주소 이동
            //수정과 삭제의 주소가 달라서 form 태그 안에 적어주지 않고 이곳에 적어준다.
            var idx = $("#idx").val();
            document.form1.action="<%=path%>/memo_servlet/update.do?idx="+ idx;
            document.form1.submit(); //서버에 제출
                                        
        
        });
 
                    });
</script>
 
</head>
<body>
 
    <!-- post면 주소에 던져지는 값 안보임 -->
    <form name="form1" method="post">
 
        <table border="1">
 
            <tr>
                <td>날짜</td>
                <td>${dto.post_date}</td>
            </tr>
 
            <tr>
                <td>이름</td>
                <td><input name="writer" value="${dto.writer}"></td>
            </tr>
            <tr>
                <td>메모</td>
                <td><textarea name="memo"> ${dto.memo} </textarea></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <!-- 수정 삭제 할때 번호를 넘겨야 하는데 idx를 화면에 보여주지 않고 넘기는 법 --> <input
                    type="hidden" id="idx" value="${dto.idx} "> 
                    <input type="button" value="수정" id="btnUpdate"> 
                    <input type="button" value="삭제" id="btnDelete">
                </td>
            </tr>
 
 
        </table>
 
    </form>
 
</body>
</html>
cs




2컨트롤러로 간다



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
else if (url.indexOf("update.do"!= -1) {
 
            int idx = Integer.parseInt(request.getParameter("idx"));
            String writer = request.getParameter("writer");
            String memo = request.getParameter("memo");
 
            // dao에 update 요청
            dao.memoUpdate(idx, writer, memo);
 
            // 페이지 이동(redirect)
            response.sendRedirect(context + "/memo/index.jsp");
 
            // 페이지 이동(redirect)
 
        }else if(url.indexOf("delete.do")!=-1){
            
            
            int idx=Integer.parseInt(request.getParameter("idx"));
            
            dao.memoDelete(idx);
        
            // 페이지 이동(redirect)
            response.sendRedirect(context + "/memo/index.jsp");
        }
 
    }
 
cs






3. DAO


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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// 업데이트
    public void memoUpdate(int idx, String writer, String memo) {
 
        Connection conn = null;
        PreparedStatement pstmt = null;
 
        try {
            conn = DB.dbConn();
 
            String sql = "update memo set writer=? , memo = ? where idx= ?";
 
            pstmt = conn.prepareStatement(sql);
 
            pstmt.setString(1, writer);
            pstmt.setString(2, memo);
            pstmt.setInt(3, idx);
 
            // 업데이트 성공하면 1 리턴
            int count = pstmt.executeUpdate();
 
            // MemoView(idx);
 
        } catch (Exception e) {
 
        } finally {// resultset= > statement=> connection
 
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
            try {
                if (conn != null) {
                    conn.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
        }
 
    }
 
    // 삭제
    public void memoDelete(int idx) {
 
        Connection conn = null;
        PreparedStatement pstmt = null;
 
        try {
            conn = DB.dbConn();
 
            String sql = "delete from memo where idx = ?";
 
            pstmt = conn.prepareStatement(sql);
 
            pstmt.setInt(1, idx);
 
            // 업데이트 성공하면 1 리턴
            int count = pstmt.executeUpdate();
 
            // MemoView(idx);
 
        } catch (Exception e) {
 
        } finally {// resultset= > statement=> connection
 
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
            try {
                if (conn != null) {
                    conn.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
 
    }
cs



4.마지막으로 INSERT 화면 호출 


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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
 
<script src="http://code.jquery.com/jquery-3.1.0.js">
    
</script>
 
<%
    //context path: 웹프로젝트의 식별자
    String path = request.getContextPath();
%>
 
<script>
    $(document).ready(function(){
        
        memo_list();
        
        //추가버튼 클릭 이벤트
        $("#btnAdd").click(function (){
            
            memo_insert();
            
        });
        
        
    });
    
    //추가 버튼 함수
    function memo_insert(){
        
        //input 태그에 입력한 값
         var writer=$("#writer").val();
        var memo=$("#memo").val();
        
        //금칙어 처리
        var bad_word_list = ["<xmp>""<script>"];
        for(var i=0; i<bad_word_list.length; i++){
            
            if(memo.indexOf(bad_word_list[i]) != -1){
                
                alert(
                        
                        bad_word_list[i]+"는 입력할 수 없습니다."
                );
                
                $("#memo").focus();
                return;
            }
            
        }
        
        
        //쿼리 구성
        
        var param = "writer="+writer+"&memo="+memo;
        
        $.ajax({
                
            type: "post",
            data: param,
            url: "<%=path%>/memo_servlet/insert.do",
            success: function(){
                //콜백함수
            
                // 추가 완료되면 목록을 갱신함
                 
                memo_list();
                                
            }
        });
        
    }
    
    
    function memo_list(){
        
        //함수
        $.ajax({
            
            //함수의 파라미터 
            url: "<%=path%>/memo_servlet/list.do",
            success : function(result) {
                //result : Response Text (서버의 응답텍스트)
                // div의 내용을 교체함
                $("#divList").html(result);
 
            }
 
        })
 
    }
</script>
 
 
 
</head>
<body>
 
    이름
    <input id="writer" size="10"> 
    <br>
    메모
    
    <textarea id="memo" rows="5" cols="30"> </textarea>
    <!-- <input id="memo" size="30"> -->
 
    <!-- 버튼은 전송기능이 없어서 js를 이용해줘야한다 -->
    <input type="button" id="btnAdd" value="확인">
 
    <h2>한줄메모장</h2>
    <div id="divList">이곳에 목록이 출력됩니다.</div>
 
</body>
</html>
cs


 








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
package config;
 
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
 
//filter 선처리 클래스
//아래 요청에 대해서 모든 필터를 적용해라
//filter와 url 맵핑
@WebFilter("/*")
public class EncodingFilter implements Filter {
 
    private String charset = "utf-8";
    
    //서버가 중지 될때 작동
    public void destroy() {
 
        System.out.println("필터 종료");
    }
 
    // 요청이 들어왔을때 거쳐가는 코드
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
 
        // 선처리할 코드
        request.setCharacterEncoding(charset);
 
        chain.doFilter(request, response);
    }
 
    // 웹서버가 실행될때 자동으로필터를 초기화 시킴
    public void init(FilterConfig fConfig) throws ServletException {
 
        System.out.println("필터가 초기화 되었습니다.");
 
    }
 
}
 
cs


El, jsp




메모 리스트

메모 제목에 A 태그 달기


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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.List"%>
<%@ page import="memo.MemoDTO"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
    <%
    
        String path=request.getContextPath();
        //컨트롤러에서 넘어온 값을 읽어옴
        // request.getAttribute(key)
        //object 타입이라 형변환 해야함
        List<MemoDTO> items = (List<MemoDTO>) request.getAttribute("items");
    %>
 
    <table border="1">
        <tr>
            <th>번호</th>
            <th>이름</th>
            <th>메모</th>
            <th>날씨</th>
        </tr>
 
        <%
            for (MemoDTO dto : items) {
        %>
 
        <tr>
            <td><%=dto.getIdx()%></td>
            <td><%=dto.getWriter()%></td>
            
            
            
            <td>
            
            <a href="<%=path %>/memo_servlet/view.do?idx=<%=dto.getIdx() %>">
            <%=dto.getMemo()%></a>
            
            </td>
            <td><%=dto.getPost_date()%></td>
 
        </tr>
 
 
        <%
            }
        %>
    </table>
 
</body>
</html>
 
cs




2컨트롤러


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
else if(url.indexOf("view.do")!=-1){
            
            //string 값으로 넘어온다.
            //글번호
            int idx=Integer.parseInt(request.getParameter("idx"));
            
            //dao에 레코드 정보 조회
            MemoDTO dto=dao.MemoView(idx);
            
            request.setAttribute("dto", dto);
            
            String page = "/memo/view.jsp";
            
            RequestDispatcher rd=request.getRequestDispatcher(page);
            
            rd.forward(request, response);
            
        }
        
    }
 
cs



3 다오


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
60
// 게시글 상세
    public MemoDTO MemoView(int idx) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        MemoDTO dto = new MemoDTO();
 
        try {
            conn = DB.dbConn();
 
            String sql = "select * from memo where idx=?";
 
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, idx);
            rs = pstmt.executeQuery();
 
            if (rs.next()) {
 
                dto.setIdx(rs.getInt("idx"));
                dto.setMemo(rs.getString("memo"));
                dto.setWriter(rs.getString("writer"));
                dto.setPost_date(rs.getString("post_date"));
 
            }
 
        } catch (Exception e) {
 
        } finally {// resultset= > statement=> connection
 
            try {
                if (rs != null) {
                    rs.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
            try {
                if (conn != null) {
                    conn.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
        }
 
        return dto;
    }
cs


4. 





4. 상세 페이지


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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
 
<form name="form1" method="post">
 
    <table border="1">
    
        <tr>
            <td>날짜</td>
            <td>${dto.post_date}</td>
        </tr>
    
    <tr>
            <td>이름</td>
            <td><input name="writer" vlaue="${dto.writer}"> </td>
        </tr>
        <tr>
            <td>메모</td>
            <td><textarea name="memo"> ${dto.memo} </textarea></td>
        </tr>
        <tr>
            <td colspan="2" align="center">
            <input type="button" value="수정" id="btnUpdate">
            <input type="button" value="삭제" id="btnDelete">
            </td>
        </tr>
    
    
    </table>
 
</form>
 
</body>
</html>
cs


한줄메모 삽입 & AJAX




INDEX.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
 
<script src="http://code.jquery.com/jquery-3.1.0.js">
    
</script>
 
<%
    //context path: 웹프로젝트의 식별자
    String path = request.getContextPath();
%>
 
<script>
    $(document).ready(function(){
        
        memo_list();
        
        //추가버튼 클릭 이벤트
        $("#btnAdd").click(function (){
            
            memo_insert();
            
        });
        
        
    });
    
    //추가 버튼 함수
    function memo_insert(){
        
        //input 태그에 입력한 값
         var writer=$("#writer").val();
        var memo=$("#memo").val();
        
        //금칙어 처리
        var bad_word_list = ["<xmp>""<script>"];
        for(var i=0; i<bad_word_list.length; i++){
            
            if(memo.indexOf(bad_word_list[i]) != -1){
                
                alert(
                        
                        bad_word_list[i]+"는 입력할 수 없습니다."
                );
                
                $("#memo").focus();
                return;
            }
            
        }
        
        
        //쿼리 구성
        
        var param = "writer="+writer+"&memo="+memo;
        
        $.ajax({
                
            type: "post",
            data: param,
            url: "<%=path%>/memo_servlet/insert.do",
            success: function(){
                //콜백함수
            
                // 추가 완료되면 목록을 갱신함
                 
                memo_list();
                                
            }
        });
        
    }
    
    
    function memo_list(){
        
        //함수
        $.ajax({
            
            //함수의 파라미터 
            url: "<%=path%>/memo_servlet/list.do",
            success : function(result) {
                //result : Response Text (서버의 응답텍스트)
                // div의 내용을 교체함
                $("#divList").html(result);
 
            }
 
        })
 
    }
</script>
 
 
 
</head>
<body>
 
    이름
    <input id="writer" size="10"
    <br>
    메모
    
    <textarea id="memo" rows="5" cols="30"> </textarea>
    <!-- <input id="memo" size="30"> -->
 
    <!-- 버튼은 전송기능이 없어서 js를 이용해줘야한다 -->
    <input type="button" id="btnAdd" value="확인">
 
    <h2>한줄메모장</h2>
    <div id="divList">이곳에 목록이 출력됩니다.</div>
 
</body>
</html>
cs




2.CONTROLLER


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
60
61
62
63
64
65
66
67
68
69
70
71
72
package memo;
 
import java.io.IOException;
import java.util.List;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
//memo로 들어오는 모든것 , 외부에서 볼수 없게 만드는 것
@WebServlet("/memo_servlet/*")
public class MemoController extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        System.out.println("메모 서블릿");
 
        // 컨텍스트 패스
        String context = request.getContextPath();
 
        // 요청한 url을 스트링으로 저장
        String url = request.getRequestURL().toString();
 
        MemoDAO dao = new MemoDAO();
 
        // 없으면 -1 있으면 -1 이 아닌 다른 정수
        if (url.indexOf("list.do"!= -1) {
 
            List<MemoDTO> items = dao.memoList();
 
            // 저장영역.setAttribute(key,value)
            // session.setAttribute
            // page.setAttribute
            request.setAttribute("items", items);
 
            // 포워딩할 페이지
            String page = "/memo/list.jsp";
 
            // 포워딩할 페이지의 정보 분석 객체
            RequestDispatcher rd = request.getRequestDispatcher(page);
 
            // 포워드 (forward) : 화면전환, 주소는 그대로
            rd.forward(request, response);
 
            // 입력
        } else if (url.indexOf("insert.do"!= -1) {
 
            String writer = request.getParameter("writer");
            String memo = request.getParameter("memo");
            MemoDTO dto = new MemoDTO(writer, memo);
 
            // dao에 insert요청
 
            dao.memoInsert(dto);
 
        }
 
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        doGet(request, response);
    }
 
}
 
cs





3. DAO


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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package memo;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
 
import config.DB;
 
//DAO  (DATA ACCESS OBJECT 데이터 처리 객체)
//비즈니스 로직을 실행하는 클래스
// 
 
public class MemoDAO {
 
    // 삽입
    public void memoInsert(MemoDTO dto) {
 
        Connection conn = null;
        PreparedStatement pstmt = null;
 
        try {
 
            conn = DB.dbConn();
            String sql = "insert into memo (writer, memo, post_date) " + "values(?,?,now())";
            pstmt = conn.prepareStatement(sql);
 
            pstmt.setString(1, dto.getWriter());
            pstmt.setString(2, dto.getMemo());
            pstmt.executeUpdate();
        } catch (Exception e) {
 
            e.printStackTrace();
        } finally {
 
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
            try {
                if (conn != null) {
                    conn.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
        }
 
    }
 
    // 리스트
    public List<MemoDTO> memoList() {
 
        List<MemoDTO> items = new ArrayList<MemoDTO>();
 
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
 
        try {
 
            // DB가 static이라서 바로 접근 가능하다.
 
            conn = DB.dbConn(); // db연결자 리턴
 
            String sql = "select * from memo order by idx desc";
 
            pstmt = conn.prepareStatement(sql);
 
            // 결과값 리턴
            rs = pstmt.executeQuery();
 
            // 다 읽어 와라 결과셋.next() 다음 레코드가 있으면 true
            while (rs.next()) {
 
                // 데이터 그릇을 만들어서 oracle에서 불러온 데이터들을 담아준다.
                MemoDTO dto = new MemoDTO();
 
                // 결과셋.get자료형("칼럼이름")
                dto.setIdx(rs.getInt("idx"));
                dto.setWriter(rs.getString("writer"));
 
                // 부등호 문자 &lt ; Less Than <
                // &gt; Greater Than >
 
                String memo = rs.getString("memo");
                // 태그 문자 처리
 
                memo = memo.replace("<""&lt;");
                memo = memo.replace(">""&gt;");
                // 공백문자 처리
                memo = memo.replace("  ""&nbsp;&nbsp;");
 
                // 줄바꿈 문자처리
                memo = memo.replace("\n""<br>");
 
                dto.setMemo(memo);
 
                dto.setPost_date(rs.getString("post_date"));
 
                // list에 쌓인다.
                items.add(dto);
            }
 
        } catch (Exception e) {
 
            e.printStackTrace();
        } finally {// 예외 발생여부와 상관없이 항상 실행
 
            // resultset= > statement=> connection
 
            try {
                if (rs != null) {
                    rs.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
 
            try {
                if (conn != null) {
                    conn.close();
                }
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return items;
 
    }
}
 
cs



4. LIST.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
46
47
48
49
50
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ page import="java.util.List"%>
<%@ page import="memo.MemoDTO"%>
 
 
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
    <%
        //컨트롤러에서 넘어온 값을 읽어옴
        // request.getAttribute(key)
        //object 타입이라 형변환 해야함
        List<MemoDTO> items = (List<MemoDTO>) request.getAttribute("items");
    %>
 
    <table border="1">
        <tr>
            <th>번호</th>
            <th>이름</th>
            <th>메모</th>
            <th>날씨</th>
        </tr>
 
        <%
            for (MemoDTO dto : items) {
        %>
 
        <tr>
            <td><%=dto.getIdx()%></td>
            <td><%=dto.getWriter()%></td>
            <td><%=dto.getMemo()%></td>
            <td><%=dto.getPost_date()%></td>
 
        </tr>
 
 
        <%
            }
        %>
    </table>
 
</body>
</html>
cs







JDBC&데이터 처리 순서






















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
    // 다 읽어 와라 결과셋.next() 다음 레코드가 있으면 true
            while (rs.next()) {
 
                // 데이터 그릇을 만들어서 oracle에서 불러온 데이터들을 담아준다.
                MemoDTO dto = new MemoDTO();
 
                // 결과셋.get자료형("칼럼이름")
                dto.setIdx(rs.getInt("idx"));
                dto.setWriter(rs.getString("writer"));
 
                // 부등호 문자 &lt ; Less Than <
                // &gt; Greater Than >
 
                String memo = rs.getString("memo");
                // 태그 문자 처리
 
                memo = memo.replace("<""&lt;");
                memo = memo.replace(">""&gt;");
                // 공백문자 처리
                memo = memo.replace("  ""&nbsp;&nbsp;");
 
                // 줄바꿈 문자처리
                memo = memo.replace("\n""<br>");
 
                dto.setMemo(memo);
 
                dto.setPost_date(rs.getString("post_date"));
 
                // list에 쌓인다.
                items.add(dto);
            }
cs




JSP에서 금칙어 처리 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//추가 버튼 함수
    function memo_insert(){
        
        //input 태그에 입력한 값
         var writer=$("#writer").val();
        var memo=$("#memo").val();
        
        //금칙어 처리
        var bad_word_list = ["<xmp>", "<script>"];
        for(var i=0; i<bad_word_list.length; i++){
            
            if(memo.indexOf(bad_word_list[i]) != -1){
                
                alert(
                        
                        bad_word_list[i]+"는 입력할 수 없습니다."
                );
                
                $("#memo").focus();
                return;
            }
            
        }
cs


+ Recent posts

티스토리 툴바