본문 바로가기
수업내용

20230525 수업내용🤦‍♂️🤦‍♂️🤦‍♂️

by titlejjk 2023. 5. 25.

직접 방명록을 만들면서

500번, 404오류를 많이 경험했다.

500번 오류는 서버에서 Exception이 발생했을 때(코딩오류)

404번 오류는 요청오류 등이 많이 발생했다.

 

 

jsp 페이지는 서버에서 해석되고 해석된 결과가 클라이언트에게 응답이 된다.

jsp는 servlet에서 해석되어 응답된다.

jsp 페이지에서 ${ }는 특별하게 해석해서 출력한다.

컨텍스트 경로는 손코딩을 하는 것 보다는 

.request.contextPath

를 쓰는 것이 좋다. 나중에 컨텍스트 경로는 프로젝트후에 삭제 또는 수정될 예정이기에 

${pageContext.request.contextPath}

를 사용하는 것이 매우 바람직하다.

이것을 EL Expression Language라고 한다.

 

먼저 guest/list.jsp를 만들어서 list.jsp 페이지에 전체 방명록글 목록을 얻어와서 응답하는 페이지를 만들어야 한다.

전체 목록을 조회하기 위해 ArrayList객체를 만들어야한다.

Dto의 필드선언하기를 통해 필드의 type과 필드명을 정한다.

필드명과 데이터베이스 칼럼명은 동일하게 해주는 것이 좋다. 이렇게 되면 의문이생긴다.

테이블당 dto하나냐?라는 의문이 생기는데 정확히는 주제별 하나당 만드는 것이 좋다.

 

dto를 작성한다음

dao를 작성한다 제일 기본적인 재료로는

package test.guest.dao;

public class GuestDao {
	
	private static GuestDao dao;
	//외부에서 객체 생성하지 못하게
	private GuestDao() {}
	//자신의 참조값을 리턴해주는 메소드
	public static GuestDao getInstance() {
		if(dao == null) {
			dao = new GuestDao();
		}
		return dao;
	}
}

이 필요하다.

	//전체 글의 목록을 리턴해주는 메소드
	public List<GuestDto> getList(){
		//글목록을 담을 객체를 미리 생성
		List<GuestDto> list = new ArrayList<>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			//DbcpBean 객체를 이용해서 Connection 객체를 얻어온다(Connection Pool 에서 얻어오기)
			conn = new DbcpBean().getConn();
			//실행할 sql 문 
			String sql = "SELECT num, writer, content, pwd, regdate"
					+ " FROM board_guest"
					+ " ORDER BY num DESC";
			pstmt = conn.prepareStatement(sql);
			//sql 문이 미완성이라면 여기서 완성
			
			//select 문 수행하고 결과값 받아오기
			rs = pstmt.executeQuery();
			//반복문 돌면서 ResultSet 에 담긴 내용 추출
			while (rs.next()) {
				GuestDto dto = new GuestDto();
				dto.setNum(rs.getInt("num"));
				dto.setWriter(rs.getString("writer"));
				dto.setContent(rs.getString("content"));
				dto.setPwd(rs.getString("pwd"));
				dto.setRegdate(rs.getString("regdate"));//날짜도 getString()으로 읽어온다.
				
				//읽어온 정보가 담긴 dto를 ArrayList객체에 누적시킨다.
				list.add(dto);
			}
		} catch (SQLException se) {
			se.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close(); //Connection 이 Connection Pool 에 반납된다.
			} catch (Exception e) {
			}
		}
//회원목록이 담긴 ArrayList 객체 리턴해 주기 
		return list;
	}

위 getList메소드는 아무것도 전달받지 않아도 List를 Select해서 보여주는 메소드이다.

<%@page import="test.util.DbcpBean"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String cPath = request.getContextPath();
	//DB 연동 가능한지 테스트
	//new DbcpBean(); //객체 생성했을때 예외가 발생하지 않고 "Connection 얻어오기 성공!" 이 콘솔창에 출력되면된다.
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index.jsp</title>
</head>
<body>
	<div class="container">
		<h1>인덱스 페이지 입니다.</h1>
		<!--<p>${pageContext.request.contextPath}</p> ${} EL => Expression Language  -->
		<ul>
			<li><a href = "${pageContext.request.contextPath}/member/list.jsp">회원 목록보기</a></li>
			<li><a href = "${pageContext.request.contextPath}/guest/list.jsp">방명록 목록보기</a></li>
		</ul>
	</div>
</body>
</html>

방명록 글을 입력할수 있는 jsp
방명록에 작성된 글을 DB에 저장할수 있도록 해주어야 하는데 이때는

