webSocket 任务数更新提醒 jeecg

本文介绍如何使用WebSocket技术实现在用户界面实时更新数据库中待办任务的数量,并提供了具体的前端JSP页面代码及后端Java实现方式。此外,还展示了通过AJAX轮询的方式作为补充方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.效果(当数据库变化时,更新任务数)

2.页面

3. jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="org.jeecgframework.web.system.pojo.base.TSUser" %>
<%@include file="/context/mytags.jsp"%>
<%@ page import="java.sql.*" %>
<!--  获取登录用户信息  -->
<% TSUser u = (TSUser) session.getAttribute("LOCAL_CLINET_USER"); System.out.println(u.getUserName()+";id="+u.getId()+";"+u.getCurrentDepart().getId());%> 
<!--  【首页提醒】我的任务 -->
<li class="dropdown hidden-xs">
      <a href="javascript:addOneTab('我的任务', 'tSTaskController.do?goTaskListTab', 'default');">                             	<i class="fa fa-bell" style="color:#EE6B6B"></i> 待办(<span id="view"></span>)</a> 
</li>  

3.1 js

 

<script type="text/javascript"> 
//先检验能不能运行起来,能不能连上,自动推送数据,先不做数据显示 
//客户端就会与服务器进行连接 
//ws://localhost:8080/jeecg/websocket/1/2 ; (1,2 是传递的参数) 
 var webSocket = new WebSocket("ws://localhost:8080/jeecg/websocket/<%=u.getId() %>/<%=u.getCurrentDepart().getId() %>");   
//这里只是调试用 
//连接失败时回调        
webSocket.onerror = function (event) { 
       	makeDataOnWeb("0");   
         //makeDataOnWeb("error"); 
       };        
//这里只是调试用        
//连接成功时回调         
 webSocket.onopen = function (event) {             
makeDataOnWeb("0");            
//console.log("conn success");             
//makeDataOnWeb("conn success");        
};        
webSocket.onmessage = function (event) {            
makeDataOnWeb(event.data);        
};        
//这里只是调试用        
webSocket.onclose = function (event) {        	
// makeDataOnWeb("0");           
makeDataOnWeb("conn close");        
};        
function makeDataOnWeb(data) {
//alert("data="+data);        	           
document.getElementById("view").innerHTML=data;       
 };    
</script>

3.2 后台代码

 

 

import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;
import org.hibernate.annotations.Where;


@ServerEndpoint("/websocket/{uId}/{dpId}")
public class websocket {
private static final Logger logger = Logger.getLogger(websocket.class);
private int currentIndex;
private SystemService systemService; //调取的其他类
private CommonService commonService; //调取的其他类
private String uid;
private String dpId;
@OnOpen
public  void onOpen(@PathParam("uId") String uId,@PathParam("dpId") String dpId,Session session) {
		 //调取的其他类
		ApplicationContext ctx = ApplicationContextUtil.getContext();
	    if (ctx.containsBean("systemService")) {
	      this.systemService = ((SystemService)ctx.getBean("systemService"));
	    }
	    if (ctx.containsBean("commonService")) {
		  this.commonService = ((CommonService)ctx.getBean("commonService"));
		}
	    while (true) {
	    	currentIndex=0;
		  //这之间写业务代码 查数据库.........
		//   
			 
		System.out.println( "待办任务="+currentIndex);
             try {
			ession.getBasicRemote().sendText(String.valueOf(currentIndex));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
             try {
               //一秒刷新一次
               Thread.sleep(1000*60);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
	    }
	      
}
 
	
	@OnClose
	  public void onClose()
	  {
	    logger.info("有一连接关闭! "  );
	  }
	  @OnError
	  public void onError(Session session, Throwable error)
	  {
	    logger.info("发生错误");
	    error.printStackTrace();
	  }

2,ajax 实现

 

  //alert("//加载消息");

 //alert("//加载消息");
	function getTaskCount(){
//     	待办  加载消息
 	   var url = "tSTaskController.do?getTaskMessageCount";
 	   $.ajax({
 	       url:url,
 	       type:"GET",
 	       dataType:"JSON",
 	       async: false,
 	       success:function(data){
 	           if(data.success){
 	        	   var messageCount = data.obj;
 	        	  //alert("待办  加载消息");
  	        	   $("#taskCount").html(messageCount);
 	           }
 	        }
 	     });  
    }
	// 重复执行某个方法 
	 window.setInterval("getTaskCount()",1000*60*5); 
	// 去掉定时器的方法 
	window.clearInterval(t1);
    $(document).ready(function(){
//------------------------------------------------------------ 
//     	alert("待办  加载消息");
//     	待办  加载消息
        getTaskCount();
 
 });  
    		
 

//------------------------------------------------------------   

  //------------------------------------------------------------   

 

 

 

/**
	 * 首页取得任务的消息
	 * 
	 * @param user
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "getTaskMessageCount")
	@ResponseBody
	public AjaxJson getNoticeList(HttpServletRequest req) {
		Integer cont = 0;
		AjaxJson j = new AjaxJson();
		j.setObj(0);
		if(userRoleId.equals("402881e75f1f2471015f206d63e60015")){
			 String qsql = "select t.c_taskid,t.c_taskname,t.c_assignee,t.c_workflowid,t.c_instanceid,t.c_createtime,t.c_taskstate,t.c_resourceid,r.c_spreadsheetid,r.c_otherparams  from t_ext_workflow_task t LEFT JOIN  t_ext_workflow_resource r on t.c_resourceid  =r.c_resourceid where  t.c_taskstate='unfinished'  AND t.c_assignee like '%"+ userRoleId + "%' ";
			  List<Map<String, Object>> taskList = DynamicDBUtil.findList("SAP_DB", qsql);
			  if (null != taskList && !taskList.isEmpty()) {
					cont += taskList.size();
			  } 
		 }
		j.setObj(cont);
		return j;
	}	  
同时也参考文章 http://blog.csdn.net/Nougats/article/details/75305370 
	http://blog.csdn.net/u014175572/article/details/46693121
http://blog.csdn.net/u014175572/article/details/46693121

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值