반응형

package user;

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

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

public class UserDAO {

		DataSource dataSource;
		
		public UserDAO() {
			try {
				
				InitialContext initContext = new InitialContext();
				// 실질적으로 소스에 접속할 수 있도록 함
				Context envContext = (Context) initContext.lookup("java:/comp/env");
				// 데이터 소스 초기화 
				dataSource = (DataSource) envContext.lookup("jdbc/UserChat");
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		//userID와 userPassword를 받아서
		public int login(String userID, String userPassword) {
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			String SQL = "SELECT * FROM USER WHERE userID = ?";
			try {
				conn = dataSource.getConnection();
				pstmt = conn.prepareStatement(SQL);
				pstmt.setString(1,  userID);
				rs = pstmt.executeQuery();
				if(rs.next()){
					//앞 쪽 userPassword는 db에서 가져온 패스워드
					if(rs.getString("userPassword").equals(userPassword)) {
						return 1; // 로그인에 성공
					}
					return 2; //비밀번호가 틀림
				}else {
					return 0; // 해당 사용자가 존재하지 않음.
				}
					
				
			}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 -1; // 데이터베이스 오류
		}
		
		//userID를 받아와서
		public int registerCheck(String userID) {
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			String SQL = "SELECT * FROM USER WHERE userID = ?";
			try {
				conn = dataSource.getConnection();
				pstmt = conn.prepareStatement(SQL);
				pstmt.setString(1,  userID);
				rs = pstmt.executeQuery();
				if(rs.next() || userID.equals("")){
					return 0; //이미 존재하는 회원
					
				}else {
					return 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 -1; // 데이터베이스 오류
		}
		
		// 회원가입하는 함수
		public int register(String userID, String userPassword, String userName, String userAge, String userGender, String userEmail, String userProfile) {
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			String SQL = "INSERT INTO USER VALUES(?,?,?,?,?,?,?)";
			try {
				conn = dataSource.getConnection();
				pstmt = conn.prepareStatement(SQL);
				pstmt.setString(1,  userID);
				pstmt.setString(2, userPassword);
				pstmt.setString(3, userName);
				pstmt.setInt(4, Integer.parseInt(userAge));
				pstmt.setString(5, userGender);
				pstmt.setString(6, userEmail);
				pstmt.setString(7,  userProfile);
				
				
				rs = pstmt.executeQuery();
				if(rs.next() || userID.equals("")){
					return 0; //이미 존재하는 회원
					
				}else {
					return 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 -1; // 데이터베이스 오류
		}
		
}

UserDAO

 

package user;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/UserRegisterCheck")
public class UserRegisterCheckServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		String userID = request.getParameter("userID");
		//문자열 형태를 출력할 수 있도록 공백을 추가해줌.
		response.getWriter().write(new UserDAO().registerCheck(userID) + "");
	}

}

UserRegisterCheckServlet

 

package user;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/userRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		String userID = request.getParameter("userID");
		String userPassword1 = request.getParameter("userPassword1");
		String userPassword2 = request.getParameter("userPassword2");
		String userName = request.getParameter("userName");
		String userAge = request.getParameter("userAge");
		String userGender = request.getParameter("userGender");
		String userEmail = request.getParameter("userEmail");
		String userProfile = request.getParameter("userProfile");
		
		if(userID == null || userID.equals("") || userPassword1 == null || userPassword1.equals("") || 
				userPassword2 == null || userPassword2.equals("") || userName == null || userName.equals("") || userAge == null ||
				userAge.equals("") || userGender == null || userGender.equals("") ||
				userEmail == null || userEmail.equals("")) {
			request.getSession().setAttribute("messageType", "오류 메시지");
			request.getSession().setAttribute("messageContent", "모든 내용을 입력해 주세요");
			response.sendRedirect("join.jsp");
			return;
		}
		if(!userPassword1.equals(userPassword2)) {
			request.getSession().setAttribute("messageType", "오류 메시지");
			request.getSession().setAttribute("messageContent", "암호가 일치하지 않습니다.");
			response.sendRedirect("join.jsp");
			return;
		}
		//여기까지 왔으면 userPassword에 1을 넣든 2를 넣든 상관 없음.
		int result = new UserDAO().register(userID, userPassword1, userName, userAge, userGender, userEmail, userProfile);
		if(result == 1) {
			request.getSession().setAttribute("messageType", "성공 메시지");
			request.getSession().setAttribute("messageContent", "회원 가입을 성공하였습니다.");
			response.sendRedirect("index.jsp");
			return;
		} else {
			request.getSession().setAttribute("messageType", "오류 메시지");
			request.getSession().setAttribute("messageContent", "이미 존재하는 회원 입니다.");
			response.sendRedirect("join.jsp");
			
		}
	}
}

UserRegisterServlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>UserChat</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  	<servlet-name>UserRegisterServlet</servlet-name>
  	<servlet-class>user.UserRegisterServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>UserRegisterServlet</servlet-name>
  	<url-pattern>/userRegister</url-pattern>
  </servlet-mapping>
</web-app>

web.xml

 

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

join.jsp 화면

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="text/html; charset=utf-8">

<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/custom.css?after">

<title>JSP Ajax fxProbest</title>

<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<!-- 자바스크립트 시작 -->
<script type="text/javascript">
	function registerCheckFunction() {
		var userID = $('#userID').val();
		// ajax 비동기 통신
		$.ajax({
			type : 'POST',
			//아래의 url로 보내줌
			url : './UserRegisterCheckServlet',
			data : {
				userID : userID
			},
			//성공했다면 result 값을 반환받음
			success : function(result) {
				if (result == 1) {
					$('#checkMessage').html('사용할 수 있는 아이디 입니다.');
					$('#checkType')
							.attr('class', 'modal-content panel-success');
				} else {
					$('#checkMessage').html('사용할 수 없는 아이디 입니다.');
					$('#checkType')
							.attr('class', 'modal-content panel-warning');
				}
				$('#checkModal').modal("show");
			}
		});

	}
	// javascript 비밀번호 체크 기능
	function passwordCheckFunction() {
		var userPassword1 = document.getElementById("userPassword1").value;
		var userPassword2 = document.getElementById("userPassword2").value;
		if (userPassword1 != userPassword2) {
			document.getElementById("passwordCheckMessage").innerHTML = "비밀번호가 틀립니다. 확인해주세요.";
		} else {
			document.getElementById("passwordCheckMessage").innerHTML = "비밀번호가 같습니다.";
		}
	}
</script>

</head>
<body>

	<%
		//userID를 초기화 해주고 session에서 userID값을 가져옵니다. 만약에 null이 아니라면 userID에 가져온 userID값을 넣어줍니다.
	String userID = null;
	if (session.getAttribute("userID") != null) {
		userID = (String) session.getAttribute("userID");
	}
	%>
	<!-- 부트스트랩을 이용하여 메뉴를 만들어 주도록 하겠씁니다. -->
	<nav class="navbar navbar-default">
		<div class="navbar-header">
			<button type="button" class="navbar-toggle collapsed"
				data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
				aria-expanded="false">
				<span class="icon-bar"></span> <span class="icon-bar"></span> <span
					class="icon-bar"></span>
			</button>
			<a class="navbar-brand" href="index.jsp">ProbestSoft members chat</a>
		</div>
		<div class="collapse navbar-collapse"
			id="bs-example-navbar-collapse-1">
			<ul class="nav navbar-nav">
				<li class="active"><a href="index.jsp">메인</a>
			</ul>
			<%
				// userID가 null 이면 로그인이 되지 않은 경우
			if (userID == null) {
			%>
			<ul class="nav navbar-nav navbar-right">
				<li class="dropdown"><a href="#" class="dropdown-toggle"
					data-toggle="dropdown" role="buton" aria-haspopup="true"
					aria-expand="false">접속하기<span class="caret"></span></a>
					<ul class="dropdown-menu">
						<li><a href="login.jsp">로그인</a>
						<li><a href="join.jsp">회원가입</a>
					</ul></li>
			</ul>
			<%
				// userID가 null이 아닐 경우 로그인이 되었다는 것.
			} else {
			%>
			<ul class="nav navbar-nav navbar-right">
				<li class="dropdown"><a href="#" class="dropdown-toggle"
					data-toggle="dropdown" role="button" aria-haspopup="true"
					aria-expand="false">회원관리<span class="caret"></span></a></li>
			</ul>
			<%
				}
			%>

		</div>
	</nav>


	<div class="container">
		<form method="post" action="./userRegister">
			<table class="table table-bordered table-hover"
				style="text-align: center; border: 1px solid #dddddd">
				<thead>
					<tr>
						<th colspan="3"><h4>회원 등록 양식</h4></th>
					</tr>
				</thead>
				<tbody>

					<tr>
						<td style="width: 110px;"><h5>아이디</h5></td>
						<td><input class="form-control" type="text" id="userID" name="userID"
							maxlength="20" placeholder="아이디를 입력해주세요">
						<td style="width: 110px;"><button class="btn btn-primary"
								onclick="registerCheckFunction();" type="button">중복체크</button> 
					</td>
					</tr>
					<tr>
						<td style="width: 110px;"><h5>비밀번호</h5></td>
						<td colspan="2"><input onkeyup="passwordCheckFunction();"
							class="form-control" id="userPassword1" type="password"
							name="userPassword1" maxlength="20" placeholder="비밀번호를 입력하세요.">
					</tr>
					<tr>
						<td style="width: 110px;"><h5>비밀번호 확인</h5></td>
						<td colspan="2"><input onkeyup="passwordCheckFunction();"
							class="form-control" id="userPassword2" type="password"
							name="userPassword2" maxlength="20" placeholder="비밀번호 확인을 해주세요.">
					</tr>
					<tr>
						<td style="width: 110px;"><h5>이름</h5></td>
						<td colspan="2"><input class="form-control" id="userName"
							type="text" name="userName" maxlength="20"
							placeholder="이름을 입력해 주세요.">
					</tr>
					<tr>
						<td style="width: 110px;"><h5>나이</h5></td>
						<td colspan="2"><input class="form-control" id="userAge"
							type="number" name="userAge" maxlength="20"
							placeholder="나이을 입력해 주세요.">
					</tr>
					<tr>
						<td style="width: 110px;"><h5>성별</h5></td>
						<td colspan="2">
							<div class="form-group"
								style="text-align: center; margin: 0 auto;">
								<div class="btn-group" data-toggle="buttons">
									<label class="btn btn-primary active"> <input
										type="radio" name="userGender" autocomplete="off" value="남자"
										checked>남자

									</label> <label class="btn btn-primary"> <input type="radio"
										name="userGender" autocomplete="off" value="여자">여자
									</label>
								</div>
							</div>
						</td>
					</tr>
					<tr>
						<td style="width: 110px;"><h5>이메일</h5></td>
						<td colspan="2"><input class="form-control" id="userEmail"
							type="email" name="userEmail" maxlength="20"
							placeholder="나이을 입력해 주세요.">
					</tr>
					<tr>
						<!-- 비밀번호를 실시간으로 확인하여 같은지 확인. -->
						<td style="text-align: left;" colspan="3">
							<h5 style="color: red;" id="passwordCheckMessage"></h5> <input
							class="btn btn-primary pull-right" type="submit" value="등록">
					</tr>
				</tbody>
			</table>
		</form>
	</div>
	<%
		//서버로부터 내용을 받아왔는지 확인.
	String messageContent = null;
	if (session.getAttribute("messageContent") != null) {
		messageContent = (String) session.getAttribute("messageContent");
	}
	String messageType = null;
	if (session.getAttribute("messageType") != null) {
		messageType = (String) session.getAttribute("messageType");
	}
	if (messageContent != null) {
	%>
	<!-- 모달창 -->
	<div class="modal fade" id="messageModal" tabindex="-1" role="dialog"
		aria-hidden="true">
		<div class="vertical-alignment-helper">
			<div class="modal-dialog vertical-align-center">
				<div
					class="modal-content <%if (messageType.equals("오류 메시지"))
	out.println("panel-warning");
else
	out.println("panel-success");%>">
					<div class="modal-header panel-heading">
						<button type="button" class="close" data-dismiss="modal">
							<span aria-hidden="true">&times</span>
							<!-- bootstrap sr-only: 화면상에 출력하지 않음 -->
							<span class="sr-only">Close</span>
						</button>
						<h4 class="modal-title">
							<%=messageType%>
						</h4>
					</div>
					<div class="modal-body">
						<%=messageContent%>
					</div>
					<div class="modal-footer">
						<!-- data-dissmiss="modal" 자바스크립트에의해 닫기 역할을 하는 속성 -->
						<button type="button" class="btn btn-primary"
							data-dissmiss="modal">확인</button>
					</div>
				</div>
			</div>
		</div>
	</div>
	<script>
		$('#messageModal').modal("show");
	</script>
	<%
		session.removeAttribute("messageContent");
	session.removeAttribute("messageType");
	}
	%>
	<!-- 하나의 모달을 더 추가 해줌. 정보를 띄워주는 모달 창 아이디 중복체크 -->
	<div class="modal fade" id="checkModal" tabindex="-1" role="dialog"
		aria-hidden="true">
		<div class="vertical-alignment-helper">
			<div class="modal-dialog vertical-align-center">
				<div id="checkType" class="modal-content panel-info">
					<div class="modal-header panel-heading">
						<button type="button" class="close" data-dismiss="modal">
							<span aria-hidden="true">&times</span>
							<!-- bootstrap sr-only: 화면상에 출력하지 않음 -->
							<span class="sr-only">Close</span>
						</button>
						<h4 class="modal-title">확인 메시지</h4>
					</div>
					<div id="checkMessage" class="modal-body"></div>
					<div class="modal-footer">
						<!-- data-dissmiss="modal" 자바스크립트에의해 닫기 역할을 하는 속성 -->
						<button type="button" class="btn btn-primary"
							data-dissmiss="modal">확인</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
</html>

 

UserDAO

package user;

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

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

public class UserDAO {

		DataSource dataSource;
		
		public UserDAO() {
			try {
				//이건 뭐야?
				InitialContext initContext = new InitialContext();
				// 실질적으로 소스에 접속할 수 있도록 함
				Context envContext = (Context) initContext.lookup("java:/comp/env");
				// 데이터 소스 초기화 
				dataSource = (DataSource) envContext.lookup("jdbc/UserChat");
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		//userID와 userPassword를 받아서
		public int login(String userID, String userPassword) {
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			String SQL = "SELECT * FROM USER WHERE userID = ?";
			try {
				conn = dataSource.getConnection();
				pstmt = conn.prepareStatement(SQL);
				pstmt.setString(1,  userID);
				rs = pstmt.executeQuery();
				if(rs.next()){
					//앞 쪽 userPassword는 db에서 가져온 패스워드
					if(rs.getString("userPassword").equals(userPassword)) {
						return 1; // 로그인에 성공
					}
					return 2; //비밀번호가 틀림
				}else {
					return 0; // 해당 사용자가 존재하지 않음.
				}
					
				
			}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 -1; // 데이터베이스 오류
		}
		
		//userID를 받아와서
		public int registerCheck(String userID) {
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			String SQL = "SELECT * FROM USER WHERE userID = ?";
			try {
				conn = dataSource.getConnection();
				pstmt = conn.prepareStatement(SQL);
				pstmt.setString(1,  userID);
				rs = pstmt.executeQuery();
				if(rs.next() || userID.equals("") ) {
				
					return 0; //이미 존재하는 회원
					
				}else {
					return 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 -1; // 데이터베이스 오류
		}
		
		// 회원가입하는 함수
		public int register(String userID, String userPassword, String userName, String userAge, String userGender, String userEmail, String userProfile) {
			Connection conn = null;
			PreparedStatement pstmt = null;
			
			String SQL = "INSERT INTO USER VALUES(?,?,?,?,?,?,?)";
			try {
				conn = dataSource.getConnection();
				pstmt = conn.prepareStatement(SQL);
				pstmt.setString(1,  userID);
				pstmt.setString(2, userPassword);
				pstmt.setString(3, userName);
				pstmt.setInt(4, Integer.parseInt(userAge));
				pstmt.setString(5, userGender);
				pstmt.setString(6, userEmail);
				pstmt.setString(7,  userProfile);
				
				return pstmt.executeUpdate();
			
					
				
			}catch(Exception e){
				e.printStackTrace();
			}finally {
				try {
					
					if(pstmt != null) pstmt.close();
					if(conn != null) conn.close();
				}catch(Exception e) {
					e.printStackTrace();
				}
			}
			return -1; // 데이터베이스 오류
		}
		
}

 

custom.css

@import url(http://fonts.googleapis.com/earlyaccess/nanumgothic.css); 
@import url(http://fonts.googleapis.com/earlyaccess/hanna.css);
@import url(http://fonts.googleapis.com/earlyaccess/notosanskr.css);

* {
	font-family: 'Nanum Gothic';	
}
h5 { 
	font-family: 'Noto Sans KR';
	font-size: 15px;
}
h4{
	font-family: 'Noto Sans KR';
}

h3{
	font-family: 'Hanna';
}
h2{
	font-family: 'Hanna';
}
h1{
	font-family: 'Hanna';
}

/* 테이블 관련 디자인 처리 */
thead th{
	background-color: #006DCC;
	color: white;
	text-align: center;
}
tr th:first-child,
tr th:first-child{
	border-top-left-radius: 6px;
	border-bottom-left-radius: 6px;
}
tr th:first-child,
tr th:first-child{
	border-top-right-radius: 6px;
	border-bottom-right-radius: 6px;
}


/* 모달 팝업창 관련 디자인*/
.vertical-alignment-helper{
	display: table;
	height: 100%;
	width: 100%;
	pointer-events: none;
}

.vertical-align-center{
	display: table-cell;
	vertical-align: middle;
	pointer-events: none;
}

.modal-content{
	width: inherit;
	height: inherit;
	margin: 0 auto;
	pointer-events: all;
}
반응형
블로그 이미지

꽃꽂이하는개발자

,

ConnectionPool이란?

2020/IT Q_A 2020. 5. 20. 11:01
반응형

  온라인 쇼핑몰의 경우 동시에 수십 명, 많게는 수백 명까지 접속해서 상품 조회, 주문하기 등의 기능을 사용하는데 앞의 방법처럼 데이터베이스와 연동해 작업해야 한다면 너무 비효율적입니다. 이 문제를 해결하기 위해 현재는 웹어플리케이션이 실행됨과 동시에 연동할 데이터베이스와의 ㅇ녀결을 미리 설정해 둡니다. 그리고 필요할 때마다 미리 연결해 놓은 상태를 이용해 빠르게 데이터베이스와 연동하여 작업을 합니다. 이렇게 미리 데이터베이스와 연결시킨 상태를 유지하는 기술을 커넥션 풀(ConnectionPool)이라고 부릅니다.

 

기존 데이터베이스 연동 방법의 문제점

  • 애플리케이션에서 데이터베이스에 연결하는 과정에서 시간이 많이 걸립니다.

ConnectionPool

  • 애플리케이션 실행 시 미리 ConnectionPool 객체를 생성한 후 데이터베이스와 연결을 맺습니다.
  • 애플리케이션은 데이터베이스 연동 작업 발생 시 이 ConnectionPool 객체를 이용해서 작업합니다.

 

커넥션 풀 동작 과정

  • 톰캣 컨테이너를 실행한 후 응용 프로그램을 실행합니다.
  • 톰캣 컨테이너 실행 시 ConnectionPool 객체를 생성합니다.
  • 생성된 커넥션 객체는 DBMS와 연결합니다.
  • 데이터베이스와의 연동 작업이 필요할 경우 응용 프로그램은 ConnectionPool에서 제공하는 메서드를 호출하여 연동합니다.

  톰캣 컨테이너는 자체적으로 ConnectionPool 기능을 제공합니다. 톰캣 실행 시 톰캣은 설정파일에 설정된 데이터베이스 정보를 이용해 미리 데이터베이스와 연결하여 ConnectionPool 객체를 생성한 후 애플리케이션이 데이터베이스와 연동할 일이 생기면 ConnectionPool 객체의 메서드를 호출해 빠르게 연동하여 작업합니다.

 

 

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형
Stacktrace:]을(를) 발생시켰습니다.
com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '���ѹα� ǥ�ؽ�' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
	at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132)
	at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2120)
	at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2143)
	at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1310)
	at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:967)
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826)
	at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
	at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
	at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
	at org.apache.tomcat.dbcp.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:55)
	at org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:355)
	at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:115)
	at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:665)
	at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:544)
	at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:753)
	at org.apache.jsp.connection_jsp._jspService(connection_jsp.java:137)
	at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:71)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
	at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
	at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
	at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:748)

 

