作业内容:
实现一个web聊天室,思路:可以将聊天信息放到application对象中。设计三个页面:主页面index.jsp包含两部分:上面是iframe,放置content.jsp,用于从application中取出聊天信息并显示,几秒刷新一次。下面是发送聊天信息的表单。表单提交给addinfo.jsp,用于将表单提交的信息存到application中。聊天信息只保留最新的5条。(提示:可以用List存储聊天信息)。
效果图:
作业实现地址:https://yuheng.tech:8080/test9/index.jsp
代码:
作业地址: https://yuheng.tech:8080/test9/index.jsp 代码--------------------------------------- index.jsp <%@ page pageEncoding="utf-8"%> <html> <body background="blue"> <input type="button" onclick="history.go(-1)" value="返回上一层"> <a href="javascript:history.go(-1)" ></a> <a href="/javaweb/index.html"><button>返回JAVA WEB总菜单</button></a> <a href="/javaweb/test_index.html"><button>到作业目录</button></a> <h1 align="center" style="color: #9932CC ;font-size: 36px;">在线聊天室</h1> <iframe src="content.jsp" name="content" width="100%" height="75%" style="background-color=transparent"></iframe> <form action="addinfo.jsp" target="content" id="chatform" method="post" > <p>编辑留言区:</p> 昵称:<input type="text" name="nicheng" id="nicheng"> 发言:<input type="text" name="info" id="info"> <input type="submit" value="确定" onclick="return check()"> </form> <script> function check() { //补充代码,昵称留言为空不允许提交 var nicheng = document.getElementById("nicheng").value; var info = document.getElementById("info").value; if (nicheng == null || nicheng == ""||info == null || info == "") { alert("昵称不能为空!"); return false; } } </script> </body> </html> ---------------------------------------------- content.jsp <%@ page pageEncoding="utf-8" import="java.util.*,java.text.*"%> <html> <head> <meta http-equiv="refresh" content="10"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cacshe"> <meta http-equiv="expires" content="0"> <style type="text/css"> body{ background: url(image/bg.jpg) no-repeat center 0; } p{ color:white; font-family: sans-serif; font-size: 24px; } </style> </head> <body> <% //显示application中的信息 ArrayList<String> infoList=(ArrayList<String>)application.getAttribute("infoList"); if(infoList==null){ %> <%=" " %> <% } else { %> document.body.innerHTML = ""; <% for(int i=0;i<infoList.size();i++){ %> <p><%=infoList.get(i)+"<br>" %></p> <% } } %> </body> </html> -------------------------------------------------------------- addinfo.jsp <%@ page pageEncoding="utf-8" import="java.util.*,java.text.*"%> <html> <body background="#00e09e"> <%!List<String> List=new ArrayList<String>(); %> <% request.setCharacterEncoding("UTF-8"); String nicheng=request.getParameter("nicheng"); String info=request.getParameter("info"); String time=new SimpleDateFormat("yy-MM-dd kk:mm:ss").format(new Date());//当前时间 if(List.size()==0) { //第一次存储信息 String s=nicheng+" "+time+":<br>"+info+"<br>"; List.add(s); application.setAttribute("infoList", List); } else{ if(List.size()==5){ //够5条 List.clear(); } List.add(nicheng+" "+time+":<br>"+info+"<br>"); application.setAttribute("infoList", List); } response.sendRedirect("content.jsp"); //重定向到content.jsp %> </body> </html>