본문 바로가기
매일코딩/JSP

11.JSP - 수정 삭제

by 인생여희 2016. 11. 11.
반응형

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


반응형

댓글