MySQL 5.1.23 이상의 버전을 사용하면 MySQL 타임존의 시곤표현 포맷이 달라져서 Connector에서 인식을 하지 못합니다.

해결법은 MySQL 버전을 5.1.23으로 낮추거나 URL주소에 serverTimezone을 추가해 주어야 합니다.

 

<!-- path는 우리 프로젝트의 이름 / docbase는 www를 넣어 줌으로써 WebContent라는걸 알림 -->
<Context path="/UserChat" docBase="www">
<Resource
	name="jdbc/UserChat"
	auth="Container"
	type="javax.sql.DataSource"
	driverClassName="com.mysql.jdbc.Driver"
	loginTimeout="10"
	validationQuery="SELECT 1 FROM DUAL"
	maxWait="5000"
	username="id"
	password="pasword"
	testOnBorrow="true"
	url="jdbc:mysql://localhost:3308/UserChat" />
<ResourceLink type="javax.sql.data.DataSource"
	name="jdbc/UserChat"
	global="jdbc/UserChat" />
</Context>
<!-- path는 우리 프로젝트의 이름 / docbase는 www를 넣어 줌으로써 WebContent라는걸 알림 -->
<Context path="/UserChat" docBase="www">
<Resource
	name="jdbc/UserChat"
	auth="Container"
	type="javax.sql.DataSource"
	driverClassName="com.mysql.jdbc.Driver"
	loginTimeout="10"
	validationQuery="SELECT 1 FROM DUAL"
	maxWait="5000"
	username="root"
	password="111111"
	testOnBorrow="true"
	url="jdbc:mysql://localhost:3308/UserChat?serverTimezone=UTC" />
