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

10.JSP - 한줄메모 삽입 & AJAX

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

한줄메모 삽입 & 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



반응형

댓글