-
Wed/Feb/05 [Java] day25. DAO Model 활용Study/2020 국비교육_Java 2020. 2. 5. 09:55
Wed/Feb/05
[Java] day25.
- Java
DATABASE
DAO와 DTO
DTO : Data Transfer Object → JoinModel.java
-
DB안에 있는 table의 field 값들을 이동
-
VO (Value Object) 객체 / Java Beans 객체 / MVC pattern의 Model 객체
-
Frame-work
-
DB관련 = myBatis
-
Code/개발 관련 = Spring
-
전자정부2.0~현재까지 표준 = myBatis+Spring
-
과거 전자정부 표준 = Hibanate(DB) + Struts(개발)
-
-
주의점
-
모든 변수는 private 접근 제한자 - getter / setter 반드시 존재
-
sql table field 명과 동일하게 변수 선언
-
DAO - DB Class → JoinDAO.java
-
지금까지는 1개 project 에 1개 table만 실습했지만,
-
실무에서는 다수의 table 사용 - 다수의 DB Class / Servlet 필요
* XML 문서 특징
-
태그 X
-
선언문 : <?xml **** ?>
-
확장자 : .xml
-
RSS / ATOM 등에서 사용; 회사별로 태그 만들어줌
-
Schema : W3에서 만든 기본 Schema 이용 ;
-
eclipse 등 에디터에서 오류 안 잡아주고, 오류시 심각한 오류 가능성 ; 띄어쓰기 오타 반드시 주의!
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
-
xml 수정 시 서버 재가동 필수
DAO 예제) 회원가입 입력과 목록
-
단순 가입 버튼 클릭 - doGet() - response.sendRedirect("")
-
Write Form <FORM method = "POST" > - doPost()
mySQL file
joinDAO.java
/* * 회원 가입 DAO Class (DB Query 실행) * @since 2020.02.05 * @author 위정훈 */ package com.wjh.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import com.wjh.model.JoinModel; public class JoinDAO { public JoinDAO() { } private Connection conn = null; private Statement stmt = null; private PreparedStatement pstmt = null; private ResultSet rs = null; private final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private final String DB_URL = "jdbc:mysql://localhost:3306/dao_db"; private final String DB_ID = "root"; private final String DB_PW = "1234"; /* * 사용할 객체 close * * @param rs * * @param stmt * * @param pstmt * * @param conn * * 최근 사용한 것부터 차례대로 close, * 사용하지 않은 객체 parameter에는 null 값 입력하면 됨 */ public void close(ResultSet rs, Statement stmt, PreparedStatement pstmt, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { System.out.println("ERR_rs.close : " + e.getMessage()); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { System.out.println("ERR_stmt.close : " + e.getMessage()); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { System.out.println("ERR_pstmt.close : " + e.getMessage()); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { System.out.println("ERR_conn.close : " + e.getMessage()); } } } private void connectDAO() { try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, DB_ID, DB_PW); // System.out.println("SUCCESS_get_conn"); } catch (ClassNotFoundException e) { System.out.println("ERR_get_conn_DriverLoading" + e.getMessage()); } catch (SQLException e) { System.out.println("ERR_get_conn_DBConnection" + e.getMessage()); } } // get_conn /* * DB table 조회 */ public ArrayList<JoinModel> select_all() { this.connectDAO(); String query = "select * from dao_table"; // ArrayList를 사용하여 ResultSet을 JoinModel 객체에 저장 ArrayList<JoinModel> list = null; try { this.stmt = this.conn.createStatement(); this.rs = stmt.executeQuery(query); list = new ArrayList<JoinModel>(); while(rs.next()){ JoinModel jm = new JoinModel(); jm.set_num(rs.getInt(1)); jm.set_id(rs.getString(2)); jm.set_pw(rs.getString(3)); jm.set_email(rs.getString(4)); jm.set_phone(rs.getString(5)); list.add(jm); } // while } catch (SQLException e) { System.out.println("ERR_select_all : " + e.getMessage()); } finally { this.close(rs, stmt, null, conn); } return list; } /* * DB table insert joinModel에서 초기값을 ""로 설정했기 때문에 값이 없는 parameter를 넣어도 실행됨 */ public void insert(JoinModel joinModel) { this.connectDAO(); String query = "insert into dao_table (id, pw, email, phone) values (?, ?, ?, ?)"; try { System.out.println("ID___"+joinModel.get_id()); System.out.println("PW___"+joinModel.get_pw()); System.out.println("EMAIL___"+joinModel.get_email()); System.out.println("PHONE___"+joinModel.get_phone()); this.pstmt = this.conn.prepareStatement(query); this.pstmt.setString(1, joinModel.get_id()); this.pstmt.setString(2, joinModel.get_pw()); this.pstmt.setString(3, joinModel.get_email()); this.pstmt.setString(4, joinModel.get_phone()); this.pstmt.executeUpdate(); } catch (SQLException e) { System.out.println("ERR_insert : " + e.getMessage()); } finally { this.close(null, null, pstmt, conn); } } // insert() }
joinModel.java > getter - setter
public class JoinModel { public JoinModel() { } private int num = 0; private String id = ""; private String pw = ""; private String email = ""; private String phone = ""; public int get_num() { return num; } public void set_num(int num) { this.num = num; } public String get_id() { return id; } public void set_id(String id) { this.id = id; } public String get_pw() { return pw; } public void set_pw(String pw) { this.pw = pw; } public String get_email() { return email; } public void set_email(String email) { this.email = email; } public String get_phone() { return phone; } public void set_phone(String phone) { this.phone = phone; } }
index.html > doGET
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Index.html</title> </head> <body> <div align="center"> <h1>.GET TEST</h1> <fieldset> <legend>JoinInsertServlet 을 GET 방식으로 요청</legend> <br>↓↓↓ CLICK ↓↓↓<br> <br> <input type="button" VALUE="WRITE" onclick="location.href = 'insert'" /> </fieldset><p> <fieldset> <legend>JoinListServlet 을 GET 방식으로 요청</legend> <br>↓↓↓ CLICK ↓↓↓<br> <br> <input type="button" VALUE="LIST" onclick="location.href = 'list'" /> </fieldset> </div> </body> </html>
joinWriter.jsp > doPOST
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Join Form</title> </head> <body> <div align="center"> <h1>Join Form</h1> <form action="insert" method="POST"> <table> <tr> <td>ID</td> <td><input type="text" name="ID" required pattern="\w+" /></td> </tr> <tr> <td>PW</td> <td><input type="password" name="PW" required /></td> </tr> <tr> <td>e-mail</td> <td><input type="email" name="EMAIL" /></td> </tr> <tr> <td>Phone</td> <td><input type="text" name="PHONE" pattern="010-(\d{4}|\d{3})-\d{4}" /></td> </tr> </table> <p> <input type="submit" value="SAVE" /> <input type="reset" value="CANCEL" onclick = "location.href = 'index.html'" /> </form> </div> </body> </html>
joinInsertServlet.java
import java.io.IOException; import javax.servlet.RequestDispatcher; 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.wjh.dao.JoinDAO; import com.wjh.model.JoinModel; @WebServlet("/insert") public class joinInsert extends HttpServlet { private static final long serialVersionUID = 1L; // JoinDAO 객체 선언 private JoinDAO JoinDAO = null; public joinInsert() { super(); } /* * @see GET 접근(가입하기 button → Join Form) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher request_dispatcher = request.getRequestDispatcher("joinWrite.jsp"); request_dispatcher.forward(request, response); } /* * @see POST 접근 () */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // POST 방식에서는 한글 parameter의 encoding이 깨짐 // setCharacterEncoding으로 encoding 재설정 request.setCharacterEncoding("UTF-8"); String id = request.getParameter("ID"); String pw = request.getParameter("PW"); String email = request.getParameter("EMAIL"); String phone = request.getParameter("PHONE"); /* * System.out.println("id___" + id); * System.out.println("pw___" + pw); * System.out.println("email___" + email); * if(phone!=null){ * System.out.println("phone___" + phone+"\n"); * } * 입력 값 없이 parameter만 넘어와도 null이 찍히지 않음 */ // JoinModel 객체 생성 JoinModel model = new JoinModel(); model.set_id(id); model.set_pw(pw); model.set_email(email); model.set_phone(phone); // JoinDAO 이용해 내용 입력 this.JoinDAO = new JoinDAO(); this.JoinDAO.insert(model); response.sendRedirect("index.html"); } }
joinList.java
package com.wjh.servlets; import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; 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.wjh.dao.JoinDAO; import com.wjh.model.JoinModel; @WebServlet("/list") public class joinList extends HttpServlet { private static final long serialVersionUID = 1L; // JoinDAO 객체 생성 private JoinDAO joinDAO = null; public joinList() { super(); } /* * @see GET 접근 = joinList 화면 접근 */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.joinDAO = new JoinDAO(); ArrayList<JoinModel> jl = this.joinDAO.select_all(); /* System.out.println("Print JoinModel"); for(JoinModel j : jl){ System.out.println(j.get_num()+"\t" +j.get_id()+"\t" +j.get_pw()+"\t" +j.get_email()+"\t" +j.get_phone()); } */ RequestDispatcher rd = request.getRequestDispatcher("joinList.jsp"); request.setAttribute("list", jl); rd.forward(request, response); // RequestDispatcher 통해 jl 객체 전달 } /* * @see POST 접근 = 검색 조회 접근 */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
joinList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import = "java.util.ArrayList, com.wjh.model.JoinModel"%> <% ArrayList<JoinModel> jl = (ArrayList<JoinModel>) request.getAttribute("list"); %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>LIST</title> </head> <body> <div align="center"> <h1>JOIN LIST</h1> <table border=1> <tr> <th>num</th> <th>id</th> <th>pw</th> <th>email</th> <th>phone</th> </tr> <% for(JoinModel j : jl) { %> <tr> <td><%=j.get_num() %></td> <td><%=j.get_id() %></td> <td><%=j.get_pw() %></td> <td><%=j.get_email() %></td> <td><%=j.get_phone() %></td> </tr> <% } %> </table> <p> <input type="button" value="HOME" onclick="location.href = 'index.html'" /> </div> </body> </html>
'Study > 2020 국비교육_Java' 카테고리의 다른 글
Tue/Feb/11 [Java-JSTL] day29. JSTL 기초 (0) 2020.02.11 Mon/Feb/10[Java-JSP] day28.JSP action tag_forward/include (0) 2020.02.10 Tue/Feb/04 [Java] day24. - JSP (0) 2020.02.04 Mon/Feb/03 [Java] day23. 페이지 간 데이터 이동 (0) 2020.02.03 Fri/Jan/31 [Java] day22. Servlet basic (0) 2020.01.31 -