<ResourceLink type="javax.sql.data.DataSource"
	name="jdbc/UserChat"
	global="jdbc/UserChat" />
</Context>

url="jdbc:mysql://localhost:3308/UserChat?serverTimezone=UTC" 이 부분을 수정해주니 잘 작동이 되었습니다.

 

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

MySql install 버전을 다운로드 하시고 설치 하시면

Command Line Client 를 실행해 줍니다.

패스워드는 초기에 지정해주셨던 ROOT 계정의 비밀번호를 입력해 주시면 됩니다.

 

이렇게 DB를 만들어 주셨으면 위에 만들었던 DATABASE에 접속할 수 있도록 하나의 자바 빈즈를 만들어 주도록 하겠습니다.

user package에 UserDTO 클래스를 만들어 줍니다.

package user;

public class UserDTO {
	String userID;
	String userPassword;
	String userName;
	int userAge;
	String userGender;
	String userEmail;
	String userProfile;
	public String getUserID() {
		return userID;
	}
	public void setUserID(String userID) {
		this.userID = userID;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public int getUserAge() {
		return userAge;
	}
	public void setUserAge(int userAge) {
		this.userAge = userAge;
	}
	public String getUserGender() {
		return userGender;
	}
	public void setUserGender(String userGender) {
		this.userGender = userGender;
	}
	public String getUserEmail() {
		return userEmail;
	}
	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}
	public String getUserProfile() {
		return userProfile;
	}
	public void setUserProfile(String userProfile) {
		this.userProfile = userProfile;
	}
	
	
	
	
}

 

