반응형

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

출처: 나동빈쌤

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

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>

 

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

반응형
블로그 이미지

꽃꽂이하는개발자

,