반응형

1. login.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>
<!-- 자바스크립트 내용 삭제 로그인 디자인 및 기능 구현 part 삭제-->
</head>
<body>

	<%
		//userID를 초기화 해주고 session에서 userID값을 가져옵니다. 만약에 null이 아니라면 userID에 가져온 userID값을 넣어줍니다.
	String userID = null;
	if (session.getAttribute("userID") != null) {
		userID = (String) session.getAttribute("userID");
	}
	//로그인 된 상태라면 (로그인 디자인 및 기능 구현 PART 추가 수정)
	if (userID != null){
		session.setAttribute("messageType", "오류 메시지");
		session.setAttribute("messageContent", "이미 로그인이 되어 있는 상태입니다.");
		response.sendRedirect("index.jsp");
		return;
	}
	%>
	<!-- 부트스트랩을 이용하여 메뉴를 만들어 주도록 하겠씁니다. -->
	<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>
			<!-- (로그인 디자인 및 기능 구현 PART 추가 삭제) -->
			<%
			}
			%>
		</div>
	</nav>
	<div class="container">
		<form method="post" action="./userLogin">
			<table class="table table-bordered table-hover" style="text-align: center; border: 1px solid #dddddd">
				<thead>
					<tr>
						<th colspan="2"><h4>로그인 양식</h4></th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td style="width: 110px;"><h5>아이디</h5></td>
						<td><input class="form-control" type="text" name="userID" maxlength="20" placeholder="아이디를 입력하세요."></td>
					</tr>
					<tr>
						<td style="width: 110px;"><h5>비밀번호</h5></td>
						<td><input class="form-control" type="password" name="userPassword" maxlength="20" placeholder="비밀번호를 입력하세요."></td>
					</tr>
					<tr>
						<td style="text-align: left;" colspan="2"><input class="btn btn-primary pull-right" type="submit" value="로그인">
					</tr>
				</tbody>
			</table>
		</form>
	</div>

	<!-- 회원 등록 양식 삭제 로그인 디자인 및 기능 구현 part  -->
	<%
		//서버로부터 내용을 받아왔는지 확인.
	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>

2. logoutAction.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">

<title>JSP Ajax fxProbest</title>
</head>
<body>
	<%
		session.invalidate();
	%>
	<script>
		location.href="index.jsp";
	</script>

</body>
</html>

3. index.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">

<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>
					<ul class="dropdown-menu">
						<li><a href="logoutAction.jsp">로그아웃</a></li>
					</ul>
				</li>
			</ul>
			<%
				}
			%>
		</div>
	</nav>
	<!-- 실시간 채팅 서비스 디자인 구현 -->
	<div class="container bootstrap snippet">
		<div class="row">
			<div class="col-xs-12">
				<div class="portlet portlet-default">
					<div class="portlet-heading">
						<div class="portlet-title">
							<h4><i class="fa fa-circle text-green"></i>실시간 채팅창</h4>
						</div>
						<div class="clearfix"></div>
					</div>
					
					<div id="chat" class="panel-collapse collapse in">
					
						<div id="chatList" class="portlet-body chat-widget" style="overflow-y auto; width: auto; height: 600px;">
						</div>
						<div class="portlet-footer">
						
							<div class="row" style="height: 90px;">
								<div class="form-group col-xs-10">
									<textarea style="height: 80px;" id="chatContent" class="form-control" placeholder="메시지를 입력하세요." maxlength="100"></textarea>
								</div>
								<div class="form-group col-xs-2">
									<button type="button" class="btn btn-default pull-right" onclick="submitFunction();">전송</button>
									<div class="clearfix"></div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="alert alert-success" id="successMessage" style="display: none;">
		<strong>메시지 전송에 성공하였습니다.</strong>
	</div>
	<div class="alert alert-danger" id="dangerMessage" style="display: none;">
		<strong>이름과 내용을 모두 입력해 주세요.</strong>
	</div>
	<div class="alert alert-warning" id="warningMessage" style="display: none;">
		<strong>데이터베이스 오류가 발생하였습니다.</strong>
	</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 id="container">

</div>
</body>
</html>