이제 MySQL Database와 JSP를 연동하기 위해서는 jdbc가 필요합니다.

GOOGLE에서 검색해서 다운 받으셔도 되지만 편의상 파일로 올리겠습니다.

mysql-connector-java-8.0.20.zip
4.48MB

우리는 MySQL Connector java.jar파일만 필요하기에 압축을 푸시고 앞의 파일을 복사해서 Eclipse내에

WEB-INF\lib 폴더안에 복사 붙여 넣기 해줍니다.

넣어준 파일에 오른쪽 마우스 우클릭을 하여 build path - add를 클릭하여 줍니다.

 

  그리고 WebContent안에 META-INF라는 폴더가 있습니다. 거기 안쪽에 하나의 context파일을 만들어 주도록 하겠습니다.

xml파일을 만들어 주시고 이름은 context.xml 으로 만들겠습니다.

<Resource
name: DataSource에 대한 JNDI이름
auth : 인증 주체
type: 데이터베이스 종류별 DataSource
driverClassName : 연결할 데이터베이스 종류에 따른 드라이버 클래스 이름
factory : 연결할 데이터베이스 종류에 따른 ConnectionPool 생성 클래스 이름
maxActive : 동시에 최대로 데이터베이스 연결할 수 있는 Connection 수
maxIdle : 동시에 idle 상태로 대기할 수 있는 최대 수
maxWait : 새로운 연결이 생길 때까지 기다릴 수 있는 최대 시간
user : 데이터베이스 접속 ID
password : 데이터베이스 접속 비밀번호
type : 데이터베이스 종류별 DataSource
url : 접속할 데이터 베이스 주소와 포트 번호 및 SID />
<!-- path는 우리 프로젝트의 이름 / docbase는 www를 넣어 줌으로써 WebContent라는걸 알림 -->
<Context path="/UserChat" docBase="www">
<Resource
	name="jdbc/UserChat"
	auth="Container"
	type="javax.sql.DataSource"
	driverClassName="com.mysql.jdbc.Driver"
	loginTimeout="10"
	validationQuery="SELECT 1 FROM DUAL"
	maxWait="5000"
	username="root"
	password="111111"
	testOnBorrow="true"
	url="jdbc:mysql://localhost:3308/UserChat?serverTimezone=UTC" />
