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">×</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에 잘 저장되어 있다는 걸 알 수 있습니다.
'2020 > JSP 기본 WEB 만들기(미완성)' 카테고리의 다른 글
#8 로그인 디자인 및 기능 구현 (0) | 2020.05.29 |
---|---|
# 6 채팅 데이터베이스 구축 (0) | 2020.05.28 |
#5 채팅창 디자인 구현 (0) | 2020.05.27 |
#4 JSP 회원 가입 DB기능 구현 (0) | 2020.05.20 |
# 회원 가입 화면 만들기 (0) | 2020.05.20 |