Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

게으른 완벽주의자의 개발자 도전기

DB와 연결하여 데이터 이동하기1(Controller, DAO, JDBCUtil 만들기) 본문

servlet jsp

DB와 연결하여 데이터 이동하기1(Controller, DAO, JDBCUtil 만들기)

머리방울 2022. 7. 31. 21:35

쌤이 실무에서는 controller(servlet)과 DTO 그리고 데이터베이스를 연결 해제 

데이터베이스 조회 삽입 삭제 수정등의 작업을 하는 각각의 페이지를 만들어서

사용한다고 했다.

 

<MVC패턴>

Model : 비즈니스 로직(기능) -> DAO(class생성)

View : 화면(jsp)
Controller : 요청에 따라 응답하는 페이지(servlet)

앞서 기본틀을 각각 실행할 servlet에 작성하면 될 줄 알았는데 그렇게하면

똥코팅이라고 욕먹는다고...ㅋㅋㅋㅋ 얼른 익혀둬야겠다.

 

회원관리 프로그램 만들기

이제는 DB를 연결해서 실제로 데이터를 주고 받는 작업을 해볼 것이다!

servlet에 아래와 같이 package를 만들어 각각의 페이지를 만들어 주었다.

 

1. DAO, JDBCUtil

 1) DAO (Data Access Object ->  DB에 접근하겠다.)

데이터베이스(DB) 기능을 담당할 클래스를 만들어 준다.
 나는 회원(Member)관리 프로그램을 만들 것이기 때문에 memberDAO로 만듦

  
public class MemberDAO {

(변수 생성)
private Connection conn; 
private PreparedStatement stmt;
private ResultSet rs;
private String sql;

 

2) JDBCUtil 만들기

데이터베이스(DB) 연결과 해제를 담당하는 클래스를 만들어 준다.

다른 클래스에 만들었으니 static으로 공용으로 사용하게 만들어 준다. 

 

public class JDBCUtil {


 i) 자바와 DB를 연결시켜주는 메소드 생성

public static Connection getConnection() {

 - 자바 DB연결 객체
Connection conn = null; 

try {
 - DB 연결 정보 받아옴
Context init= new InitialContext();  
DataSource ds = (DataSource)init.lookup("java:comp/env/jdbc/OracleDB"); 

- DB와 자바를 연결
conn = ds.getConnection();

}catch(Exception e) {
e.printStackTrace();
System.out.println("JDBCUtil -> getConnection() 메소드 오류");
}

return conn;

}

ii) 사용한 객체를 소멸시키는 메소드 생성
public static void close(ResultSet rs, PreparedStatement stmt, Connection conn) {
try {
if(rs != null) {

rs.close();
}

if(stmt != null) {
stmt.close();

}

if(conn != null) {

conn.close();
}


}catch(Exception e) {
e.printStackTrace();
}


}

}

 

3. controller 만들기

1) 데이터베이스의 기능을 담당할 DAO를 사용하기 위해서 객체를 생성해준다

위치는 servlet 클래스 실행하는 곳에 넣어준다.

MemberDAO memberDAO = new MemberDAO();  

 

2) 기본틀 만들기

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}

protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


(한글 인코딩 처리)
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");

String requestURI = request.getRequestURI();
String contextPath = request.getContextPath();
String command = requestURI.substring(contextPath.length());

String page = "";
boolean isRedirect = false;

 

if(command.equals.("/    ")) {

 

page = "  ";

}

else if(command.equals.("/   ")) {

 

page= " ";

}

 

if(isRedirect) {
response.sendRedirect(page);
}
else {
RequestDispatcher dispatcher = request.getRequestDispatcher(page);
dispatcher.forward(request, response);
}