login.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><title>登入聊天室</title></head><body><table width="400" height="100" border="1" align="center"cellpadding="0" cellspacing="0"><tr><td align="center">登入聊天室</td></tr><tr><td align="center"><form name="form1" method="post"action="/charpter19/method.jsp?action=login">您的暱稱:<input name="username" id="username" type="text" /> <inputtype="submit" name="Submit" value="進入" /></form></td></tr></table></body></html>
method.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%><%@ page import="java.util.*"%><jsp:useBean id="msgs" class="java.util.HashMap" scope="application" /><%request.setCharacterEncoding("UTF-8");String action = request.getParameter("action");if (action.equals("login")) {//使用者登入,獲得使用者名稱。然後建立兩個變數,儲存使用者登入資訊和聊天資訊String username = request.getParameter("username");String msg = "歡迎" + username + "光臨本聊天室。<br/>";session.setAttribute("username", username);msgs.put(username, msg);response.sendRedirect("main.html");}if (action.equals("sendMsg")) {String newMsg = session.getAttribute("username") + ":" + request.getParameter("msg");//發送訊息時,將聊天室所有人的訊息都加上新的發言內容Iterator it = msgs.keySet().iterator();String username = null;String msg = null;while (it.hasNext()) {username = (String) it.next();msg = (String) msgs.get(username);msg = msg + "<br/>" + newMsg;msgs.put(username, msg);}response.sendRedirect("inputMsg.jsp");}if (action.equals("showMsg")) {//顯示某個使用者的訊息String username = (String) session.getAttribute("username");String msg = (String) msgs.get(username);out.println("loadContent.innerHTML=\""+msg+"\";");}%>
main.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><title>聊天室首頁面</title></head><frameset rows="*,80" frameborder="yes" border="2" framespacing="2"><frame src="showMsg.html" name="mainFrame"><frame src="inputMsg.jsp" name="bottomFrame" scrolling="no"noresize="noresize"></frameset></html>
inputMsg.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title></title></head><body><form name="form1" method="post"action="/charpter19/method.jsp?action=sendMsg"><%=session.getAttribute("username")%>:<input name="msg" id="msg"type="text" size="60" /> <input type="submit" name="Submit"value="發言" /></form></body></html>
showMsg.html
<html><head><script language="javascript" type="text/javascript">function GetData(){url = "/charpter19/method.jsp?action=showMsg";try{DataLoad.src = url;}catch(e){return false;}{var timeoutid = setTimeout("GetData()",2000)}}</script><script id="DataLoad" language="javascript" type="text/javascript" defer></script></head><body onload="javascript:GetData();"><span id="loadContent">資料載入中……</span></body></html>