1월 28일(2)

SJY0000·2022년 2월 1일
0

JSP, SERVLET and DB연동

목록 보기
22/24

오늘 배운 것

  • 연락처App 완성하기(1)

DB데이터를 받을 메소드 생성

	public ContactDAO(DataSource dataSource) {
		this.dataSource = dataSource; // 객체 생성시 Connection pool에 DataSource를 입력
	}
	
	// 모든 연락처를 list로 return
	public List<Contact> findAll() {
		List<Contact> list = new ArrayList<Contact>();
		
		try {
			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement("select * from contacts");
			rs = pstmt.executeQuery();
			
			while (rs.next()) {
				Contact contact = new Contact();
				contact.setId(rs.getInt("id"));
				contact.setName(rs.getString("name"));
				contact.setEmail(rs.getString("email"));
				contact.setPhone(rs.getString("phone"));
				
				list.add(contact);
			}
		} catch (SQLException e) {
			System.out.println("SQL에러");
		} finally {
			closeAll();
		}
		
		return list;
	}

Controller에서 DB데이터를 'contacts'에 저장하고 list.jsp로 이동시킴

	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Contact> list = contactDao.findAll();
		request.setAttribute("contacts", list);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("contact/list.jsp");
		dispatcher.forward(request, response);

넘어온 data를 table을 이용하여 각 row에 수정,삭제 버튼을 추가하고 출력

        <table class="table table-hover">
        	<thead>
            	<tr>
                	<th>#</th>
                    <th>이름</th>
                    <th>이메일</th>
                    <th>연락처</th>
                    <th width="5%">&nbsp;</th>
                    <th width="5%">&nbsp;</th>
                </tr>
            </thead>
            <tbody>
            <c:forEach var="contact" items="${contacts}">
            	<tr>
                	<td><c:out value="${contact.id}" /></td>
                    <td><c:out value="${contact.name}" /></td>
                    <td><c:out value="${contact.email}" /></td>
                    <td><c:out value="${contact.phone}" /></td>
                    <td>
                    	<button type="button" class="btn btn-info btn-sm btn-edit" data-id="<c:out value='${contact.id}' />">
                    		수정
                    	</button>
                    </td>
                    <td>
                    	<button type="button" class="btn btn-danger btn-sm btn-delete" data-id="<c:out value='${contact.id}' />" data-toggle="modal" data-target="#modal-delete">
                                                        삭제
                        </button>
                    </td>
                </tr>
            </c:forEach>
            </tbody>
        </table>

추가버튼을 클릭 시

  • modal창을 불러옴
			<button type="button" class="btn btn-primary btn-add" data-toggle="modal" data-target="#modal-add-update">
				추 가 
			</button>
  • modal창에 form문을 이용하여 작성한 데이터 전송
    <div class="modal fade" id="modal-add-update" tabindex="-1" aria-labelledby="addUpdateLabel" aria-hidden="true">
	    <div class="modal-dialog">
	        <div class="modal-content">
	            <div class="modal-header">
	                <h5 id="title-add-upd" class="modal-title"></h5>
	                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
	                    <span aria-hidden="true">&times;</span>
	                </button>
	            </div>
	            <form autocomplete="off" action="<%= request.getContextPath()%>/Contacts">
	            <input type="hidden" name="action" value="post" > 
		            <div class="modal-body">
	                	<div class="form-group">
		                    <label for="name">name</label>
		                    <input type="text" class="form-control" id="name" name="name" required>
		                </div>
		
		                <div class="form-group">
		                    <label for="email">Email</label>
		                    <input type="email" class="form-control" id="email" name="email" required>
		                </div>
		
		                <div class="form-group">
		                    <label for="phone">phone</label>
		                    <input type="text" class="form-control" id="phone" name="phone" required maxlength="15">
		                </div>
		            </div>
		            <div class="modal-footer">
		            	<button type="submit" class="btn btn-success btn-action">저장</button>
		                <button type="button" class="btn btn-secondary btn-action" data-dismiss="modal">취소</button>
		            </div>
	            </form>
	        </div>
	    </div>
	</div>
  • Controller로 Data전송받아 DB에 저장
	private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF8");
		
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		
		Contact contact = new Contact(name, email, phone);
		
		contactDao.save(contact);
		
		response.sendRedirect("Contacts?action=list");
	}
  • DB저장 메소드
	public boolean save(Contact contact) {
		boolean rowAffected = false;
		try {
			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement("insert into contacts(name, email, phone) values(?,?,?)");
			
			pstmt.setString(1, contact.getName());
			pstmt.setString(2, contact.getEmail());
			pstmt.setString(3, contact.getPhone());
			
			rowAffected = pstmt.executeUpdate() > 0;
		} catch (SQLException e) {
			System.out.println("DB 저장 실패");
		}
		return rowAffected;
	}


0개의 댓글