使用dwr实现后台消息推送功能

前端之家收集整理的这篇文章主要介绍了使用dwr实现后台消息推送功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

大多数网站都有站内信,未读消息,今日要闻等消息的推送功能,就拿本站来说打开今日第一次csdn首页,立马会在右下角出现一个弹出窗口,就是下图这样的,你一定见过的:

很多无良网站都会有各种各样的浮动层,飘来飘去的很烦人,一不小心点到了,弹出令人更烦的无良广告。csdn当然不是无良网站,尽管有弹出层,但没有乱飞,并且也不是以广告为目的的,这样大家就不会抵制和排斥了。作为一个web开发者,我曾经略微思考过,如何实现这种功能呢?什么触发事件,如何响应的呢?正好用户要求加这么一个消息提醒功能,就借此深入研究了一下。

至于消息推送的功能,网上给的建议是使用dwr的消息推送,由于平时我们所做的操作都是基于请求--》处理--》响应模式的,那么没有请求直接响应可以吗?http协议似乎对此支持的并不好。我们常见的消息推送,短信、聊天工具、邮件,这些都是需要服务器来支持的,那么在javaEE web开发中,能不能实现无请求的消息推送呢?

遍差网上资料,发现有几个方案可以支持:1,dwr3实现;2,comet4j实现。这两个技术之前都没怎么接触过,如何选择呢?dwr技术毕竟更为成熟,网上的资料更多,可行性更强些。毕竟身边的人会的不多,客户那边要求挺紧,必须兼顾到各种情况。
客户要求是:当后台发布了一篇内容(报道、公告、新闻通知或其他)之后,前台登录用户首页上可以看到消息提醒。
那么我就把问题分成几步来解决
1,后台发布消息的时候要做登记,不能直接广播,要指定推送目标,那么就要做一个内容和接收人的对应关系,后台发布内容时作登记。
2,用户进入首页的时候,检测是否存在符合推送条件(有文章且允许)。
3,查出所有用户的未读信息列表,弹出提醒窗口。
4,用户点击某条信息后,把状态为设为已读。
这么几个步骤,就可以解决问题了。
首先说第一步:这一步似乎是最简单的,但却是最不容易思考的地方,由于项目本身对用户的管理是通过组来实现,在发布内容的时候也是列出的所有的组供用户选择,让用户勾选。我们可以在这个时候“趁火打劫”,在保存组的时候,不妨把组里面的用户也一一取到,放入我们的操作表中,操作表结构如下:


仅有两列,一列是内容id,一列是user_id,本想再弄一个标志位,后来觉得用户把信息读取一条信息之后就可以把本条记录直接删除了,留着也没有实际意义。

后台代码(hibernate实现):

  1. // 保存浏览会员组
  2. if (viewGroupIds != null && viewGroupIds.length > 0) {
  3. for (Integer gid : viewGroupIds) {
  4. bean.addToGroups(cmsGroupMng.findById(gid));
  5. }
  6. }
  7. // 保存浏览会员
  8. String addToMsgAlert = request.getParameter("addToMsgAlert");
  9. //前台选择了该消息,要做提醒
  10. if(addToMsgAlert!=null&&Boolean.parseBoolean(addToMsgAlert)){
  11. List<Integer> groupList = this.getUserViewGroupIds(bean);
  12. Integer[] user_viewGroupIds = null;
  13. if(groupList!=null&&groupList.size()>0){
  14. user_viewGroupIds = groupList.toArray(new Integer[0]);
  15. }
  16. if (user_viewGroupIds != null && user_viewGroupIds.length > 0) {
  17. List<CmsUser> userList = this.getUserListByGroupIds(user_viewGroupIds==null?null:Arrays.asList(user_viewGroupIds));
  18. for (CmsUser cmsUser : userList) {
  19. bean.addToUsers(cmsUser);
  20. }
  21. }
  22. }

  1. @SuppressWarnings("unchecked")
  2. private List<CmsUser> getUserListByGroupIds(List<Integer> groupList){
  3. List<CmsUser> userList = new ArrayList<CmsUser>();
  4. if(groupList==null){
  5. for (CmsGroup group : cmsGroupMng.getList()) {
  6. userList.addAll(this.cmsUserMng.getList(null,null,group.getId(),null));
  7. }
  8. }else{
  9. for (Integer groupId : groupList) {
  10. userList.addAll(this.cmsUserMng.getList(null,groupId,null));
  11. }
  12. }
  13. return userList;
  14. }