<ResourceLink type="javax.sql.data.DataSource"
	name="jdbc/UserChat"
	global="jdbc/UserChat" />
</Context>

저는 port 번호를 3308로 설정을 하여서 url에 3308로 하였지만 수정 안하신 분들은 3306일거에요!

이렇게 설정이 완료되면 성공적으로 커넥션 풀을 이용할 수 있습니다.

 

이제 커넥션 풀을 이용할 수 있는지 테스트를 한번 해보겠습니다.

WebContent에 테스트 할 connection.jsp 파일을 만들어 주겠습니다.

<!DOCTYPE html>
<html>
<head>
<%@ page import="java.sql.*, javax.sql.*, java.io.*,javax.naming.InitialContext, javax.naming.Context" %>
</head>
<body>
	<%
		InitialContext initCtx = new InitialContext();
		Context envContext = (Context)initCtx.lookup("java:/comp/env");
		DataSource ds = (DataSource) envContext.lookup("jdbc/UserChat");
		Connection conn = ds.getConnection();
		Statement stmt = conn.createStatement();
		ResultSet rs = stmt.executeQuery("SELECT VERSION();");
		while(rs.next()){
			out.println("MySQL Version : " + rs.getString("version()"));
		}
		rs.close();
		stmt.close();
		conn.close();
		initCtx.close();
	%>
