利用application实现简单的聊天室
login.jsp完成功能: 接收用户名,提交给chat.jsp
chat.jsp完成功能
获取登录用户名,显示欢迎信息
从application对象中获取所有用户的聊天记录,并显示(使用application对象的getAttribute方法)
获取用户输入的聊天信息,并提交给app.jsp
app.jsp完成功能
获取用户输入的聊天信息,将其添加到所有用户的聊天记录中,并保存(使用application对象的setAttribute方法)
跳转回chat.jsp。
仅供代码参考
login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="chat.jsp" name="log">
用户名:<input type="text" name="user">
<input type="submit" name="submit" value="login">
</form>
</body>
</html>
chat.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"%>
<!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>Insert title here</title>
</head>
<body>
<%
String user=request.getParameter("user");
if(user!=null)
{
session.setAttribute("user",user);}
%>
welcome: <%=session.getAttribute("user") %>
<form name="chat" action="app.jsp">
<textarea name="chatword" rows="5">
<%
ArrayList<String> says=new ArrayList<String>();
says=(ArrayList<String>)application.getAttribute("say");
if (says!=null){
for(int s=0;s<says.size();s++){
out.println(says.get(s));
}
}
%>
</textarea>
<br>
<input type="text" name="word">
<input type="submit" value="发言">
</form>
</body>
</html>
app.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"%>
<!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>Insert title here</title>
</head>
<body>
<%
String mywords=new String(request.getParameter("word").getBytes("iso-8859-1"));
ArrayList<String> says=new ArrayList<String>();
says=(ArrayList<String>)application.getAttribute("say");
if(says==null){
application.setAttribute("say", new ArrayList());
}
if(mywords!=null){
says.add(says.size(),mywords);
application.setAttribute("say", says);
}
response.sendRedirect("chat.jsp");
%>
</body>
</html>