메뉴 건너뛰기

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

단축키

Prev이전 문서

Next다음 문서

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

단축키

Prev이전 문서

Next다음 문서

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

1리스트에서 도서등록 버튼 누르면 2 insert.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
   <%@page import="book.*"%> 
   <%@page import="java.util.ArrayList"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<h2> 도서목록</h2>
 
<input type="button" value="도서등록"
    onclick="location.href='insert.jsp' "
>
 
 
<table border="1"
 
    <tr>
                <th>번호</th>    
                <th>도서명</th>
                <th>저자</th>
                <th>가격</th>
                <th>수량</th>
    
    </tr>
 
 
<%
        BookDAO dao=new BookDAO();
        //dao.dbConn();   db 연결 확인 작업
        
         ArrayList<bookDTO>list=dao.bookList();
         for(bookDTO dto:list){
                     
%>
 
        <tr>
                <td><%=dto.getId() %></td>
                <td><%=dto.getTitle() %></td>
                <td><%=dto.getAuthor() %></td>
                <td><%=dto.getPrice() %></td>
                <td><%=dto.getQty() %></td>
        
        </tr>
 
 
 
<%
 
         } //for 문의 끝
%>
 </table>
 
</body>
</html>
cs

 

 

 

 

2. insert.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
<%@ 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() {
 
        $("#btnAdd").click(function() { //버튼 클릭이벤트
 
            var title = $("#title").val(); //태그입력값
            var author = $("#author").val();
            var price = $("#price").val();
            var qty = $("#qty").val();
 
            if (title == "") { //빈값이면
 
                alert("도서명을 입력하세요")
                $("#title").focus(); //입력포커스 이동
                return//함수 종료
 
            }
 
            if (author == "") {
 
                alert("저자명을 입력하세요")
                $("#author").focus();
                return;
 
            }
 
            if (price == 0) {
 
                alert("가격을 입력하세요")
                $("#price").focus();
                return;
 
            }
 
            if (qty == 0) {
 
                alert("수량을 입력하세요")
                $("#qty").focus();
                return;
 
            }
 
            /* 폼에 입력한 데이터를 서버로 전송 */
            document.form1.submit();
        });
 
    });
</script>
 
</head>
<body>
    <!-- request.getContextPath() = 컨택스트 페스를 리턴함 -->
    a
    <!-- ction ="/컨텍스트/가상디렉토리 / 서블릿 url" -->
    <!-- id 는 jsp에서 쓸 것이고 name은 서블릿에서 사용할 것이다. -->
    <h2>도서 정보 등록</h2>
 
    <form name="form1" method="post"
        action="<%=request.getContextPath()%>/book_servlet/insert.do">
 
        <table border="1">
            <tr>
                <td>도서명</td>
                <td><input name="title" id="title"></td>
            </tr>
 
            <tr>
                <td>저자</td>
                <td><input type="text" name="author" id="author"></td>
            </tr>
 
 
            <tr>
                <td>가격</td>
                <td><input type="number" name="price" id="price" required></td>
            </tr>
 
            <tr>
                <td>수량</td>
                <td><input type="number" name="qty" id="qty" required></td>
            </tr>
 
 
            <tr>
                <td colspan="2" align="center"><input type="button" id="btnAdd"
                    value="확인"> <input type="reset" value="취소"></td>
            </tr>
 
 
        </table>
 
    </form>
 
</body>
</html>
cs
 
 

 

3. bookController (서블릿)

 

 

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
package book;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
//url patter 지정 
//
 
@WebServlet("/book_servlet/*")
public class BookController extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        System.out.println("서블릿 호출");
 
        // 한글처리
        request.setCharacterEncoding("utf-8");
 
        // 컨텍스트 페스 경로가져오기
        String context = request.getContextPath();
        // DAO생성
        BookDAO dao = new BookDAO();
        // 폼에서 입력 받은 데이터를 DTO에 저장
 
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        int price = Integer.parseInt(request.getParameter("price"));
        int qty = Integer.parseInt(request.getParameter("qty"));
 
        bookDTO dto = new bookDTO(title, author, price, qty);
 
        // 테이블에 저장
        dao.bookInsert(dto);
 
        // 페이지 이동
        response.sendRedirect(context + "/book/book_list.jsp");
 
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        doGet(request, response);
    }
 
}
 
cs


 

 

 

 

4. 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
152
153
154
155
156
157
158
159
package book;
 
// jdbc import
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
 
public class BookDAO {
 
    // db접속
    public Connection dbConn() {
 
        Connection conn = null// db접속 객체
 
        try {
            // mysql jdbc driver 로딩
            Class.forName("com.mysql.jdbc.Driver");
 
            // db연결 문자열 but 이방법은 보안에 취약하다. ..
            String url = "jdbc:mysql://localhost:3306/java";
            String id = "java"// mysql 접속아이디
            String pwd = "java1234"// mysql 접속 비번
 
            // db 접속
 
            conn = DriverManager.getConnection(url, id, pwd);
            System.out.println("db접속 성공");
        } catch (Exception e) {
            // db관련작업은 반드시 익셉션 처리
            System.out.println("db접속 실패");
            e.printStackTrace();
        }
        return conn;
 
    }
 
    // 북리스트
    public ArrayList<bookDTO> bookList() {
 
        ArrayList<bookDTO> list = new ArrayList<bookDTO>();
        Connection conn = null// DB접속 객체
        PreparedStatement pstmt = null// SQL실행객체
        ResultSet rs = null// 결과셋 처리 객체
 
        try {
            conn = dbConn(); // db연결 키
            String sql = "select * from book_table";
            pstmt = conn.prepareStatement(sql); // sql을 실행시키는 객체 만들어짐
            rs = pstmt.executeQuery(); // 실행 후 결과 값이 rs에 넘어옴
 
            while (rs.next()) { // 결과셋.next(); 다음 레코드가 있으면 true
 
                bookDTO dto = new bookDTO();
                dto.setId(rs.getInt("id"));
                dto.setTitle(rs.getString("title"));
                dto.setAuthor(rs.getString("author"));
                dto.setPrice(rs.getInt("price"));
                dto.setQty(rs.getInt("qty"));
 
                // ArrayList에 추가
                list.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 list;
    }
    //삽입
    public void bookInsert(bookDTO dto) {
        
        Connection conn = null// DB접속 객체
        PreparedStatement pstmt = null// SQL실행객체
        
        try{
            
            conn=dbConn();
            
            String sql="insert into book_table(title, author, price, qty)"+" values(?,?,?,?)";
            
            
            //sql 실행객체 생성
            pstmt=conn.prepareStatement(sql);
            
            //? 에 입력될 값 매핑
            pstmt.setString(1, dto.getTitle());
            pstmt.setString(2, dto.getAuthor());
            pstmt.setInt(3, dto.getPrice());
            pstmt.setInt(4, dto.getQty());
            
            //executeQuery() select 명령어
            //executeUpdate select 이외 명령어
            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();
            }
 
            
        }
        
    }
 
}
 
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 197 

    jsp - 각종 체크 &우편번호

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

    jsp - 아이디 체크

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

    jsp - 회원가입

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

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

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

    JSP - 수정 삭제

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

  9. JSP - 메모 상세 & EL

  10. 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 185 

    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