1.DAO(Data Acceses Object) 패턴
    1) 비즈니스 로직과 데이터 엑세스 로직을 분리하는 것이 원칙
    2) 의미있는 비즈니스 로직을 가진 엔터프라이즈 애플리케이션이라면 데이터 액세스 계층을
       DAO패턴으로 분리해야 한다.
    3) 서비스계층에 영향을 주지 않고 데이터 엑세스 기술을 변경할수 있는 장점이 있다.

    2.커넥션 풀링을 지원하는 DataSource
    1) 미리 정해진 개수만클의 DB 커넥션을 풀(Pool)에 준비해두고,
       애플리케이션이 요청할 때마다 Pool에서 꺼내서 하나씩 할당해주고
       다시 돌려받아서 Pool에 넣는 식의 기법
    2) 다중 사용자를 갖는 엔터프라이즈 시스템에서라면 반드시 DB 커넥션 풀링
       기능을 지원하는 DataSource를 사용해야 한다.

    3. DataSource 종류
    1) 오픈소스 DataSource
    - Apache Commons DBCP
    : 가장 유명한 오픈소스 DB 커넥션 풀(Pool) 라이브러리

    DAO DTO

    Connection Pool로 연결할 DB속성

    백업 할경우

    server.xml 복사 해놓기


    DBCP 테스트

    context.xml 추가

    <?xml version="1.0" encoding="UTF-8"?>
    <!--
      Licensed to the Apache Software Foundation (ASF) under one or more
      contributor license agreements.  See the NOTICE file distributed with
      this work for additional information regarding copyright ownership.
      The ASF licenses this file to You under the Apache License, Version 2.0
      (the "License"); you may not use this file except in compliance with
      the License.  You may obtain a copy of the License at
    
          http://www.apache.org/licenses/LICENSE-2.0
    
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.
    --><!-- The contents of this file will be loaded for each web application --><Context>
    
        <!-- Default set of monitored resources. If one of these changes, the    -->
        <!-- web application will be reloaded.                                   -->
        <WatchedResource>WEB-INF/web.xml</WatchedResource>
        <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
    
        <!-- Uncomment this to disable session persistence across Tomcat restarts -->
        <!--
        <Manager pathname="" />
        -->
        <!-- 서버에서 DBCP를 사용하겠다라고 기재하는 코드 -->
        <Resource
    		name = "jdbc/dbconn"
    		auth = "Container"
    		driverClassName = "com.mysql.cj.jdbc.Driver"
    		url = "jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC"
    		username = "root"
    		password = "7496"
    		type = "javax.sql.DataSource"
    		maxActive = "50"
    		maxIdle = "10"
    		maxWait = "5000"
    	/>
        
    </Context>

     

    dbcpLab.jsp

    <%@page import="java.sql.Connection"%>
    <%@page import="javax.sql.DataSource"%>
    <%@page import="javax.naming.Context"%>
    <%@page import="javax.naming.InitialContext"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!-- 
    	1.DAO(Data Acceses Object) 패턴
    		1) 비즈니스 로직과 데이터 엑세스 로직을 분리하는 것이 원칙
    		2) 의미있는 비즈니스 로직을 가진 엔터프라이즈 애플리케이션이라면 데이터 액세스 계층을
    		   DAO패턴으로 분리해야 한다.
    		3) 서비스계층에 영향을 주지 않고 데이터 엑세스 기술을 변경할수 있는 장점이 있다.
    		
    	2.커넥션 풀링을 지원하는 DataSource
    		1) 미리 정해진 개수만클의 DB 커넥션을 풀(Pool)에 준비해두고,
    		   애플리케이션이 요청할 때마다 Pool에서 꺼내서 하나씩 할당해주고
    		   다시 돌려받아서 Pool에 넣는 식의 기법
    		2) 다중 사용자를 갖는 엔터프라이즈 시스템에서라면 반드시 DB 커넥션 풀링
    		   기능을 지원하는 DataSource를 사용해야 한다.
    	
    	3. DataSource 종류
    		1) 오픈소스 DataSource
    			- Apache Commons DBCP
    				: 가장 유명한 오픈소스 DB 커넥션 풀(Pool) 라이브러리
    					   
     -->
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>DBCP 테스트</title>
    </head>
    <body>
    	<%
    		/* Context인터페이스 : 서버에 있는 컨텍스트 패스를 얻기 위해서 생성 
    		   서버가 실행 되면 이미 DBCP는 만들어졌기 때문에 가져다 사용하면 된다.
    		   Context의 lookup()사용하기 위해서 */
    	   Context context = new InitialContext();
    	   DataSource dataSource = (DataSource)context.lookup("java:comp/env/" + "jdbc/dbconn");
    	   Connection connection = dataSource.getConnection();
    	   System.out.println("DBCP연동 완료");
    	   System.out.println("Connection 객체 : " + connection.toString());
    	   System.out.println("스레드 명 : " + Thread.currentThread().getName());
    	%>
    </body>
    </html>

    DB SQL

    drop table if exists memberDTO;
    create table memberDTO(
    	username varchar(15),
    	id 		 varchar(15),
    	pw       varchar(15),
    	phone1   varchar(15),
    	phone2   varchar(15),
    	phone3   varchar(15),
    	gender   varchar(10)
    );
    
    select * 
    from memberdto;
    
    insert into memberdto values('이방원', 'Lee', '0217', '010', '5678', '7890', '남자');
    
    insert into memberdto values('이도', 'Lee2', '0217', '010', '5678', '7890', '남자');
    insert into memberdto values('이제', 'Lee3', '0217', '010', '5678', '7890', '남자');
    insert into memberdto values('하륜', 'Ha', '0217', '010', '5678', '7890', '남자');
    insert into memberdto values('이숙번', 'Lee4', '0217', '010', '5678', '7890', '남자');

    MemberDTO.java

    package kr.gov.dto;
    
    /*
     * DTO (Data Transfer Object) : DB로부터 가져오는 데이터를 클래스 형식으로 가져오는 객체(빈).
     */
    public class MemberDTO {
    	
    	private String username;
    	private String id;
    	private String pw;
    	private String phone1;
    	private String phone2;
    	private String phone3;
    	private String gender;
    	
    	public MemberDTO() {
    	
    	}
    
    	public MemberDTO(String username, String id, String pw, String phone1, String phone2, String phone3,
    			String gender) {
    		super();
    		this.username = username;
    		this.id = id;
    		this.pw = pw;
    		this.phone1 = phone1;
    		this.phone2 = phone2;
    		this.phone3 = phone3;
    		this.gender = gender;
    	}
    
    	public String getUsername() {
    		return username;
    	}
    
    	public void setUsername(String username) {
    		this.username = username;
    	}
    
    	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 String getPhone1() {
    		return phone1;
    	}
    
    	public void setPhone1(String phone1) {
    		this.phone1 = phone1;
    	}
    
    	public String getPhone2() {
    		return phone2;
    	}
    
    	public void setPhone2(String phone2) {
    		this.phone2 = phone2;
    	}
    
    	public String getPhone3() {
    		return phone3;
    	}
    
    	public void setPhone3(String phone3) {
    		this.phone3 = phone3;
    	}
    
    	public String getGender() {
    		return gender;
    	}
    
    	public void setGender(String gender) {
    		this.gender = gender;
    	}
    	
    }
    

     

    MemberDAO.java

    package kr.gov.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;
    
    import kr.gov.dto.MemberDTO;
    
    public class MemberDAO {
    
    	private DataSource dataSource;
    	private Connection conn;
    	private PreparedStatement pstmt;
    	private ResultSet rs;
    	private Context context;
    	ArrayList<MemberDTO> dtos = new ArrayList<>();
    	
    	public MemberDAO() {
    		try {
    			context = new InitialContext();
    			dataSource = (DataSource)context.lookup("java:comp/env/" + "jdbc/dbconn");
    			conn = dataSource.getConnection();
    			
    			System.out.println("DBCP에 있는 커넥션 객체 얻어오기 성공");
    			System.out.println("스레드 명 : " + Thread.currentThread().getName());
    			
    		} catch (Exception e) {
    			
    			e.printStackTrace();
    		}
    	}
    	
    	//DBCP에서 Connection을 반환하는 메서드
    	/*public Connection getConnection() {
    		
    	
    	 * try { context = new InitialContext(); dataSource =
    	 * (DataSource)context.lookup("java:comp/env/" + "jdbc/dbconn"); conn =
    	 * dataSource.getConnection();
    	 * 
    	 * System.out.println("DBCP에 있는 커넥션 객체 얻어오기 성공"); System.out.println("스레드 명 : "
    	 * + Thread.currentThread().getName());
    	 * 
    	 * } catch (Exception e) {
    	 * 
    	 * e.printStackTrace(); }
    	 * 
    	 * return conn; }
    	 */
    	
    	//memberDTO테이블에 있는 데이터 리스트를 가져오는 메서드(select)
    	public ArrayList<MemberDTO> memberList() {
    		
    		try {
    			//Connection conn = this.getConnection();
    			String sql = "select * from memberDTO";
    			pstmt = conn.prepareStatement(sql);
    			rs = pstmt.executeQuery();
    			
    			while(rs.next()) {
    				String username = rs.getString("username");
    				String id = rs.getString("id");
    				String pw = rs.getString("pw");
    				String phone1 = rs.getString("phone1");
    				String phone2 = rs.getString("phone2");
    				String phone3 = rs.getString("phone3");
    				String gender = rs.getString("gender");
    				
    				MemberDTO dto = new MemberDTO(username, id, pw, phone1, phone2, phone3, gender);
    				dtos.add(dto);
    			}
    			
    			System.out.println("DB에 있는 데이터 가져오기 성공");
    			System.out.println("스레드 명 : " + Thread.currentThread().getName());
    			
    		} catch (Exception e) {
    			
    			e.printStackTrace();
    		}
    		
    		return dtos;
    	}
    	
    	//신규 회원정보를 DB에 insert하는 메서드
    	public void addMember(MemberDTO dto) {
    		
    		int n = 0;
    		try {
    			String sql = "insert into memberDTO values(?,?,?,?,?,?,?) ";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, dto.getUsername());
    			pstmt.setString(2, dto.getId());
    			pstmt.setString(3, dto.getPw());
    			pstmt.setString(4, dto.getPhone1());
    			pstmt.setString(5, dto.getPhone2());
    			pstmt.setString(6, dto.getPhone3());
    			pstmt.setString(7, dto.getGender());
    			n = pstmt.executeUpdate();
    			System.out.println("입력 갯수 : " + n);
    			
    		} catch (Exception e) {
    			
    			e.printStackTrace();
    		}
    		
    		System.out.println("addMember 오케이");
    	}
    	
    }

    select

     

    memberList.jsp

    <%@page import="kr.gov.dto.MemberDTO"%>
    <%@page import="java.util.ArrayList"%>
    <%@page import="kr.gov.dao.MemberDAO"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>멤버 List</title>
    </head>
    <body>
    	<table border="1">
    		<tr>
    			<th>사용자 이름</th>
    			<th>아이디</th>
    			<th>비밀번호</th>
    			<th>전화번호</th>
    			<th>성별</th>
    		</tr>
    	<% 
    		/* MemberDAO 객체를 생성하여 memberList()호출하는 부분 */
    		MemberDAO dao = new MemberDAO();
    		ArrayList<MemberDTO> dtos = dao.memberList();
    		
    		for(MemberDTO dto : dtos) {
    			String username = dto.getUsername();
    			String id = dto.getId();
    			String pw = dto.getPw();
    			String phone = dto.getPhone1() +"-"+ dto.getPhone2() +"-"+ dto.getPhone3();
    			String gender = dto.getGender();
    	%>
    		<tr>
    			<td><%=username %></td>
    			<td><%=id %></td>
    			<td><%=pw %></td>
    			<td><%=phone %></td>
    			<td><%=gender %></td>
    		</tr>
    	<%
    		}
    	%>
    	
    	</table>
    </body>
    </html>

    Console

    DB에 있는 데이터 가져오기 성공
    스레드 명 : http-nio-8080-exec-7


    insert

     

    joinMember.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>신규 회원 가입</title>
    </head>
    <body>
    	<h2>신규 회원 가입</h2>
    	<form action="joinOk.jsp" method="post">
    		<p><b>이름 : </b> <input type="text" name="username" placeholder="이름을 입력하세요." required="required" /></p>
    		<p><b>아이디 : </b> <input type="text" name="id" placeholder="아이디를 입력하세요." required="required" /></p>	
    		<p><b>비밀번호 : </b> <input type="password" name="pw" placeholder="비밀번호를 입력하세요." required="required" /></p>	
    		<p><b>전화번호 : </b> <input type="number" name="phone1" size="3" /> -  <input type="number" name="phone2" size="4" /> - <input type="number" name="phone3" size="4" /></p>	
    		<p><b>성별 : </b> <input type="radio" name="gender" value="남자" />남자
    					 	  <input type="radio" name="gender" value="남자" />여자</p><br/>
    		<input type="submit" value="가입" /> &nbsp;&nbsp;&nbsp;
    		<input type="reset" value="재입력" />	
    	</form>
    </body>
    </html>

     

    joinOk.jsp

    <%@page import="kr.gov.dao.MemberDAO"%>
    <%@page import="kr.gov.dto.MemberDTO"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    
    <%
    	request.setCharacterEncoding("UTF-8");
    	String username = request.getParameter("username");
    	String id = request.getParameter("id");
    	String pw = request.getParameter("pw");
    	String phone1 = request.getParameter("phone1");
    	String phone2 = request.getParameter("phone2");
    	String phone3 = request.getParameter("phone3");
    	String gender = request.getParameter("gender");
    	
    	MemberDTO dto = new MemberDTO();
    	MemberDAO dao = new MemberDAO();
    	
    	//클라이언트가 *입력한 회원가입정보를 DTO객체에 저장하는 코드
    	dto.setUsername(username);
    	dto.setId(id);
    	dto.setPw(pw);
    	dto.setPhone1(phone1);
    	dto.setPhone2(phone2);
    	dto.setPhone3(phone3);
    	dto.setGender(gender);
    	
    	dao.addMember(dto);
    	response.sendRedirect("memberList.jsp");
    %>

     

    • 네이버 블러그 공유하기
    • 네이버 밴드에 공유하기
    • 페이스북 공유하기
    • 카카오스토리 공유하기
    loading