폼전송되는 방명록 작성자 그리고 글내용을 읽어온 후에 DB에 저장해주도록 하고 결과를 응답해주는 insert.jsp를 만들어준다.

 

 

<!-- 이 주석은 웹브라우저에게 출력되지만 웹브라우저가 무시하는 주석-->

<%-- 이 주석은 jsp 페이지가 무시하는 주석(웹브라우저에 출력되지 않는다.) --%>

<%-- javascript 응답하기 --%>

<%@page import="test.guest.dao.GuestDao"%>
<%@page import="test.guest.dto.GuestDto"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	//1. 삭제할 글의 정보를 읽어온다.
	request.setCharacterEncoding("utf-8");
	int num = Integer.parseInt(request.getParameter("num"));
	String pwd = request.getParameter("pwd");
	//2. DB에서 삭제한다.
	GuestDto dto = new GuestDto();
	dto.setNum(num);
	dto.setPwd(pwd);
	boolean isSuccess = GuestDao.getInstance().delete(dto);
	//3. 응답한다.
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/guest/delete.jsp</title>
</head>
<body>
	<%if(isSuccess){ %>
		<% 
			//삭제 성공이면 list.jsp 로 리다이렉트이동시키기
			String cPath=request.getContextPath();
			response.sendRedirect(cPath + "/guest/list.jsp");
		%>
	<%}else{ %>
	
	<%} %>
</body>
</html>

방명록 삭제를 요청하는 jsp

//삭제 성공이면 list.jsp 로 리다이렉트이동시키기
			String cPath=request.getContextPath();
			response.sendRedirect(cPath + "/guest/list.jsp");
package test.guest.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import test.guest.dto.GuestDto;
import test.util.DbcpBean;

public class GuestDao {
   
   private static GuestDao dao;
   //외부에서 객체 생성하지 못하게
   private GuestDao() {}
   //자신의 참조값을 리턴해주는 메소드 
   public static GuestDao getInstance() {
      if(dao==null) {
         dao=new GuestDao();
      }
      return dao;
   }
   //글하나의 정보를 수정 반영하는 메소드(비밀번호가 일치해야 수정이된다)
   public boolean update(GuestDto dto) {
	   Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	int rowCount = 0;
	try {
		//DbcpBean 객체를 이용해서 Connection 객체를 얻어온다(Connection Pool 에서 얻어오기)
		conn = new DbcpBean().getConn();
		//실행할 sql 문 
		String sql = "UPDATE board_guest"
				+ " SET writer = ?, content = ?"
				+ " WHERE num = ? AND pwd =?";
		pstmt = conn.prepareStatement(sql);
		//sql 문이 미완성이라면 여기서 완성
		pstmt.setString(1, dto.getWriter());
		pstmt.setString(2,  dto.getContent());
		pstmt.setInt(3, dto.getNum());
		pstmt.setString(4, dto.getPwd());
		//select 문 수행하고 결과값 받아오기
		rowCount = pstmt.executeUpdate();
		//반복문 돌면서 ResultSet 에 담긴 내용 추출
	} catch (SQLException se) {
		se.printStackTrace();
	} finally {
		try {
			if (pstmt != null)
				pstmt.close();
			if (conn != null)
				conn.close();
		} catch (Exception e) {
		}
	}
	//만일 변화된 row 의 갯수가 0 보다 크면 작업 성공
	if (rowCount > 0) {
		return true;
	} else {
		return false;
	}

   }
   //글하나의 정보를 리턴하는 메소드
   public GuestDto getData(int num) {
      GuestDto dto=null;
      //필요한 객체의 참조값을 담을 지역변수 미리 만들기
      Connection conn = null;
      PreparedStatement pstmt = null;
      ResultSet rs = null;
      try {
         //DbcpBean 객체를 이용해서 Connection 객체를 얻어온다(Connection Pool 에서 얻어오기)
         conn = new DbcpBean().getConn();
         //실행할 sql 문 
         String sql = "SELECT num, writer, content, pwd, regdate"
               + " FROM board_guest"
               + " WHERE num=?";
         pstmt = conn.prepareStatement(sql);
         //sql 문이 미완성이라면 여기서 완성
         pstmt.setInt(1, num);
         //select 문 수행하고 결과값 받아오기
         rs = pstmt.executeQuery();
         //반복문 돌면서 ResultSet 에 담긴 내용 추출
         while (rs.next()) {
            dto=new GuestDto();
            dto.setNum(num);
            dto.setWriter(rs.getString("writer"));
            dto.setContent(rs.getString("content"));
            dto.setPwd(rs.getString("pwd"));
            dto.setRegdate(rs.getString("regdate"));
         }
      } catch (SQLException se) {
         se.printStackTrace();
      } finally {
         try {
            if (rs != null)
               rs.close();
            if (pstmt != null)
               pstmt.close();
            if (conn != null)
               conn.close(); //Connection 이 Connection Pool 에 반납된다.
         } catch (Exception e) {
         }
      }
      return dto;
   }
   
