오늘이라도
[Web] 4. SQL 테이블과 연동하여 HTML, Servlet, DTO, DAO 만들기 본문
반응형
https://github.com/upcake/Class_Examples
교육 중에 작성한 예제들은 깃허브에 올려두고 있습니다.
gif 파일은 클릭해서 보는 것이 정확합니다.
- SQL 테이블과 연동하여 HTML, Servlet, DTO, DAO 만들기 -
① SQL 문서 만들기 : Member 테이블 생성
- 원하는 경로 우클릭 - New - Other... - SQL Development - SQL File
- 블록 지정 후 우클릭 - Execute Selected Text(Alt + X)로 SQL문을 실행할 수 있다.
② 회원가입 화면 만들기 : MemberMain.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원가입 입력 화면</title>
</head>
<body>
<form action="s03.do" method="post">
이름 : <input type="text" name="irum" required="required" /><br />
아이디 : <input type="text" name="id" required="required" /><br />
비밀번호 : <input type="password" name="pw" required="required" /><br />
나이 : <input tyape="number" name="age" required="required" /><br />
주소 : <input type="text" name="addr" required="required" /><br />
전화번호 : <input type="text" name="tel" required="required" /><br />
<input type="submit" value="회원가입" />
<input type="reset" value="초기화" />
<input type="button" value="회원 목록 보기" onclick="location.href='s04.do'" />
</form>
<!-- 폼을 완성한 뒤 주소가 제대로 넘어가는지 확인해본다. -->
</body>
</html>
▲회원가입 화면(MemberMain.html)
③ 클라이언트의 요청을 받고 응답할 Servlet 만들기 : Servlet03.java, MemberDTO.java, MemberDAO.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hanul.study.MemberDAO;
import com.hanul.study.MemberDTO;
@WebServlet("/s03.do")
public class Servlet03 extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//① 클라이언트의 요청을 받는다 : 폼의 매개 변수를 가져온다 ▶ HttpServletRequest
request.setCharacterEncoding("utf-8");
//방법 1 : 미리 만들어둔 DTO 클래스 이용
// String irum = request.getParameter("irum");
// String id = request.getParameter("id");
// String pw = request.getParameter("pw");
// int age = Integer.parseInt(request.getParameter("age"));
// String addr = request.getParameter("addr");
// String tel = request.getParameter("tel");
//방법 2 : 매개 변수 가져오면서 DTO 생성
MemberDTO dto = new MemberDTO();
dto.setIrum(request.getParameter("irum"));
dto.setId(request.getParameter("id"));
dto.setPw(request.getParameter("pw"));
dto.setAge(Integer.parseInt(request.getParameter("age")));
dto.setAddr(request.getParameter("addr"));
dto.setTel(request.getParameter("tel"));
//② 비즈니스 로직 : DataBase 연동(DTO, DAO)
// MemberDTO dto = new MemberDTO(irum, id, pw, age, addr, tel);
MemberDAO dao = new MemberDAO();
int succ = dao.memberInsert(dto);
//③ 프레젠테이션 로직(결과를 응답) : *.html, *.jsp ▶ HttpServletResponse
response.setContentType("text/html; charset=utf-8"); //MIME Type
PrintWriter out = response.getWriter();
if(succ > 0) {
out.println("<script>alert('회원가입 성공!');</script>");
out.println("<a href='MemberMain.html'>회원가입 화면</a>");
out.println("<br />");
out.println("<a href='s04.do'>회원 목록 보기</a>");
} else {
out.println("<script>alert('회원가입 실패!');</script>");
out.println("<a href='MemberMain.html'>회원가입 화면</a>");
out.println("<br />");
out.println("<a href='s04.do'>회원 목록 보기</a>");
} //if
} //service()
} //class
▲s03.do(Servlet03.java)
package com.hanul.study;
import java.io.Serializable;
public class MemberDTO implements Serializable {
private String irum;
private String id;
private String pw;
private int age;
private String addr;
private String tel;
public MemberDTO() {}
public MemberDTO(String irum, String id, String pw, int age, String addr, String tel) {
super();
this.irum = irum;
this.id = id;
this.pw = pw;
this.age = age;
this.addr = addr;
this.tel = tel;
}
public String getIrum() {
return irum;
}
public void setIrum(String irum) {
this.irum = irum;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
▲MemberDTO.java
package com.hanul.study;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class MemberDAO {
private Connection conn; //연결 객체
private PreparedStatement ps; //전송 객체
private ResultSet rs; //결과 객체
//DB 접속 : 정적 로딩(ojdbc6.jar ▶ WebContent → WEB-INF → lib 붙여넣기)
public Connection getConn() {
String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
String user = "hanul";
String password = "0000";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
System.out.println("getConn() Exception!!!");
}
return conn;
} //getConn()
//회원가입
public int memberInsert(MemberDTO dto) {
conn = getConn();
String sql = "INSERT INTO member VALUES(?, ?, ?, ?, ?, ?)";
int succ = 0;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, dto.getIrum());
ps.setString(2, dto.getId());
ps.setString(3, dto.getPw());
ps.setInt(4, dto.getAge());
ps.setString(5, dto.getAddr());
ps.setString(6, dto.getTel());
succ = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
System.out.println("memberInsert() Exception!!!");
} finally {
dbClose();
}
return succ;
} //memberInsert()
//전체 회원 검색
public ArrayList<MemberDTO> memberSearchAll() {
conn = getConn();
String sql = "SELECT * FROM member";
ArrayList<MemberDTO> list = new ArrayList<>();
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
String irum = rs.getString("irum");
String id = rs.getString("id");
String pw = rs.getString("pw");
int age = rs.getInt("age");
String addr = rs.getString("addr");
String tel = rs.getString("tel");
MemberDTO dto = new MemberDTO(irum, id, pw, age, addr, tel);
list.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("memberSearchAll Exception!!!");
} finally {
dbClose();
}
return list;
} //memberSearchAll()
//DB Close
public void dbClose() {
try {
if(rs != null) rs.close();
if(ps != null) ps.close();
if(conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("dbClose() Exception!!!");
}
} //db Close
} //class
▲MemberDAO.java
④ 회원 목록 보기 버튼, 기능, 화면 추가 : Servlet04.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hanul.study.MemberDAO;
import com.hanul.study.MemberDTO;
@WebServlet("/s04.do")
public class Servlet04 extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//비즈니스 로직 : 전체 회원 목록을 검색하는 메서드 호출 ▶ memberSearchAll()
MemberDAO dao = new MemberDAO();
ArrayList<MemberDTO> list = dao.memberSearchAll();
//프레젠테이션 로직 : list의 값을 출력 → *.html, *.jsp
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("[전체 회원 목록 보기]");
out.println("<br />");
out.println("<table border='1'>");
out.println("<tr>");
out.println("<th>이름</th>");
out.println("<th>아이디</th>");
out.println("<th>비밀번호</th>");
out.println("<th>나이</th>");
out.println("<th>주소</th>");
out.println("<th>전화번호</th>");
out.println("</tr>");
for (MemberDTO dto : list) {
out.println("<tr align='center'>");
out.println("<td>" + dto.getIrum() + "</td>");
out.println("<td>" + dto.getId() + "</td>");
out.println("<td>" + dto.getPw() + "</td>");
out.println("<td>" + dto.getAge() + "</td>");
out.println("<td>" + dto.getAddr() + "</td>");
out.println("<td>" + dto.getTel() + "</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("<br />");
out.println("<a href='MemberMain.html'>회원가입 화면</a>");
}
}
▲s04.do(Servlet04.java)
반응형
'취업성공패키지 SW 개발자 교육 > Web' 카테고리의 다른 글
[Web] 6. NCS 평가 프로젝트 : 작성 조건, 도서 정보 입력, 조회, 삭제 구현 (0) | 2020.05.13 |
---|---|
[Web] 5. 회원 목록 삭제 추가, 정적 페이지 전환, 동적 페이지 전환 : forward(), sendRedirect() (0) | 2020.05.12 |
[Web] 3. Servlet 생성하는 방법, HelloServlet, 누적합 계산 ①, ② (0) | 2020.05.08 |
[Web] 2. 회원가입 화면 만들기 : index 작성, Servlet, web.xml, JSP (4) | 2020.05.07 |
[Web] 1. Java EE 개발 환경 구축 (1) | 2020.05.06 |