4. UserLoginServlet

package chat;

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;

import user.UserDAO;

/**
 * Servlet implementation class UserLoginServlet
 */
@WebServlet("/UserLoginServlet")
public class UserLoginServlet 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");
		String userPassword= request.getParameter("userPassword");
		// 만약에 userID나 userPassword가  null이거나 공백이라면 로그인을 할 수 없기 때문에 오류창을 띄움
		if(userID == null || userID.equals("") || userPassword == null || userPassword.equals("")) {
			request.getSession().setAttribute("messageType", "오류 메시지");
			request.getSession().setAttribute("messageContent", "모든 내용을 입력해주세요.");
			response.sendRedirect("login.jsp");
			return;
		}
		int result = new UserDAO().login(userID, userPassword);
		if(result==1) {
			request.getSession().setAttribute("userID", userID);
			request.getSession().setAttribute("messageType", "성공메 시지");
			request.getSession().setAttribute("messageContent", "로그인에 성공했습니다.");
			response.sendRedirect("index.jsp");
		}else if(result == 2) {
			request.getSession().setAttribute("messageType", "오류 메시지");
			request.getSession().setAttribute("messageContent", "비밀번호를 확인해 주세요.");
			response.sendRedirect("login.jsp");
		}else if(result == 0) {
			request.getSession().setAttribute("messageType", "오류 메시지");
			request.getSession().setAttribute("messageContent", "아이디가 정확하지 않습니다.");
			response.sendRedirect("login.jsp");
		}else if(result == -1) {
			request.getSession().setAttribute("messageType",  "오류 메시지");
			request.getSession().setAttribute("messageContent", "데이터 베이스 오류가 발생하였습니다.");
			response.sendRedirect("login.jsp");
		}
	}

}

5. web.xml 내용 추가

<?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>
  
  <servlet>
  	<servlet-name>ChatSubmitServlet</servlet-name>
  	<servlet-class>chat.ChatSubmitServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>ChatSubmitServlet</servlet-name>
  	<url-pattern>/chatSubmitServlet</url-pattern>
  </servlet-mapping>
  
    <servlet>
  	<servlet-name>ChatListServlet</servlet-name>
  	<servlet-class>chat.ChatListServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>ChatListServlet</servlet-name>
  	<url-pattern>/chatListServlet</url-pattern>
  </servlet-mapping>
  
  <servlet>
  	<servlet-name>UserLoginServlet</servlet-name>
  	<servlet-class>chat.UserLoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>UserLoginServlet</servlet-name>
  	<url-pattern>/userLogin</url-pattern>
  </servlet-mapping>
</web-app>

 

결과물

1. 로그인 양식

2. 기존의 db에 저장되어있는 아이디와 비밀번호로 로그인 가능. 

3. 아이디가 없으면 아이디 확인해달라는 메시지가 뜨고 비밀번호가 틀리면 비밀번호 확인해 달라는 메시지가 뜸.

 

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

1. 채팅 서블릿을 만들어 주겠습니다.

package chat;

import java.io.IOException;
import java.net.URLDecoder;

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

/**
 * Servlet implementation class ChatSubmitServlet
 */
@WebServlet("/ChatSubmitServlet")
public class ChatSubmitServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 request.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html; charset=UTF-8");
		 String fromID = request.getParameter("fromID");
		 String toID = request.getParameter("toID");
		 String chatContent = request.getParameter("chatContent");
		 if(fromID == null || fromID.equals("") || toID == null || toID.equals("") || chatContent == null || chatContent.equals("")) {
			 response.getWriter().write("0");
		 }else {
			 //괄호 안의 fromID, toID, chatContent 를 UTF-8로 바꿔줌
			 fromID = URLDecoder.decode(fromID, "UTF-8");
			 toID = URLDecoder.decode(toID, "UTF-8");
			 chatContent = URLDecoder.decode(chatContent, "UTF-8");
			 //사용자에게 값 반환
			 response.getWriter().write(new ChatDAO().submit(fromID, toID, chatContent) + "");
		 }
	}

}

2. web.xml에서 매핑을 추가해 주겠습니다.

