利用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>