</body>
</html>

실행을 하게 되면 

저의 MySQL 버전이 나옵니다. 연결이 잘 됬나 봅니다^^

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

1. bootstrap 3.7.7 을 사용하겠습니다.

https://getbootstrap.com/docs/3.3/getting-started/

 

Getting started · Bootstrap

Bootstrap is downloadable in two forms, within which you'll find the following directories and files, logically grouping common resources and providing both compiled and minified variations. jQuery required Please note that all JavaScript plugins require j

getbootstrap.com

 

 

2. dynamic web project를 만들어 주겠습니다.

WebContent아래에 다운받은 Bootstrap 3종을 넣어줍니다. 그리고 우리가 따로 꾸밀 custom.css 파일을 하나 만들어 줍니다.

  메인 페이지를 구성할 index.jsp도 만들어 주겠습니다.

 

3. index.jsp에 메인 화면의 header부분을 만들어 주겠습니다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="text/html; charset=utf-8">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/custom.css">
<title>JSP Ajax fxProbest</title>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
	
	<% //userID를 초기화 해주고 session에서 userID값을 가져옵니다. 만약에 null이 아니라면 userID에 가져온 userID값을 넣어줍니다.
		String userID = null;
	if(session.getAttribute("userID") != null){
		userID = (String) session.getAttribute("userID");
	}
	%>
	<!-- 부트스트랩을 이용하여 메뉴를 만들어 주도록 하겠씁니다. -->
	<nav class="navbar navbar-default">
		<div class="navbar-header">
			<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" 
			data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
			</button>
			<a class="navbar-brand" href="index.jsp">ProbestSoft members chat</a>
		</div>
		<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
			<ul class="nav navbar-nav">
				<li class="active"><a href="index.jsp">메인</a>
			</ul>
			<% // userID가 null 이면 로그인이 되지 않은 경우
				if(userID == null){
			%>
			<ul class="nav navbar-nav navbar-right">
				<li class="dropdown">
					<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="buton" aria-haspopup="true"
					aria-expand="false">접속하기<span class="caret"></span></a>
					<ul class="dropdown-menu">
						<li><a href="login.jsp">로그인</a>
						<li><a href="join.jsp">회원가입</a>
					</ul>
				</li>
			</ul>
			<%
				// userID가 null이 아닐 경우 로그인이 되었다는 것.
				} else {
			%>
			<ul class="nav navbar-nav navbar-right">
				<li class="dropdown">
					<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
					aria-expand="false">회원관리<span class="caret"></span></a>
				</li>
			</ul>
			<%
				}
			%>
			
		</div>
	</nav>
