Java Web入门之网络聊天室

书本最后是一个聊天室的小项目,我就将之作为java web学习小阶段的结束。书本上提供了完整的解决方案,实际上我参考的也不多,更多的还是自己思考设计的。过程之中发现我会的东西还是太少了,要做web后端必须也很熟悉前端才行。只能以我当前会的东西做一个简陋的聊天室了。

先看一下界面

登陆界面
登陆界面
聊天界面
聊天界面

再说一下逻辑

数据存储

namecontentscope
name当前用户的名字session
usernum在线用户数量application
username在线用户的名字集合application
begin聊天记录的开始位置application
end聊天记录的结束位置application
talk11号位置application
talkxx号位置application

在application中分配50个位置来存储聊天记录,分别为1-50,这相当于一个队列,FIFO,begin和end来记录队列的起始和结束。

流程

login.html,输入名字→check.jsp,将名字写入session和application→charroom.jsp,聊天界面。
聊天界面由3个frame构成,users.jsp负责显示在线用户列表,input.jsp负责用户输入信息,chats.jsp负责显示所有聊天记录。
input.jsp将用户输入的内容post给talk.jsp,talk.jsp负责将这些内容存到application中。

代码

login.html,登陆界面

<html>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript">
    // 从url 字符串中提取变量的值
    function GetQueryValue(sorStr, panStr)
    {
        var vStr = "";
        if (sorStr==null || sorStr=="" || panStr==null || panStr=="") return vStr;
        sorStr = sorStr.toLowerCase();
        panStr += "=";
        var itmp = sorStr.indexOf(panStr);
        if (itmp < 0) return vStr;
        sorStr = sorStr.substr(itmp + panStr.length);
        itmp = sorStr.indexOf("&");
        if (itmp < 0) return sorStr;
        else
        {
            sorStr = sorStr.substr(0, itmp);
            return sorStr;
        }
    }
</script>

<body><br><br><br><br><center>
大侠请输入你的名号<br>
    <form action="check.jsp" method="post">
        <input type=text name="name">
        <input type=submit value="开始">
    </form>
<p id="alert"></p>
<script>
// 获得url字符串
var strGetQuery = document.location.search;
// 获得alert参数的值
var stylevalue = GetQueryValue(strGetQuery,'alert');
// 输出
document.getElementById("alert").innerHTML = stylevalue;
</script>
</center></body>
</html>

它可以接受alert参数,并将参数内容输出。

check.jsp,用来检查名字有效性

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<html>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<body>
    <%
        request.setCharacterEncoding("utf-8");

        //名字为空
        String name = request.getParameter("name");
        if(name == null || name == "") {
            response.sendRedirect("login.html");
            return;
        }

        //这是第一个用户
        String strusernum = (String)application.getAttribute("usernum");
        int usernum = 0;
        if(strusernum != null)  usernum = Integer.parseInt(strusernum);
        if(strusernum == null || usernum == 0) {
            application.setAttribute("username", name+";");
            application.setAttribute("usernum", "1");
            session.setAttribute("name", name);
            response.sendRedirect("chatroom.jsp");
            return;
        }

        //已有用户
        String username = (String)application.getAttribute("username");
        if(username.contains(name)) {
            response.sendRedirect("login.html?alert=The_name_already_exists.");
            return;
        }

        //新用户
        ++usernum;
        application.setAttribute("username", username+name+";");
        application.setAttribute("usernum", ""+usernum);
        session.setAttribute("name", name);
        response.sendRedirect("chatroom.jsp");
    %>
</body>
</html>

chatroom.jsp,这是聊天室主界面

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>chat room</title>
    </head>
    <%response.setHeader("refresh","5");%>
    <%if(request.getSession().getAttribute("name") == null){%>
    <jsp:forward page="login.html"/>
    <%}%>
    <frameset cols="80%,*">
        <frameset rows="70%,*" >
            <frame src="chats.jsp" name="frachats" scrolling="no">
            <frame src="input.jsp" scrolling="no">
        </frameset>
        <frame src="users.jsp" frameborder=0>
    </frameset>