<?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>
  
  <servlet>
  	<servlet-name>ChatSubmitServlet</servlet-name>
  	<servlet-class>chat.ChatSubmitServelt</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>ChatSubmitServlet</servlet-name>
  	<url-pattern>/chatSubmitServlet</url-pattern>
  </servlet-mapping>
  
    <servlet>
  	<servlet-name>ChatListServlet</servlet-name>
  	<servlet-class>chat.ChatListServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>ChatListServlet</servlet-name>
  	<url-pattern>/chatListServlet</url-pattern>
  	
  </servlet-mapping>
  
</web-app>

3. chat.jsp에 코드를 추가 하였습니다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<% //userID를 초기화 해주고 session에서 userID값을 가져옵니다. 만약에 null이 아니라면 userID에 가져온 userID값을 넣어줍니다.
		String userID = null;
	if(session.getAttribute("userID") != null){
		userID = (String) session.getAttribute("userID");
	}
	String toID = null;
	if(request.getParameter("toID") != null){
		toID = (String) request.getParameter("toID");
	}
	%>
<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>
<script type="text/javascript">
	function autoClosingAlert(selector, delay){
		var alert = $(selector).alert();
		alert.show();
		window.setTimeout(function() {alert.hide() }, delay);
	}
	function submitFunction(){
		var fromID = '<%= userID %>';
		var toID = '<%= toID %>';
		var chatContent = $('#chatContent').val();
		$.ajax({
			type: "POST",
			url: "./chatSubmitServlet",
			data: {
				fromID: encodeURIComponent(fromID),
				toID: encodeURIComponent(toID),
				chatContent: encodeURIComponent(chatContent),
			},
			success: function(result){
				if(result == 1) {
					autoClosingAlert('#successMessage', 2000);
				}else if(result == 0){
					autoClosingAlert('#dangerMessage', 2000);
				}else{
					autoClosingAlert('#warningMessage', 2000);
				}
			}
		});
		$('#chatContent').val("");
	}
</script>
</head>
<body>
	

	<!-- 부트스트랩을 이용하여 메뉴를 만들어 주도록 하겠습니다. -->
	<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 bootstrap snippet">
		<div class="row">
			<div class="col-xs-12">
				<div class="portlet portlet-default">
					<div class="portlet-heading">
						<div class="portlet-title">
							<h4><i class="fa fa-circle text-green"></i>실시간 채팅창</h4>
						</div>
						<div class="clearfix"></div>
					</div>
					
					<div id="chat" class="panel-collapse collapse in">
					
						<div id="chatList" class="portlet-body chat-widget" style="overflow-y auto; width: auto; height: 600px;">
						</div>
						<div class="portlet-footer">
							<div class="row" style="height: 90px;">
								<div class="form-group col-xs-10">
									<textarea style="height: 80px;" id="chatContent" class="form-control" placeholder="메시지를 입력하세요." maxlength="100"></textarea>
								</div>
								<div class="form-group col-xs-2">
									<button type="button" class="btn btn-default pull-right" onclick="submitFunction();">전송</button>
									<div class="clearfix"></div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="alert alert-success" id="successMessage" style="display: none;">
		<strong>메시지 전송에 성공하였습니다.</strong>
	</div>
	<div class="alert alert-danger" id="dangerMessage" style="display: none;">
		<strong>이름과 내용을 모두 입력해 주세요.</strong>
	</div>
	<div class="alert alert-warning" id="warningMessage" style="display: none;">
		<strong>데이터베이스 오류가 발생하였습니다.</strong>
	</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 id="container">
</div>
</body>
</html>

4.자동 로그인이 되도록 UserRegisterServelt에 코드를 한줄 추가 하였습니다.

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");
		
		System.out.println("userID: " + userID);
		System.out.println(userPassword1);
		System.out.println(userPassword2);
		System.out.println(userName);
		System.out.println(userAge);
		System.out.println(userGender);
		System.out.println(userEmail);
		System.out.println(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("userID", userID);
			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");
			
		}
	}
}