hibernate配置文件
  1. <set name="viewUsers" table="jc_content_user_flag">
  2. <cache usage="read-write"/>
  3. <key column="content_id"/>
  4. <many-to-many column="user_id" class="CmsUser"/>
  5. </set>

第二、三步:消息侦测和弹出窗口:

前台代码

  1.  
  1. <script type="text/javascript" src="../dwr/engine.js"></script>
  2. <script type="text/javascript" src="../dwr/util.js"></script>
  3. <script type="text/javascript" src="../dwr/interface/pushMsg.js"></script>
  1. <div style="display: block;" id="_popup_msg_container">
  1. <div class="im_popupWindow" id="im_popupWindow_miniMsg" wistate="max"
  2. style="display: block; height: 244px;">
  3. <h6 class="wi_draggable">
  4. <a href="#" onclick="_message_tips_pop('down');return false;">
  5. <img src="/${res}/jlczmh/alert/x.gif" class="founctionpic3" alt="colse" />
  6. </a>
  7. </h6>
  8. <div class="wi_content" id="im_popupWindow_miniMsgContent">
  9. <div class="kuai">
  10. <div class="tuijian">
  11. <div id="alertTitle"><h3>您有<span id="msgNum"></span>条消息未读</h3></div>
  12. <div id="msgList">
  13. </div>
  14. <div id="queryAll">
  15. <span style="float: left;"><span style="margin-top: 2px;">不在提醒</span><input type="checkBox" onclick="notAlert();" id=""/></span>
  16. <a id="queryAll_a" onclick="queryAllMsg();return false;" href="javascript:void(0);">
  17. </a>
  18. </div>
  19. </div>
  20. </div>
  21. </div>
  22. </div>
  23. </div>
  24. <SCRIPT language=JavaScript type=text/javascript>
  25.  
  26. function notAlert(){
  27. _message_tips_pop('down');
  28. var userId = $("#userId").val();
  29. pushMsg.alertOrNot(userId);
  30. }
  31. function _message_node(id) {
  32. return document.getElementById(id)
  33. }
  34. function _message_child(p,c) {
  35. var pdom = _message_node(p);
  36. var nodes = pdom.childNodes;
  37. var cdom = false;
  38. for (var i = 0; i < nodes.length; i++) {
  39. if (nodes[i].tagName == c.toUpperCase()) {
  40. cdom = nodes[i];
  41. break
  42. }
  43. }
  44. return cdom
  45. }
  46. function _message_tips_pop(act) {
  47. var MsgPop = _message_child("_popup_msg_container","div");
  48. var MsgPop = null == MsgPop ? document.getElementById("_popup_msg_container") : MsgPop;
  49. var popH = parseInt(MsgPop.clientHeight);
  50. if (act == "up") {
  51. MsgPop.style.display = "block";
  52. show = setInterval("_message_changeH('up')",2)
  53. }
  54. if (act == "down") {
  55. hide = setInterval("_message_changeH('down')",2)
  56. }
  57. }
  58. function _message_changeH(str) {
  59. var MsgPop = _message_child("_popup_msg_container","div");
  60. var MsgPop = null == MsgPop ? document.getElementById("_popup_msg_container") : MsgPop;
  61. var popH = parseInt(MsgPop.clientHeight);
  62. if (str == "up") {
  63. if (popH <= 240) {
  64. MsgPop.style.height = (popH + 4).toString() + "px"
  65. } else {
  66. clearInterval(show)
  67. }
  68. }
  69. if (str == "down") {
  70. if (popH >= 8) {
  71. MsgPop.style.height = (popH - 4).toString() + "px"
  72. } else {
  73. MsgPop.style.display = "none";
  74. clearInterval(hide)
  75. }
  76. }
  77. }
  78. var server = window.location.host;
  79. if (server.indexOf("local") < 0) {
  80. server = "www.jb51.net"
  81. }
  82. var p = "1=1";
  83. if (window.location.search.indexOf("?") > -1) {
  84. var p = window.location.search.substring(1)
  85. }
  86. var MsgPop = _message_child("_popup_msg_container","div");
  87. if (MsgPop) {
  88. MsgPop.style.display = "none";
  89. MsgPop.style.height = "0px"
  90. }
  91. function click_push(){
  92. pushMsg2();//先加载一次
  93. //var time = 5000; //5*10秒
  94. //window.setInterval('pushMsg()',time);
  95. }
  96. pushMsg2 = function(){
  97. var userId = $("#userId").val();
  98. if(userId!=""&&userId!=null&&userId!=undefined){
  99. dwr.engine.setAsync(false);//设置同步
  100. pushMsg.getMsg(userId,function(data){
  101. var jsonData = eval("("+data+")");
  102. //alert(jsonData);
  103. var len = jsonData.length;
  104. if(len>0){
  105. //alert("您有"+len+"条新内容未读");
  106. var max = 8;
  107. var titleLen = 13;
  108. var html = "<ul>"
  109. for(var i = 0;i < (len>max?max:len);i++){
  110. var title = jsonData[i].title;
  111. if(title.length>titleLen)
  112. title = title.substring(0,titleLen)+"...";
  113. var addr = "/"+jsonData[i].path+"/"+jsonData[i].id+".jhtml";
  114. html+="<li><a href='"+addr+"' onclick='readMsg2("+jsonData[i].id+","+userId+");' title='"+jsonData[i].title+"'>["+jsonData[i].date+"] "+title+"</a></li>";
  115. }
  116. html+="</ul>";
  117. $("#msgList").html(html);
  118. $("#msgNum").html(len);
  119. if(len>max){
  120. $("#queryAll_a").html("查看所有未读信息");
  121. }
  122. _message_tips_pop("up");
  123. }
  124. });
  125. dwr.engine.setAsync(true);//设置异步
  126. }
  127. }
  128. readMsg2 = function(contentId,userId){
  129. dwr.engine.setAsync(false);//设置同步
  130. pushMsg.readMsg(contentId,function(data){
  131. //alert(data);
  132. });
  133. dwr.engine.setAsync(true);//设置异步
  134. }
  135. //setTimeout("_message_tips_pop('up')",100);
  136. queryAllMsg = function(){
  137. document.location.href='/content/getAllUnReadMsg.jspx';
  138. }
  139. </SCRIPT>
  140. <script type="text/javascript">
  141. $(function(){
  142. click_push();
  143. });
  144. </script>

