1. 程式人生 > >初學 Java web(二)application例項

初學 Java web(二)application例項

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