심심한 개발자의 취미생활

본 글은 victolee님의 포스팅을 보고 따라 학습하며 내용을 정리한 포스팅 입니다.

Servlet / DAO / VO(DTO)

DAO(Data Access Object)
VO(Value Object) / DTO(Data Transfer Object)

  • DAO
    • DB 질의를 통해 데이터에 접근하는 객체
  • VO
    • DB 테이블의 컬럼 값을 java에서 객체로 다루기 위한 객체

JDBC 설정

  • JDBC 라이브러치 추가(이전 JDBC 라이브러리 추가 방법 참조)
  • Deployment Assembly 설정
  1. 프로젝트 Properties -> Deployment Assemply -> Add...
  2. Jaav Build Path Entries -> 이전에 생성한 JDBC 라이브러리 선택 -> Apply

Dao 클래스 생성

public class UserDao {
	private Connection getConnection() throws SQLException {
		Connection conn = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			
			String url = "jdbc:mysql://localhost/연결DB명";
			conn = DriverManager.getConnection(url, 아이디, 패스워드);
		} catch (ClassNotFoundException e) {
			System.out.println("드라이버 로딩 실패");
		}
		
		return conn;
	}
	
	public boolean insert(UserVo vo) {
		boolean result = false;
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try {
			conn = getConnection();
			
			String sql = "INSERT INTO USER VALUES (null, ?, ?, ?)";
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, vo.getName());
			pstmt.setString(2, vo.getEmail());
			pstmt.setString(3, vo.getPwd());
			
			int count = pstmt.executeUpdate();
			
			result = (count == 1);
		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(conn != null && !conn.isClosed()) {
					conn.close();
				}
				if(pstmt != null && !pstmt.isClosed()) {
					pstmt.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return result;
	}
	
	public UserVo select(UserVo vo) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		UserVo resultVo = new UserVo();
		
		try {
			conn = getConnection();
			
			String sql = "SELECT NAME, EMAIL, PWD FROM USER WHERE NAME = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, vo.getName());
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				resultVo.setName(rs.getString(1));
				resultVo.setEmail(rs.getString(2));
				resultVo.setPwd(rs.getString(3));
			}
		} catch (SQLException e) {
			System.out.println("Query Error : " + e);
			e.printStackTrace();
		} finally {
			try {
				if(conn != null && !conn.isClosed()) {
					conn.close();
				}
				if(pstmt != null && !pstmt.isClosed()) {
					pstmt.close();
				}
			} catch(SQLException e) {
				e.printStackTrace();
			}
		}
		return resultVo;
	}
}

Servlet 작성

protected void doGet(HttpServletRequest, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");

    UserVo vo = new UserVo();
    vo.setName(request.getParameter("name"));
    vo.setEmail(request.getParameter("email"));
    vo.setPwd(request.getParameter("pwd"));

    UserDao dao = new UserDao();
    dao.select(vo);
    dao.insert(vo);

    response.sendRedirect("/Project/index.jsp");
}
  • 클라이언트에게 응답 페이지를 보여주기 위한 redirect 작성