我想要的是获取数据库更新。
即如果数据库发生任何更改或插入新记录,它应该通知用户。
直到知道我实现的是使用 jQuery,如下所示
$(document).ready(function() {
var updateInterval = setInterval(function() {
$('#chat').load('Db.jsp?elect=<%=emesg%>');
},1000);
});
它对我来说效果很好,但我的老师告诉我,这不是推荐使用 comet 或长轮询技术的好方法。
任何人都可以给我一些使用 cometd 或长轮询获取数据库更新的例子吗 在 servlet/jsp 中?我正在使用 Tomcat 作为服务器。
最佳答案
只是在黑暗中拍摄,因为我不知道你的确切环境......你可以让数据库触发器在每次提交行时触发对 servlet 的调用,然后运行一些看起来像以下:
获取对于我们要更新的页面处于 Activity 状态的脚本 session 。这消除了检查站点上运行的每个反向 ajax 脚本 session 的需要。一旦我们有了脚本 session ,我们就可以使用第二个代码块来获取一些数据并更新客户端的表。第二个代码部分所做的就是将 javascript 发送到客户端,以通过打开的反向 ajax 连接执行。
String page = ServerContextFactory.get().getContextPath() + "/reverseajax/clock.html";
Browser.withPage(page, new Runnable() {
public void run() {
Util.setValue("clockDisplay", output);
}
});
// Creates a new Person bean.
Person person = new Person(true);
// Creates a multi-dimensional array, containing a row and the rows column data.
String[][] data = {
{person.getId(), person.getName(), person.getAddress(), person.getAge()+"", person.isSuperhero()+""}
};
// Call DWR's util which adds rows into a table. peopleTable is the id of the tbody and
// data conta
ins the row/column data.
Util.addRows("peopleTable", data);
请注意,以上两段代码都是直接从文档示例中提取的@ http://directwebremoting.org/dwr-demo/ .这些只是反向 ajax 如何向客户端发送数据的简单示例,但您的具体情况似乎更取决于您如何接收通知,而不是如何更新客户端屏幕。
如果没有某种类型的数据库通知到 java 代码,我认为您将不得不按设定的时间间隔轮询系统。即使在轮询时,您也可以通过在轮询数据库获取信息之前验证页面是否存在 Activity 的反向 ajax 脚本 session 来提高系统效率。
关于java - 使用 servlet 或 jsp 获取数据库更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19899729/