1. 程式人生 > >WEB訊息提醒實現之二 實現方式-Jquery Ajax輪詢

WEB訊息提醒實現之二 實現方式-Jquery Ajax輪詢

Jquery Ajax輪詢

原理

普通的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>

測試

輸入圖片說明

輸入圖片說明

我們回到pollingPage.jsp頁面

輸入圖片說明

可以啦~!成功把訊息返回來,再提交一次資訊

輸入圖片說明

再看pollingPage.jsp

輸入圖片說明

OK,這樣基本的ajax輪詢實現訊息提醒就完成了。