5. 회원가입을 하게 되면 이제오른쪽 상단에 회원관리라는 드랍다운이 생기게 됩니다. 아직 기능은 없습니다.

 

6. http://localhost:8080/UserChat/chat.jsp?toID=123 로 이동하여 메시지를 보내면

채팅 입력창 아래에 메시지를 보냈다고 우리가 설정한 시간동안 출력이되고 사라집니다.

 

7. 저는 총 2번의 테스트 문자를 보내봤습니다.

네 이렇게 DB에 잘 저장되어 있다는 걸 알 수 있습니다.

 

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

1. index.jsp를 복사하여 그대로 chat.jsp로 만들어 줍니다

2. chat.jsp 안에 있는 채팅관련 코드를 삭제합니다.

3. CHAT DB를 만들어 주겠습니다.

4. 모델을 만들어 주도록 하겠습니다. 우선 chat 패키지를 만들어주고 ChatDTO와 ChatDAO 클래스를 만들어 줍니다.

DTO를 만들어 주었습니다.

package chat;

public class ChatDTO {
	
//	mysql> create table chat(
//		    -> chatID INT PRIMARY KEY AUTO_INCREMENT,
//		    -> fromID VARCHAR(20),
//		    -> toID VARCHAR(20),
//		    -> chatContent VARCHAR(100),
//		    -> chatTime DATETIME);
	
	int chatID;
	String fromID;
	String toID;
	String chatContent;
	String chatTime;
	public int getChatID() {
		return chatID;
	}
	public void setChatID(int chatID) {
		this.chatID = chatID;
	}
	public String getFromID() {
		return fromID;
	}
	public void setFromID(String fromID) {
		this.fromID = fromID;
	}
	public String getToID() {
		return toID;
	}
	public void setToID(String toID) {
		this.toID = toID;
	}
	public String getChatContent() {
		return chatContent;
	}
	public void setChatContent(String chatContent) {
		this.chatContent = chatContent;
	}
	public String getChatTime() {
		return chatTime;
	}
	public void setChatTime(String chatTime) {
		this.chatTime = chatTime;
	}
	
	
}

DAO를 만들어 주었습니다.

package chat;

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

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

public class ChatDAO {

