初学 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>



评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吃三明治的胖虎x

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值