前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >聊天室收发信息

聊天室收发信息

作者头像
ydymz
发布2018-09-10 14:53:56
7771
发布2018-09-10 14:53:56
举报
文章被收录于专栏:lgp20151222lgp20151222

要自己做一个聊天室

在这里写下思路

聊天室,首先就是要有信息的收发

也就是收集和显示

代码语言:javascript
复制
信息显示
chatinfo.jsp

<body>
    <table align="center" cellspacing="10">
        <tr>
            <td colspan="3"><textarea rows="20" cols="80">${applicationScope.talks}</textarea>
            </td>
        </tr>
    </table>
</body>
代码语言:javascript
复制
信息收集
index.jsp
<body>
    <table align="center">
            <tr>
                <td colspan="2">
                    <iframe src="chatinfo.jsp" width="800px" height="460px"></iframe>
                </td>
            </tr>
            <tr>
                <td align="center">
                    <form action="chat.do" method="post">
                        <input type="text" name="chat" size="60">
                        <input type="submit" value="发言">
                    </form>
                </td>
            </tr>
        </table>
</body>

 前端搞定了,就要想想怎么写后面

由于不用数据库

发送的信息一定要保存在服务器端

根据其存在时间,我觉得用servletcontext来最好

写个监听器监听servletcontext

代码语言:javascript
复制
public class ContextListener implements ServletContextListener {
    public static final String Talks = "talks";
    //static final 静态最终啥的玩意 其实就是放在application里的数据
    //Talks是服务器内部调用的 ContextListener.Talks
    //talks是web前端调用的 applicationScope.talks
    private StringBuilder talks = new StringBuilder();
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub
        sce.getServletContext().removeAttribute(Talks);
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // TODO Auto-generated method stub
        sce.getServletContext().setAttribute(Talks, talks);
    }
}

 最后上个servlet就好了

其中的dopost方法

代码语言:javascript
复制
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String talk=req.getParameter("talks");
        ServletContext sc = this.getServletContext();
        StringBuilder sb = (StringBuilder) sc
                .getAttribute(ContextListener.Talks);
        sb.append(String.format("说:%s%n", talk));
        resp.sendRedirect(req.getContextPath() + "/index.jsp");
    }

 最后web.xml我就不写了

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-02-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档