   //글 하나의 정보를 DB 에서 삭제하는 메소드
   public boolean delete(GuestDto dto) {
      Connection conn = null;
      PreparedStatement pstmt = null;
      int rowCount = 0;
      try {
         conn = new DbcpBean().getConn();
         String sql = "DELETE FROM board_guest"
               + " WHERE num=? AND pwd=?";
         pstmt = conn.prepareStatement(sql);
         //실행할 sql 문이 미완성이라면 여기서 완성
         pstmt.setInt(1, dto.getNum());
         pstmt.setString(2, dto.getPwd());
         //sql 문을 수행하고 변화된(추가, 수정, 삭제된) row 의 갯수 리턴 받기
         rowCount = pstmt.executeUpdate();
      } catch (SQLException se) {
         se.printStackTrace();
      } finally {
         try {
            if (pstmt != null)
               pstmt.close();
            if (conn != null)
               conn.close();
         } catch (Exception e) {
         }
      }
      //만일 변화된 row 의 갯수가 0 보다 크면 작업 성공
      if (rowCount > 0) {
         return true;
      } else {
         return false;
      }
   }
   
   //글 하나의 정보를 DB 에 저장하는 메소드 
   public boolean insert(GuestDto dto) {
      Connection conn = null;
      PreparedStatement pstmt = null;
      int rowCount = 0;
      try {
         conn = new DbcpBean().getConn();
         String sql = "INSERT INTO board_guest"
               + " (num, writer, content, pwd, regdate)"
               + " VALUES(board_guest_seq.NEXTVAL, ?, ?, ?, SYSDATE)";
         pstmt = conn.prepareStatement(sql);
         //실행할 sql 문이 미완성이라면 여기서 완성
         pstmt.setString(1, dto.getWriter());
         pstmt.setString(2, dto.getContent());
         pstmt.setString(3, dto.getPwd());
         //sql 문을 수행하고 변화된(추가, 수정, 삭제된) row 의 갯수 리턴 받기
         rowCount = pstmt.executeUpdate();
      } catch (SQLException se) {
         se.printStackTrace();
      } finally {
         try {
            if (pstmt != null)
               pstmt.close();
            if (conn != null)
               conn.close();
         } catch (Exception e) {
         }
      }
      //만일 변화된 row 의 갯수가 0 보다 크면 작업 성공
      if (rowCount > 0) {
         return true;
      } else {
         return false;
      }
   }
   
   //전체 글의 목록을 리턴해주는 메소드 
   public List<GuestDto> getList(){
      //글목록을 담을 객체를 미리 생성
      List<GuestDto> list=new ArrayList<>();
      //필요한 객체의 참조값을 담을 지역변수 미리 만들기
      Connection conn = null;
      PreparedStatement pstmt = null;
      ResultSet rs = null;
      try {
         //DbcpBean 객체를 이용해서 Connection 객체를 얻어온다(Connection Pool 에서 얻어오기)
         conn = new DbcpBean().getConn();
         //실행할 sql 문 
         String sql = "SELECT num, writer, content, pwd, regdate"
               + " FROM board_guest"
               + " ORDER BY num DESC";
         pstmt = conn.prepareStatement(sql);
         //sql 문이 미완성이라면 여기서 완성

         //select 문 수행하고 결과값 받아오기
         rs = pstmt.executeQuery();
         //반복문 돌면서 ResultSet 에 담긴 내용 추출
         while (rs.next()) {
            GuestDto dto=new GuestDto();
            dto.setNum(rs.getInt("num"));
            dto.setWriter(rs.getString("writer"));
            dto.setContent(rs.getString("content"));
            dto.setPwd(rs.getString("pwd"));
            dto.setRegdate(rs.getString("regdate"));//날짜도 getString() 으로 읽어온다.
            //글정보가 담긴 dto 를 ArrayList 객체에 누적시킨다.
            list.add(dto);
         }
      } catch (SQLException se) {
         se.printStackTrace();
      } finally {
         try {
            if (rs != null)
               rs.close();
            if (pstmt != null)
               pstmt.close();
            if (conn != null)
               conn.close(); //Connection 이 Connection Pool 에 반납된다.
         } catch (Exception e) {
         }
      }
      return list;
   }
}

완성한 방명록 dao

댓글