Web jsp开发学习——网上直播聊天室的简单开发

整个界面为chat.jsp:

如果用户没有登录,就不能进行聊天。

为将发言的句子传到页面上,要设置一个<iframe></iframe>虚拟框架,将allmessage.jsp的内容转过来

而allmessage.jsp里的内容是通过application获取发言的内容。点击“发言”,会调用chat.do的servlet,

 使用重定向可以将application传到allmessage.jsp

 

chat.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>直播室</title>
<style>
    #main #allmsg{border:solid 1px #ccc; height:400px;}
    #main #mymsg input[type=text]{width:800px; height:30px; }
    #main #mymsg input[type=submit]{width:80px; height:36px;
        font-size:20px; vertical-algin:middle; line-height:30px;}
</style>
<script>
    function Clear(){
        var frm = document.getElementById("form1");
        var obj = document.getElementById("msg");
        frm.submit();
        obj.value = "";
        return false
    }
</script>
</head>
<body>
<jsp:include page = "head.jsp?col=4"></jsp:include>
<div id="main" class="layout">
    <div id="allmsg">
        <iframe src="allmessage.jsp" width="1000" height="400" name="f1" frameborder="0"></iframe>
    </div>
    <%
        String user = (String)session.getAttribute("username");
        if(user!=null){
    %>
        <div id="mymsg">
            <form id="form1" action="chat.do" method="post" target="f1" onsubmit="return Clear();">
            <input type="text" id="msg" name="message">
            <input type="submit" value="发言">
            </form>
        </div>
    <%
        }
    %>
</div>
<%@ include file="foot.jsp" %>
</body>
</html>

ChatServlet doGet

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //获取表单数据
        request.setCharacterEncoding("utf-8");
        String msg = request.getParameter("message");
        System.out.println(msg);
        
        //获取session
        HttpSession session = request.getSession();
        String user = (String)session.getAttribute("username");
        
        //加入application
        ServletContext application = this.getServletContext();
        String allmsg = (String)application.getAttribute("chat");
        if(allmsg == null) {
            allmsg = "["+Tools.getTime()+"]"+ user + "说:" + msg + "<br>";
        }else {
            allmsg += "["+Tools.getTime()+"]"+ user + "说:" + msg + "<br>";
        }
        application.setAttribute("chat", allmsg);
        System.out.println(allmsg);
        
        // 重定向
        response.sendRedirect("allmessage.jsp");
    }

获取时间用这个

猜你喜欢

转载自www.cnblogs.com/caiyishuai/p/10728831.html
今日推荐