</html>

users.jsp,显示当前在线用户

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<html>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
<body>
<%String strusernum = (String)application.getAttribute("usernum");%><%=strusernum%>位在线用户:
    <hr>
    <%
    int usernum = Integer.parseInt(strusernum);
    String username = (String)application.getAttribute("username");
    String[] names = username.split(";");
    for (int i=0; i<usernum; ++i) out.print(names[i]+"<br>");
    %>
</body>
</html>

input.jsp,用户输入消息的界面

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<html>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
<head>
    <script language="javascript">
        function chk()
        {
            if(content.txttalk.valu == "") return;
            content.submit();
            content.txttalk.value = "";
        }
    </script>
</head>
<body>
    <p>你好,<%=(String)request.getSession().getAttribute("name")%></p>
    <form name=content action="talk.jsp" method="post" target="frachats">
        <textarea name="txttalk" rows="4" cols="100"></textarea>
        <input type="button" value="发言" onclick="chk()">
        <input name="" type="reset" value="清除">
    </form>
</body>
</html>

chats.jsp,显示所有聊天记录的界面

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<html>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <script type="text/javascript">
    function pagescrolltoend() {
        var c = window.document.body.scrollHeight;
        window.scroll(0,c); 
    }
    function divscrolltoend() {
        var div = document.getElementById('scrolldIV');
        div.scrollTop = div.scrollHeight; 
    }
    </script>
<body onload="divscrolltoend()">
    <marquee>通知:本聊天室正式开放</marquee>
    <br>
    <br>
    <div id="scrolldIV" style="overflow:scroll; height: 500px; width: auto; border: 1px solid #999;">
        <%
            String strbegin = (String)application.getAttribute("begin");
            if(strbegin == null){
                out.println("nothing");
                return;
            } else {
                int begin = Integer.parseInt(strbegin);
                int end = Integer.parseInt((String)application.getAttribute("end"));
                if (begin < end) {
                    for (int i=begin; i<end; ++i) {
                        out.print((String)application.getAttribute("talk"+i)+"<br>");
                    }
                }
                else {
                    for(int i=begin; i<102; ++i) out.println((String)application.getAttribute("talk"+i)+"<br>");
                    for(int i=1; i<end; ++i) out.println((String)application.getAttribute("talk"+i)+"<br>");
                }
            }
        %>
    </div>
</body>
</html>

talk.jsp,处理用户消息,将其插入消息记录的页面

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<html>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
<body>
    <%
    request.setCharacterEncoding("utf-8");
    String text = request.getParameter("txttalk");
    if(text == null || text == "") {
        response.sendRedirect("chats.jsp");
        return;
    }
    String name = (String)session.getAttribute("name");
    Date date=new Date();
    SimpleDateFormat f=new SimpleDateFormat(" [HH:mm:ss]");
    String time=f.format(date);
    String strbegin = (String)application.getAttribute("begin");
    text = name+time+"<br>"+text;
    if(strbegin == null) {
        application.setAttribute("begin", "1");
        application.setAttribute("end", "2");
        application.setAttribute("talk1", text);
    } else {
        String strend = (String)application.getAttribute("end");
        int end = Integer.parseInt(strend);
        int begin = Integer.parseInt(strbegin);
        application.setAttribute("talk"+end, text);
        ++end;
        if(end == 102) end = 1;
        if(end == begin) {
            ++begin;
            if(begin ==102) begin = 1;
            application.setAttribute("begin", ""+begin);
        }
        application.setAttribute("end", ""+end);
    }
    response.sendRedirect("chats.jsp");
    %>
</body>
</html>

bugs

信息的实时显示,通过设定页面自动更新response.setHeader("refresh","5");来实现,没办法,前端的东西不懂,只能这样实现了。
重要问题!用户关闭浏览器或因其他原因退出聊天室的时候,服务器是没响应的!预期解决方法:将session的有效期设置为一个较小的值,并为session的销毁设定一个监听器,session销毁时,将application中存储的此用户删去。
关于session和监听器的内容,后面的文章再说。在线用户删除功能就不实现了吧。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值