메뉴 건너뛰기

조회 수 167 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

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

 

 


  1. No Image 31Mar
    by
    2021/03/31 Views 188 

    jsp header의 사용

  2. No Image 28Mar
    by
    2021/03/28 Views 160 

    jsp mybatis sample file and spring mvc

  3. No Image 28Mar
    by
    2021/03/28 Views 194 

    jsp - 각종 체크 &우편번호

  4. No Image 28Mar
    by
    2021/03/28 Views 313 

    jsp - 아이디 체크

  5. No Image 28Mar
    by
    2021/03/28 Views 223 

    jsp - 회원가입

  6. No Image 28Mar
    by
    2021/03/28 Views 21623 

    JSP - 로그인 & AJAX 비동기 방식으로 처리&암호화&정규표현식

  7. No Image 28Mar
    by
    2021/03/28 Views 187 

    JSP - 수정 삭제

  8. JSP - filter 필터 &한글처리

  9. JSP - 메모 상세 & EL

  10. 28Mar
    by 조쉬
    2021/03/28 Views 167 

    JSP - 한줄메모 삽입 & AJAX

  11. JSP - JDBC&데이터 처리 순서&DB CONN 따로 분리

  12. JSP - 태그문자&공백문자&줄바꿈 문자 처리

  13. JSP - 한줄메모 목록 리스트 AJAX

  14. JSP - MVC 패턴 & 도서 목록 컨트롤러에서 해당 URL 받아서 처리하기

  15. JSP - DBCP 커넥션 풀

  16. JSP - 페이지 화면이동 방식

  17. No Image 27Mar
    by
    2021/03/27 Views 183 

    JSP - MYSQL JSP insert 폼에서 servlet으로 값넘기기

  18. No Image 27Mar
    by
    2021/03/27 Views 237 

    JSP - MYSQL JSP 연동 &리스트 뽑아오기

  19. JSP - 환경설정 및 기본개념

  20. No Image 25Mar
    by
    2021/03/25 Views 1477 

    파라미터를 배열 형식으로 받기

Board Pagination Prev 1 2 3 4 Next
/ 4

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved