• ajax轮询


    http://blog.csdn.net/qq_23412263/article/details/70260057

    原理

    普通的jquery ajax轮询的原理主要是,客户端通过定时器定时发送ajax请求到服务器,服务器获取数据后马上响应并关闭连接。

    普通的jquuery ajax轮询过程如下图:

    输入图片说明

    可以看到,每次请求都会到服务器中获取数据回来(不管数据有没有变化),然后关闭连接,再进行下一次的请求,如此反复。

    优点:后端程序编写比较容易。

    缺点:请求中有大半是无用,浪费带宽和服务器资源。

    实例

    要实现消息提醒,当然首先得要有消息才行啦,以下是用来发送消息的Servlet:

    /**
     * 用于发送消息的servlet,也就是把消息保存到数据库中
     * @author 马艺俊
     *
     */
    public class SendMsgServlet extends HttpServlet {
    
            @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
    
    
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        Message msg = new Message();
        msg.setTitle(title);
        msg.setContent(content);
    
        MessageDao msgDao = new MessageDao();
    
        msgDao.insertMsg(msg);
    
        PrintWriter out = resp.getWriter();
    
        out.write("发送完毕!");
    
        out.flush();
    
        out.close();
    }
    
    }
    

    发送消息的后台有了,前台提供一个简单的表单页面:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServ    erPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
    
        <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
      </head>
    
      <body>
    <form action="SendMsgServlet" method="post">
        <table>
            <tr>
                <td>标题</td>
                <td><input type="text" name="title"/></td>
            </tr>
            <tr>
                <td>内容</td>
                <td><textarea name="content"></textarea></td>
            </tr>
            <tr><td>
                <input type="submit" value="提交"/>
            </td></tr>
        </table>
    </form>
      </body>
    </html>
    

    消息有了,前台就可以定时发送请求来服务查询数据了,下面是返回数据库message表消息数量的Servlet:

    /**
     * 轮询实现消息提醒
     * @author 马艺俊
     *
     */
    public class PollingMsgServlet extends HttpServlet {
    
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    
        req.setCharacterEncoding("utf-8");
    
        PrintWriter out = resp.getWriter();
    
        MessageDao msgDao = new MessageDao();
        int num = msgDao.getMsgNum();
    
        Message msg = msgDao.getTheNewestMsg();
    
        StringBuffer msgJson = new StringBuffer("{");
        msgJson.append(""id":"+msg.getId()+",");
        msgJson.append(""title":""+msg.getTitle()+"",");
        msgJson.append(""content":""+msg.getContent()+""");
        msgJson.append("}");
    
        StringBuffer json = new StringBuffer("{");
        json.append(""msgNum":"+num+","msg":"+msgJson);
        json.append("}");
        out.write(json.toString());
        out.close();
    }
    
    }
    

    前台要定时发送ajax到后台请求数据,并刷新数据:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServ    erPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src="jquery-easyui-v1.4.4/jquery.min.js"></script>
    
    <script type="text/javascript">
    setInterval(function(){
        getMsgNum();
    },3000);
    
    function getMsgNum(){
        $.ajax({
            url:'PollingMsgServlet',
            type:'post',
            dataType:'json',
            success:function(data){
                if(data && data.msgNum){
                    $("#msgNum").html(data.msgNum);
    
                    $("#title").html(data.msg.title);
                    $("#content").html(data.msg.content);
                } 
            }
        });
    }
    
    </script>
      </head>
    
      <body>
    <div>
        您有<span id="msgNum" style="color: red;">0</span>条消息!
    </div>
    <div>
        <p id="title">title</p>
        <p id="content">content</p>
    </div>
      </body>
    </html>
    

    测试

    项目部署好后,访问http://localhost:8088/JsPollingDemo/pollingPage.jsp

    输入图片说明

    现在还没有新的消息,不关闭这个页面,我们访问http://localhost:8088/JsPollingDemo/ 提交信息。

    输入图片说明

    我们回到pollingPage.jsp页面

    输入图片说明

    可以啦~!成功把消息返回来,再提交一次信息

    输入图片说明

    再看pollingPage.jsp

    输入图片说明

    OK,这样基本的ajax轮询实现消息提醒就完成了。

  • 相关阅读:
    线程的同步之Synchronized的使用
    线程的优先级
    线程的状态和常用操作
    Eclipse设置代码模板Code Template
    Eclipse设置每行代码的长度
    Eclipse设置控制台字体
    Gradle 安装(Windows)
    DSL与GPL
    Windows 新增 Sublime Text3 右键快捷方式
    mvn install 上传 jar 包到Maven仓库
  • 原文地址:https://www.cnblogs.com/bobc/p/8135336.html
Copyright © 2020-2023  润新知