</body>
</html>

 

출처: 안경잡이 개발자 나 동 빈 

반응형
블로그 이미지

꽃꽂이하는개발자

,

서블릿 매핑

2020/JSP SERVLET 2020. 5. 17. 19:19
반응형

web.xml servlet 매핑 설정.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>pro5</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>aaa</servlet-name>
  	<servlet-class>sec01.ex01.FirstServlet</servlet-class>
  </servlet>
  <servlet>
  	<servlet-name>bbb</servlet-name>
  	<servlet-class>sec01.ex01.SecondServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>aaa</servlet-name>
  	<url-pattern>/first</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
  	<servlet-name>bbb</servlet-name>
  	<url-pattern>/second</url-pattern>
 </servlet-mapping>
 
</web-app>

 

 

 

FirstServlet 

package sec01.ex01;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet{
	@Override
	public void init() throws ServletException{
		System.out.println("init 메서드 호출");
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		System.out.println("doGet메서드 호출");
	}
	
	@Override
	public void destroy() {
		System.out.println("destory 메서드 호출");
	}
	
}

SecondServlet

package sec01.ex01;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SecondServlet extends HttpServlet{
	@Override
	public void init() throws ServletException{
		System.out.println("Init 메서드 호출");
		}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse rep) throws ServletException, IOException{
		System.out.println("doGet 메서드 호출");
	}
	
	@Override
	public void destroy() {
		System.out.println("destory 메서드 호출");
	}
}

 

