Servlet을 사용할 때, DB는 어떻게 연결을 했을까?
다양한 방법으로 소개를 하고 추후 이를 토대로 발전사를 정리해보고자 한다.
앞으로 다뤄볼 내용의 구조는 다음과 같다.
servletController - memberDAO - memberVO
servletController : 요청에 대한 처리를 할 Servlet
memberDAO : DB 처리할 Servlet
memberVO : DB와 관련된 객체를 담을 Servlet
// Controller
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// MemberDAO 객체 선언
MemberDAO dao=new MemberDAO();
// MemberDAO 객체의 메서드 중 listMembers()호출 후 반환값 담기
List<MemberVO> list=dao.listMembers();
// VO의 메서드를 통해 출력
for (int i=0; i<list.size();i++){
MemberVO memberVO=(MemberVO) list.get(i);
String id=memberVO.getId();
String pwd = memberVO.getPwd();
String name=memberVO.getName();
String email=memberVO.getEmail();
Date joinDate = memberVO.getJoinDate();
}
}
// VO
private String id;
private String pwd;
private String name;
private String email;
private Date joinDate;
public MemberVO() {
System.out.println("MemberVO 생성자 호출");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getJoinDate() {
return joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
// DAO
// DB 연결 정보
private static final String driver = "oracle.jdbc.driver.OracleDriver";
private static final String url = "jdbc:oracle:thin:@localhost:1521:XE";
private static final String user = "id";
private static final String pwd = "pwd";
private Connection con;
private Statement stmt;
public List<MemberVO> listMembers() {
List<MemberVO> list = new ArrayList<MemberVO>();
try {
connDB();
String query = "select * from jaemin.t_member ";
System.out.println(query);
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String id = rs.getString("id");
String pwd = rs.getString("pwd");
String name = rs.getString("name");
String email = rs.getString("email");
Date joinDate = rs.getDate("joinDate");
MemberVO vo = new MemberVO();
vo.setId(id);
vo.setPwd(pwd);
vo.setName(name);
vo.setEmail(email);
vo.setJoinDate(joinDate);
list.add(vo);
}
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
private void connDB() {
try {
Class.forName(driver);
System.out.println("Oracle 드라이버 로딩 성공");
con = DriverManager.getConnection(url, user, pwd);
System.out.println("Connection 생성 성공");
stmt = con.createStatement();
System.out.println("Statement 생성 성공");
} catch (Exception e) {
e.printStackTrace();
}
}
'Server Development > Serlvet' 카테고리의 다른 글
Servlet - Cookie And Session (0) | 2023.03.21 |
---|---|
Servlet - ServletContext (0) | 2023.03.21 |
Servlet - Binding (0) | 2023.03.21 |
Servlet - Forwarding (0) | 2023.03.21 |
Servlet - Get, Post (0) | 2023.03.21 |