dwr配置文件
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE
  3. dwr
  4. PUBLIC
  5. "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
  6. "http://getahead.org/dwr/dwr30.dtd">
  7. <dwr>
  8. <allow>
  9. <create
  10. creator="spring"
  11. javascript="pushMsg">
  12. <param name="beanName" value="pushMsg"/>
  13. </create>
  14. </allow>
  15. </dwr>
creator=‘spring’是指需要的bean是使用spring配置的,名字(id)叫做 pushMsg。

java代码
  1. package cn.com.dwr;
  2.  
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import java.util.List;
  6. import java.util.Map;
  7.  
  8.  
  9. import org.json.JSONArray;
  10. import org.json.JSONException;
  11. import org.json.JSONObject;
  12. import org.springframework.jdbc.core.JdbcTemplate;
  13.  
  14. public class PushMsg {
  15.  
  16. private JdbcTemplate jdbcTemplate;
  17. private String userId;
  18. public JdbcTemplate getJdbcTemplate() {
  19. return jdbcTemplate;
  20. }
  21.  
  22. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  23. this.jdbcTemplate = jdbcTemplate;
  24. }
  25. /**
  26. * 根据userId获取所有的未读信息
  27. * @param userId
  28. * @return
  29. * @throws JSONException
  30. */
  31. @SuppressWarnings("unchecked")
  32. public String getMsg(String userId) throws JSONException {
  33. JSONArray msgArr = new JSONArray();
  34. JSONObject o;
  35. Map<String,Integer> contentIdMap = null;
  36. String path = "";
  37. Integer contentId = null;
  38. String title = "";
  39. String releaseDate = "";
  40. this.userId = userId;
  41. List contentIdList = jdbcTemplate
  42. .queryForList("SELECT content_id FROM jc_content_user_flag jf,jc_user ju where jf.user_id=ju.user_id and ju.alertornot= '0' and ju.user_id = "
  43. + Integer.parseInt(userId)+" order by content_id desc");
  44. for (int i = 0; i < contentIdList.size(); i++) {
  45. o = new JSONObject();
  46. contentIdMap = (Map<String,Integer>) contentIdList.get(i);
  47. contentId = contentIdMap.get("content_id");
  48. path = getPathByContentId(contentId);
  49. Map<String,Object> map = getTitleAndTimeByContentId(contentId);
  50. title = (String) map.get("title");
  51. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  52. releaseDate = sdf.format((Date)map.get("release_date"));
  53. o.put("id",contentId);
  54. o.put("path",path);
  55. o.put("title",title);
  56. o.put("date",releaseDate);
  57. msgArr.put(o);
  58. }
  59. return msgArr.toString();// contentIds.toString();
  60. }
  61. /**
  62. * 阅读过一条信息,将此信息从表中删除
  63. * @param contentId
  64. * @return
  65. */
  66. public String readMsg(String contentId){
  67. String result = "false";
  68. try {
  69. jdbcTemplate.update("DELETE FROM jc_content_user_flag WHERE content_id = "+Integer.parseInt(contentId)+" and user_id="+Integer.parseInt(userId));
  70. result = "true";
  71. } catch (Exception e) {
  72. e.printStackTrace();
  73. }
  74. return result;
  75. }
  76. /**
  77. * 设置用户不再提醒消息
  78. * @param userId
  79. */
  80. public void alertOrNot(String userId){
  81. try{
  82. jdbcTemplate.update("update jc_user set alertornot = '1' where user_id="+userId);
  83. System.out.println(userId);
  84. }catch (Exception e) {
  85. e.printStackTrace();
  86. }
  87. }
  88. /**
  89. * 设置用户提醒消息
  90. * @param userId
  91. */
  92. public void alert(String userId){
  93. try{
  94. jdbcTemplate.update("update jc_user set alertornot = '0' where user_id="+userId);
  95. System.out.println(userId);
  96. }catch (Exception e) {
  97. e.printStackTrace();
  98. }
  99. }
  100. private Map<String,Object> getTitleAndTimeByContentId(Integer contentId) {
  101. Map<String,Object> map = jdbcTemplate
  102. .queryForMap("select title,release_date from jc_content_ext where content_id="
  103. + contentId);
  104. return map;
  105. }
  106.  
  107. private String getPathByContentId(Integer contentId) {
  108. Map<String,Object> map = jdbcTemplate
  109. .queryForMap("select channel_path from jc_channel cha,jc_content con where cha.channel_id=con.channel_id and con.content_id="
  110. + contentId);
  111. return (String) map.get("channel_path");
  112. }
  113. }

其中采用了jdbc模板来操作,并没有使用和系统相同的hibernate,一来由于业务量小,不用费事处理复杂配置文件。二来,对这种形式的查询我更为熟悉。

效果


如果点击不在提醒,那么用户表中的标志位就起了作用,这里没有设解锁功能,一旦设置成了不再提醒,想恢复就需要修改数据库。这是功能不够完善,用户暂时没提这个功能,也就乐得不改动。

后台发布的时候:


红框是可浏览的会员组选择,绿框表示本条消息是否作为提醒的消息,有了这两个参数,操作起来就变得灵活多了。

如果未读消息过多,那么弹出层右下角会出现“查看所有未读消息”,这样就能看全了。

总结:本方案并没有彻底实现消息推送功能,依然是前台刷新,后台响应这种模式,消息的推送不是即时的。但考虑到用户最常去的页面就是首页,session超时也设为10分钟,本项目发布的消息也不是十分紧急,考虑上述情况,无需采用即时推送,如果用户经常在线,那么最多延迟十分钟,如果用户不经常在线,即时推送也没有意义。

本方案并没有完全发挥dwr消息推送的优势,这样的推送形式ajax似乎也办得到,效率未必比它差,有时间可以换一种形式来实现。

猜你在找的Ajax相关文章