创建一个登陆页面
<%@ page language="java" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>用户登陆</title>
</head>
<body>
<form action="chart.jsp" method="post">
帐号<input type="text" name="userName"/>
口令<input type="password" name="passwd"/>
<input type="submit" value="确认"/>
</form>
</body>
</html>
创建一个聊天页面名字为chart.jsp
<%@ page contentType="text/html; charset=GBK" import="java.util.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>My JSP 'chart.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<%response.setIntHeader("Refresh",10); %>
</head>
<body>
欢迎来到网站聊天系统
<%
/**
程序目的:模拟一个聊天室程序
测试方法,请在本机上打开3个IE窗口,从登陆界面进去。再发言.
反应可能不是很快,你多等一会。我已经测试过了.
**/
try{
//获取从用户登陆界面传递过来的用户
String loginname = request.getParameter("userName");
//获取用户的sessionId
String userSessionId=(String)session.getAttribute("userSessionId");
//根据sessionId取出用户帐号
String name = (String)session.getAttribute(userSessionId+"user");
//如果loginnmae!=null,表明用户初次登陆
if(loginname!=null)
{ //初次登陆,创造一个sessionid,把系统当前时间作为sessionId
userSessionId=System.currentTimeMillis()+"";
session.setAttribute("userSessionId",userSessionId);
//存储帐号在session中
session.setAttribute(userSessionId+"user",loginname);
}
//获取用户发言
String word = request.getParameter("yourWords");
//从application中所有用户历史发言
String chart = (String)application.getAttribute("chart");
//当发言到一定长度就清空,以免耗尽内存
if(chart!=null&&chart.length()>10000) application.setAttribute("chart","");
if(name!=null&&word!=null){
//组装用户在屏幕上发言语句:
String userword=new Date()+" 用户名:["+name+"]说:"+word;
//将用户发言存入历史记录中
chart+=userword+"/r/n";
application.setAttribute("chart",chart);
}
%>
<textarea rows="15" cols="40" name="output" style="width:100%">
<% if(name!=null) out.print(chart);
%>
</textarea>
<% if(name!=null) out.print(name+"说");%>
<form action="" method="post">
<input type="text" size="45" name="yourWords">
<input type="hidden" name="chart"><br>
<input type="submit" value="发送"/>
</form>
</body>
</html>
<%}catch(Exception e){
e.printStackTrace();
}%>