		DataSource dataSource;
		//DB접근
		public ChatDAO() {
			try {
				InitialContext initContext = new InitialContext();
				Context envContext = (Context) initContext.lookup("java:/comp/env");
				dataSource = (DataSource) envContext.lookup("jdbc/UserChat");
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		//함수 생성
		public ArrayList<ChatDTO> getChatListByID(String fromID, String toID, String chatID){
			ArrayList<ChatDTO> chatList = null;
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			String SQL = "SELECT * FROM CHAT WHERE ((fromID = ? AND toID =?) OR (toID = ? AND fromID = ?)) AND chatID > ? ORDER BY chatTime";
			
			try {
				//db연결
				conn = dataSource.getConnection();
				pstmt = conn.prepareStatement(SQL);
				pstmt.setString(1,  fromID);
				pstmt.setString(2,  toID);
				pstmt.setString(3,  toID);
				pstmt.setString(4,  fromID);
				pstmt.setInt(5, Integer.parseInt(chatID));
				rs = pstmt.executeQuery();
				chatList = new ArrayList<ChatDTO>();
				while(rs.next()) {
					ChatDTO chat = new ChatDTO();
					chat.setChatID(rs.getInt("chatID"));
					chat.setFromID(rs.getString("fromID").replaceAll(" ", "&nbsp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br>"));
					chat.setToID(rs.getString("toID").replaceAll(" ", "&nbsp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br>"));
					chat.setChatContent(rs.getString("ChatContent").replaceAll(" ", "&nbsp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br>"));
					int chatTime = Integer.parseInt(rs.getString("chatTime").substring(11, 13));
					String timeType = "오전";
					if(chatTime > 12) {
						timeType = "오후";
						chatTime -= 12;
					}
					chat.setChatTime(rs.getString("chatTime").substring(0, 11) + " " + timeType + " " + chatTime + ":" + rs.getString("chatTime").substring(14, 16)+ "");
					chatList.add(chat);
							
				}
			} 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 chatList; //리스트 반환 
			
		}
		
			//대화 내역 중 최근 몇개만 가져옴
				public ArrayList<ChatDTO> getChatListByRecent(String fromID, String toID, int number){
					ArrayList<ChatDTO> chatList = null;
					Connection conn = null;
					PreparedStatement pstmt = null;
					ResultSet rs = null;
					String SQL = "SELECT * FROM CHAT WHERE ((fromID = ? AND toID =?) OR (fromID = ? and toID = ?)) AND chatID > (SELECT MAX(cahtID) - ? FROM CHAT) ORDER BY chatTime";
					
					try {
						//db연결
						conn = dataSource.getConnection();
						pstmt = conn.prepareStatement(SQL);
						pstmt.setString(1,  fromID);
						pstmt.setString(2,  toID);
						pstmt.setString(3,  toID);
						pstmt.setString(4,  fromID);
						pstmt.setInt(5, number);
						rs = pstmt.executeQuery();
						chatList = new ArrayList<ChatDTO>();
						while(rs.next()) {
							ChatDTO chat = new ChatDTO();
							chat.setChatID(rs.getInt("chatID"));
							chat.setFromID(rs.getString("fromID").replaceAll(" ", "&nbsp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br>"));
							chat.setToID(rs.getString("toID").replaceAll(" ", "&nbsp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br>"));
							chat.setChatContent(rs.getString("ChatContent").replaceAll(" ", "&nbsp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br>"));
							int chatTime = Integer.parseInt(rs.getString("chatTime").substring(11, 13));
							String timeType = "오전";
							if(chatTime > 12) {
								timeType = "오후";
								chatTime -= 12;
							}
							chat.setChatTime(rs.getString("chatTime").substring(0, 11) + " " + timeType + " " + chatTime + ":" + rs.getString("chatTime").substring(14, 16)+ "");
							chatList.add(chat);
									
						}
					} 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 chatList; //리스트 반환 
					
				}
				
				// 채팅을 상대방에게 보내는 기능
				// fromID로부터 toID에게 어떠한 chatContent를 보내는지.
				public int submit(String fromID, String toID, String chatContent){
					Connection conn = null;
					PreparedStatement pstmt = null;
					ResultSet rs = null;
					String SQL = "INSERT INTO CHAT VALUES (NULL, ?, ?, ?, NOW())";
					try {
						//db연결
						conn = dataSource.getConnection();
						pstmt = conn.prepareStatement(SQL);
						pstmt.setString(1,  fromID);
						pstmt.setString(2,  toID);
						pstmt.setString(3,  chatContent);
						//성공적으로 채팅을 보냈다면  1개의 데이터에 삽입이 되서 1이라는 값이 반환
						return pstmt.executeUpdate();
					} 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; //데이터베이스 오류
					
				}
		
}
반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

1. 회원 가입시 index.jsp로 넘어가면서 회원가입 성공이라는 모달창 띄움

2. 실시간 채팅창 디자인 구현 (index.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">

<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>
	<!-- 실시간 채팅 서비스 디자인 구현 -->
	<div class="container bootstrap snippet">
		<div class="row">
			<div class="col-xs-12">
				<div class="portlet portlet-default">
					<div class="portlet-heading">
						<div class="portlet-title">
							<h4><i class="fa fa-circle text-green"></i>실시간 채팅창</h4>
						</div>
						<div class="clearfix"></div>
					</div>
					
					<div id="chat" class="panel-collapse collapse in">
					
						<div id="chatList" class="portlet-body chat-widget" style="overflow-y auto; width: auto; height: 600px;">
						</div>
						<div class="portlet-footer">
							<div class="row">
				   				<div class="form-group col-xs-4">
									<input style="height: 40px;" type="text" id="chatName" class="form-control" placeholder="이름" maxlength="8">
									
								</div>
							</div>
							<div class="row" style="height: 90px;">
								<div class="form-group col-xs-10">
									<textarea style="height: 80px;" id="chatContent" class="form-control" placeholder="메시지를 입력하세요." maxlength="100"></textarea>
								</div>
								<div class="form-group col-xs-2">
									<button type="button" class="btn btn-default pull-right" onclick="submitFunction();">전송</button>
									<div class="clearfix"></div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="alert alert-success" id="successMessage" style="display: none;">
		<strong>메시지 전송에 성공하였습니다.</strong>
	</div>
	<div class="alert alert-danger" id="dangerMessage" style="display: none;">
		<strong>이름과 내용을 모두 입력해 주세요.</strong>
	</div>
	<div class="alert alert-warning" id="warningMessage" style="display: none;">
		<strong>데이터베이스 오류가 발생하였습니다.</strong>
	</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 id="container">

</div>
</body>
</html>

 

 

3. 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;
}

/* 채팅창 디자인 처리 */
.portlet {
	margin-bottom: 15px;
}

.btn-white {
	border-color: #cccccc;
	color: #333333;
	background-color: #ffffff;
}

.portlet {
	border: 1px solid;
}

.portlet .portlet-heading {
	padding: 0 15px;
}

.portlet .portlet-heading h4 {
	padding: 1px 0;
	font-size: 16px;
}

.portlet .portlet-heading a {
	color: #fff;
}

.portlet .portlet-heading a:hover, .portlet .portlet-heading a:active,
	.portlet .portlet-heading a:focus {
	outline: none;
}

.portlet .portlet-widgets .dropdown-menu a {
	color: #333;
}

.portlet .portlet-widgets ul.dropdown-menu {
	min-width: 0;
}

.portlet .portlet-heading .portlet-title {
	float: left;
}

.portlet .portlet-heading .portlet-title h4 {
	margin: 10px 0;
}

.portlet .portlet-heading .portlet-widgets {
	float: right;
	margin: 8px 0;
}

.portlet .portlet-heading .portlet-widgets .tabbed-portlets {
	display: inline;
}

.portlet .portlet-heading .portlet-widgets .divider {
	margin: 0 5px;
}

.portlet .portlet-body {
	padding: 15px;
	background: #fff;
}

.portlet .portlet-footer {
	padding: 10px 15px;
	background: #e0e7e8;
}

.portlet .portlet-footer ul {
	margin: 0;
}

.portlet-green, .portlet-green>.portlet-heading {
	border-color: #16a085;
}

.portlet-green>.portlet-heading {
	color: #fff;
	background-color: #16a085;
}

.portlet-orange, .portlet-orange>.portlet-heading {
	border-color: #f39c12;
}

.portlet-orange>.portlet-heading {
	color: #fff;
	background-color: #f39c12;
}

.portlet-blue, .portlet-blue>.portlet-heading {
	border-color: #2980b9;
}

.portlet-blue>.portlet-heading {
	color: #fff;
	background-color: #2980b9;
}

.portlet-red, .portlet-red>.portlet-heading {
	border-color: #e74c3c;
}

.portlet-red>.portlet-heading {
	color: #fff;
	background-color: #e74c3c;
}

.portlet-purple, .portlet-purple>.portlet-heading {
	border-color: #8e44ad;
}

.portlet-purple>.portlet-heading {
	color: #fff;
	background-color: #8e44ad;
}

.portlet-default, .portlet-dark-blue, .portlet-default>.portlet-heading,
	.portlet-dark-blue>.portlet-heading {
	border-color: #34495e;
}

.portlet-default>.portlet-heading, .portlet-dark-blue>.portlet-heading {
	color: #fff;
	background-color: #34495e;
}

.portlet-basic, .portlet-basic>.portlet-heading {
	border-color: #333;
}

.portlet-basic>.portlet-heading {
	border-bottom: 1px solid #333;
	color: #333;
	background-color: #fff;
}

@media ( min-width :768px) {
	.portlet {
		margin-bottom: 30px;
	}
}

.img-chat {
	width: 40px;
	height: 40px;
}

.text-green {
	color: #16a085;
}

.text-orange {
	color: #f39c12;
}

.text-red {
	color: #e74c3c;
}

출처: 나동빈쌤

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

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;
}
반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

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>

 

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

반응형
블로그 이미지

꽃꽂이하는개발자

,