탐캣을 실행하시고 웹브라우저에 http://localhost:8080/pro5/first or second를 하시면 Init 이 한번 실행되고 doGet메소드는 주소를 한번 입력할때마다 계속 console에 log가 출력되게 됩니다.

반응형

'2020 > JSP SERVLET' 카테고리의 다른 글

게시판 글 삭제 기능 구현  (0) 2020.01.06
글 수정 기능 구현  (0) 2020.01.03
글 상세 구현  (0) 2020.01.03
게시판 글쓰기(파일첨부) 구현  (0) 2020.01.03
모델 2 답변형 게시판 구현(게시판 테이블 생성)  (0) 2020.01.02
블로그 이미지

꽃꽂이하는개발자

,
반응형

  이클립스는 통합 개발 환경 도구이므로 일일이 직접 만들 필요 없이 이클립스에서 설정만 해주면 됩니다. 그러면 이클립스에서 자동으로 톰캣에 프로젝트를 등록시켜줍니다. 지금부터 이클립스에서 톰캣과 어떻게 연동하는지 보겠습니다.

 

1. 이클립스 하단의 Servers 탭을 선택하고 마우스 오른쪽 버튼을 클릭한 후 New> Server를 선택.

2. 서버 설정창의 Apache 항목에서 Tomcat v9.0 Server을 선택한 후 Next 클릭

 

3. 톰캣 설치 디렉터리를 설정하기 위해 Browse... 를 클릭하여 톰캣 홈 디렉터리 경로를 선택한 후 폴더 선택을 클릭합니다.

4. 설정 경로를 한 번 더 확인하고 Finish를 클릭합니다. 이클립스 하단의 Server 탭을 보면 다음과 같이 표시됩니다.

 

5. 이클립스에서 톰캣 컨테이너를 추가하면 다음과 같이 프로젝트 탐색기에 Servers 항목이 추가되면서 톰캣과 관련된 xml 파일들이 나타납니다. 이클립스에서 톰캣 컨테이너를 설정할 때 톰캣 루트 디렉터리에 있던 여러 가지 xml 설정 파일들이 이클립스 Project Explorer 상단에 자동으로 복사된 것입니다.

반응형
블로그 이미지

꽃꽂이하는개발자

,