gwooden_코린이

데이터베이스 커넥션 풀 (DBCP) 본문

JSP&Servlet

데이터베이스 커넥션 풀 (DBCP)

gwooden22 2023. 1. 30. 12:28
728x90

1. 데이터베이스 커넥션 풀 (DBCP)

커넥션 풀

 

Apache Tomcat 9 (9.0.71) - JNDI Datasource How-To

JNDI Datasource configuration is covered extensively in the JNDI-Resources-HOWTO. However, feedback from tomcat-user has shown that specifics for individual configurations can be rather tricky. Here then are some example configurations that have been poste

tomcat.apache.org

<Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:xe"
              username="study" password="1234" maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/>
  • maxTotal
  • maxIdle
  • maxWaitMillis 
<%@page import="javax.naming.InitialContext"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.Context"%>


<%

	Context initContext = new InitialContext();
	Context envContext  = (Context)initContext.lookup("java:/comp/env");
	DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
	Connection conn = ds.getConnection();
	

%>

2. 회원관리 시스템

 

- 데이터보 보관(전달)을 하는 객체

자바빈, VO(value object), DTO(data transfer obeject)

package com.study.vo;

public class MemberVO {
	
	private String name;
	private String id;
	private String pw;
	private String email;
	private String phone;
	private int admin;
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	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 getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public int getAdmin() {
		return admin;
	}
	public void setAdmin(int admin) {
		this.admin = admin;
	}
	
	

}

 

 

-DB접근을 위한 객체

DAO(data access object)

 

 

싱글톤 형식에 기본 형

package com.study.dao;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

//싱글톤
public class MemberDAO {
	
	//싱글콘은 생성자가 private
	//그래야 다른 class나 등등에서 객체생성을 못함
	private MemberDAO() {
		
	}
	
	//객체 생성 private 다른데에서 수정같은걸 못하게 방지
	//static 정적 객체로 생성(메모리에 공유가 됨)
	private static MemberDAO instance = new MemberDAO();
	
	//생성한 객체를 호출(리턴)하는 메서드
	//수정은 못함 get가능 (읽기전용)
	public static MemberDAO getInstance() {
		 return instance;
	 }
	
	//커넥션 풀 get하는 메서드
	public Connection getConnection() throws Exception {
		
		Context initContext = new InitialContext();
		Context envContext  = (Context)initContext.lookup("java:/comp/env");
		DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
		Connection conn = ds.getConnection();
		
		return conn;
	}
		

	
}

 

//싱글톤을 사용하지 않았을 때

MemberDAO dao = new MemberDAO();

 

//싱글톤을 사용했을 때

MemberDAO dao = MemberDAO.getInstance();


 

 

Index of /download/release/v13.14.0/

 

nodejs.org


package com.study.vo;


public class MemberVO {
	
	private String name;
	private String id;
	private String pw;
	private String email;
	private String phone;
	private int admin;
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	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 getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public int getAdmin() {
		return admin;
	}
	public void setAdmin(int admin) {
		this.admin = admin;
	}
	
	

}
package com.study.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.study.vo.MemberVO;

//싱글톤
public class MemberDAO {
	
	//싱글콘은 생성자가 private
	//그래야 다른 class나 등등에서 객체생성을 못함
	private MemberDAO() {
		
	}
	
	//객체 생성 private 다른데에서 수정같은걸 못하게 방지
	//static 정적 객체로 생성(메모리에 공유가 됨)
	private static MemberDAO instance = new MemberDAO();
	
	//생성한 객체를 호출(리턴)하는 메서드
	//수정은 못함 get가능 (읽기전용)
	public static MemberDAO getInstance() {
		 return instance;
	 }
	
	//커넥션 풀 get하는 메서드
	public Connection getConnection() throws Exception {
		
		Context initContext = new InitialContext();
		Context envContext  = (Context)initContext.lookup("java:/comp/env");
		DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
		Connection conn = ds.getConnection();
		
		return conn;
	}
		
	//아이디 비번 체크하는 메서드
	public int userCheck(String id, String pw) {
		
		int result = -1; //결과 저장 변수
		
		String sql = "select pw from member where userid=?";
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			conn = getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				if(rs.getString("pw") != null && rs.getString("pw").equals(pw)) {
					result = 1; //아이디 비번 모두 일치
				} else {
					result = 0; //아이디는 일치, 비번을 일치하지 않음
				}
			} else {
				result = -1; //입력한 아이디가 없음
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null)
					rs.close();
				if(pstmt != null)
					pstmt.close();
				if(conn != null)
					conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return result;
	}
	
	//로그인 성공한 사람의 정보를 빼오는 검색문
	public MemberVO getMember(String id) {
		MemberVO vo = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		String sql = "select * from member where userid = ?";
		
		try {
			conn = getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				vo = new MemberVO();
				
				vo.setName(rs.getString("name"));
				vo.setId(rs.getString("userid"));
				vo.setPw(rs.getString("pw"));
				vo.setEmail(rs.getString("email"));
				vo.setPhone(rs.getString("phone"));
				vo.setAdmin(rs.getInt("admin"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null)
					rs.close();
				if(pstmt != null)
					pstmt.close();
				if(conn != null)
					conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return vo;
	}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>환영쓰</h1>
	<a href="login.do">로그인페이지로 이동</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>로그인 페이지</h1>
	<form method="post" action="login.do" name="frm">
		아이디 : <input type="text" name="id" > <br>
		비밀번호 : <input type="text" name="pw" > <br><br>
		<input type="submit" value="로그인" onclick="return loginCheck()"> 
		<input type="button" value="회원가입">
	</form>
	<h3 style="color:red" >${msg}</h3>
	
	<script src="script/member.js"></script>
</body>
</html>
//아이디 유효성 검사
function loginCheck() {
	if(document.frm.id.value.length == 0) {
		alert("아이디 입력하세요.")
		frm.id.focus();
		
		return false; //submit 막는
	}


//비밀번호 유효성 검사
	if(document.frm.pw.value == "") {
		alert("비밀번호 입력하세요.")
		frm.pw.focus();
		
		return false; //submit 막는
	}
	
	//둘다 만족했을 경우 sumbit 사용가능
	return true;
}
package com.study.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
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 javax.servlet.http.HttpSession;

import com.study.dao.MemberDAO;
import com.study.vo.MemberVO;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;
       

    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher("member/login.jsp");
		dispatcher.forward(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String url = "member/login.jsp"; //로그인 실패시 이동할 페이지
		
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");
		
		MemberDAO dao = MemberDAO.getInstance();
		
		// 여기는 dao에서 로그인 인증처리하는 메서드를 호출
		//1 : 로그인 성공 | 0 : 비번 틀림 | -1 : 아이디 틀림
		int result = dao.userCheck(id, pw);
		
		if(result == 1) {
			//로그인 성공 세션에 회원정보 등록
			MemberVO vo = dao.getMember(id);
			
			HttpSession session = request.getSession();
			
			session.setAttribute("loginUser", vo);
			
			url =  "main.jsp"; //로그인 성공시 이동할 페이지
			
			
		} else if(result == 0) {
			request.setAttribute("msg", "비밀번호가 틀렸습니다.");
		} else {
			request.setAttribute("msg", "아이디가 틀렸습니다.");
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
		
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1>회원 페이지</h1>
	<h3>${loginUser.name}(${loginUser.id})님 환영합니다.</h3>
	



</body>
</html>

index.jsp -> 로그인 서블릿.java -> 로그인 페이지.jsp -> 로그인 서블릿.java -> 메인 페이지.jsp

 멤버.js(유효성 검사)

728x90
Comments