1월 24일

SJY0000·2022년 1월 24일
0

JSP, SERVLET and DB연동

목록 보기
16/24

오늘 배운 것

  • ToDo 만들기

주소를 "/"로 설정하니 web.xml의 welcome설정과 switch문의 defalut와 충돌해 오류가 발생하고 action의 값들을 "/new"와 같이 주소형태로 했을 시에도 오류가 발생하여 parameter로 받을 수 있도록 변경

  • ToDo 리스트 클릭으로 DB에 등록된 모든 할 일들을 출력할 수 있도록 함
  • JSTL의 반복문 foreach를 이용해 출력
  • 각 row 마다 수정,삭제 버튼을 추가
 <header>
      <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
          <a class="navbar-brand" href="#">TODO APP</a>
          <button
            class="navbar-toggler"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent"
            aria-expanded="false"
            aria-label="Toggle navigation"
          >
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mb-2 mb-lg-0">
              <li class="nav-item">
                <a class="nav-link" href="<%=request.getContextPath()%>/todos?action=list">ToDo 리스트</a>
              </li>
            </ul>
            <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
              <li class="nav-item">
                <a class="nav-link" href="<%=request.getContextPath()%>/logout">로그아웃</a>
              </li>
            </ul>
          </div>
        </div>
      </nav>
    </header>
    <!-- navbar 끝 -->
    <!-- 본문 -->
    <div class="container">
      <h3 class="text-center">DO IT list's</h3>
      <hr />
      <div class="container text-left">
        <a href="<%=request.getContextPath()%>/todos?action=new" class="btn btn-success">할일 추가</a>
      </div>
      <br />
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>제목</th>
            <th>마감 일자</th>
            <th>현재 상태</th>
            <th>액션</th>
          </tr>
        </thead>
        <tbody>
          <!-- 할 일 데이터를 table로 -->
          <c:forEach var="todo" items="${listTodo}">
            <tr>
              <td><c:out value="${todo.title}" /></td>
              <td><c:out value="${todo.targetDate}" /></td>
              <td><c:out value="${todo.status}" /></td>
              <td>
              <a href="<%=request.getContextPath()%>/todos?action=edit&id=${todo.id}" class="btn btn-info btn-sm">수정</a>
              <a href="<%=request.getContextPath()%>/todos?action=delete&id=${todo.id}" class="btn btn-danger btn-sm">삭제</a>
              </td>
            </tr>
          </c:forEach>
        </tbody>
      </table>
    </div>
    <!-- 본문 끝 -->
    <jsp:include page="../common/footer.jsp" />
    <script src="<%=request.getContextPath()%>/js/bootstrap.bundle.min.js"></script>
  </body>
</html>

  • list의 상단 할일 추가 버튼을 클릭시
	private void showNewForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher("todo/todo-form.jsp");
		dispatcher.forward(request, response);
		
	}
  • 저번에 만든 insert메소드를 사용하여 DB에 데이터 추가
	public void insertTodo(Todo todo) {
		String INSERT_USER_SQL = "insert into todos(title, username, description, target_date,is_done) "
				+ "value (?,?,?,?,?)";

		try {
			Connection conn = JDBCUtils.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(INSERT_USER_SQL);
			pstmt.setString(1, todo.getTitle());
			pstmt.setString(2, todo.getUsername());
			pstmt.setString(3, todo.getDescription());
			pstmt.setDate(4, JDBCUtils.getSQLDate(todo.getTargetDate())); // ToDo에 입력된 날짜를 SQL문에 입력될 날짜타입으로 변경
			pstmt.setBoolean(5, todo.isStatus()); // pstmt 완성

			pstmt.executeUpdate(); // pstmt 실행, 결과가 없는 Update, Delete, Drop, Insert 등은 executeUpdate() 사용
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

  • 각 row의 수정버튼 클릭 시 클릭한 row의 id 값을 같이 전송하여 선택한 객체를 수정 할 수 있도록 함
		// 수정할 todo객체를 같이 보냄
		Long id = Long.parseLong(request.getParameter("id"));
		Todo theTodo = todoDAO.selectTodo(id);
		
		request.setAttribute("todo", theTodo);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("todo/todo-form.jsp");
		dispatcher.forward(request, response);
		
	}
  • 저번에 만든 update메소드를 사용하여 DB데이터 수정
	public boolean updateTodo(Todo todo) {
		String UPDATE_SQL = "update todos set description = ?, title = ?, username = ?, target_date = ?, is_done = ? where id = ? ";
		boolean status = false;	
		try {
			Connection conn = JDBCUtils.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(UPDATE_SQL);
			pstmt.setString(1, todo.getDescription());
			pstmt.setString(2, todo.getTitle());
			pstmt.setString(3, todo.getUsername());
			pstmt.setDate(4, JDBCUtils.getSQLDate(todo.getTargetDate()));		
			pstmt.setBoolean(5, todo.isStatus());
			pstmt.setLong(6, todo.getId());

			status = pstmt.executeUpdate() > 0; // 한 줄 이상 Update가 되면 true			
			
		} catch (SQLException e) {
			System.out.println("SQL UPDATE TODO ERROR");
			return false;
		}
		System.out.println("UPDATE 완료");
		return status;
	}

  • description(할 일 설명)을 변경하고 저장을 누른결과 DB에도 변경됨

0개의 댓글

관련 채용 정보