使用Ajax輪詢模擬簡單的站內信箱(消息管理)功能

前一段時間項目須要寫一個相似於站內信箱的消息管理的功能,因爲對前端不是很熟悉,剛開始不知道怎麼作,後來看了網上的方案,現模擬一個很是簡單的消息管理。html

咱們首先看一下最終效果的樣式,就是很是簡單的一個樣子,以下所示:前端

我這邊暫時只寫了三個類型的消息,訂單、上下架、審覈。不一樣的消息推送過來會顯示在不一樣類型上,消息管理上顯示的是三種類型的消息總數量。ajax

好,接下來介紹一下代碼。首先是數據庫的設計,共有七個字段,分別是一個自增字段id,消息類型type,消息標題title,消息具體內容detail,消息狀態status,建立時間time以及用戶userId。以下所示:數據庫

而後咱們看推送消息的後臺代碼PullMsgServlet,分別有四個方法,分別是獲取全部消息的歷史記錄,獲取某人的未讀消息,獲取未讀消息的總數,還有獲取某種類型的未讀消息總數。json

 1 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2         String operateType = Base64Util.decode(request.getParameter("operateType"));
 3         msgDao = new MessageDao();
 4         switch (operateType) {
 5             case "showHistory":
 6                 showHistory(request, response);
 7                 break;
 8             case "showPending":
 9                 showPending(request, response);
10                 break;
11             case "showCount":
12                 showCount(request,response);
13                 break;
14             case "showCountByType":
15                 showCountByType(request, response);
16                 break;
17             default:
18                 break;
19         }
20         response.setCharacterEncoding("utf-8");
21         response.setContentType("text/html;charset=UTF-8");
22         response.getWriter().print(Base64Util.encode(result.toString()));
23     }
24 
25     /**
26      * 全部消息的歷史記錄
27      * @param request
28      * @param response
29      * @throws ServletException
30      * @throws IOException
31      */
32     private void showHistory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
33         HttpSession session = request.getSession();
34         userId = session.getAttribute("userId").toString();
35         List<Object> historyList = msgDao.getMsgByUserId(userId);
36         HttpResultList result = new HttpResultList();
37         result.setResult(historyList.size()>0);
38         result.setDatas(historyList);
39     }
40 
41     /**
42      * 某人的未讀消息
43      * @param request
44      * @param response
45      * @throws ServletException
46      * @throws IOException
47      */
48     private void showPending(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
49         HttpSession session = request.getSession();
50         userId = session.getAttribute("userId").toString();
51         List<Object> pendingList = msgDao.getUnreadMsg();
52         HttpResultList result = new HttpResultList();
53         result.setResult(pendingList.size()>0);
54         result.setDatas(pendingList);
55     }
56 
57     /**
58      * 某人未讀消息的總數
59      * @param request
60      * @param response
61      * @throws ServletException
62      * @throws IOException
63      */
64     private void showCount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
65         String number = msgDao.getMsgNum()+"";
66         result = new JSONObject();
67         result.put("result", number);
68     }
69 
70     /**
71      * 某人某種類型的未讀消息總數
72      * @param request
73      * @param response
74      * @throws ServletException
75      * @throws IOException
76      */
77     private void showCountByType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
78         Map<String, Integer> map = msgDao.getTypeNum();
79         //得到返回的type
80         List<String> keyList = new ArrayList<>();
81         for (String key : map.keySet()) {
82             keyList.add(key);
83         }
84         //得到返回type的個數
85         List<Integer> valueList = new ArrayList<>();
86         for (Integer value : map.values()) {
87             valueList.add(value);
88         }
89         result = new JSONObject();
90         JSONObject content = new JSONObject();
91         content.put("type", JSONArray.fromObject(keyList));
92         content.put("typeNum", JSONArray.fromObject(valueList));
93         result.put("result", content);
94     }

接下來咱們看前端代碼,這邊使用了setInterval定時器,設置的js代碼每5秒輪詢後臺一次,請求後臺servlet從數據庫裏面獲取的數據,以下所示:session

 1 setInterval(function(){
 2     getType();
 3 },5000);
 4 
 5 /**
 6  * 獲得某個類型的消息數量
 7  */
 8 function getType(){
 9     var lis = document.getElementById("type").getElementsByTagName("li");
10     var msgType = "";
11     for(var i=0; i<lis.length; i++){
12         msgType = lis[i].innerText;
13     }
14     $.ajax({
15         type:"POST",
16         url:"PullMsgServlet",
17         dataType:'json',
18         processData:false,
19         data: {
20             operateType: "showCountByType"
21         },
22         success:function(data){
23             var result = data.result;
24             var type = "";
25             if(result){
26                 for(var i=0; i<result.type.length; i++){
27                     type = result.type[i];
28                     if(type == "訂單"){
29                         $("#order").html(result.typeNum[i]);
30                     }else if(type == "上下架"){
31                         $("#shelf").html(result.typeNum[i]);
32                     }else if(type == "審覈"){
33                         $("#review").html(result.typeNum[i]);
34                     }
35                 }
36             }
37         },
38         error: function () {
39             // alert("error...");
40         }
41     });
42 }

這樣前端每隔5秒就輪詢一次PullMsgServlet,查詢數據庫裏是否有未讀的消息,若是有,就顯示在前端頁面上。這樣,一個最簡單的消息推送以及顯示功能就有了,只是我尚未寫前端歷史列表的查看,等之後寫了再更新。。。。url

相關文章
相關標籤/搜索