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>

测试

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

在这里插入图片描述

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

在这里插入图片描述

我们回到pollingPage.jsp页面

在这里插入图片描述

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

在这里插入图片描述

再看pollingPage.jsp

在这里插入图片描述

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

  • 7
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值