我将实现一个新闻提要通知系统,我将在网页上显示新项目。像这样:http://jsfiddle.net/8ND53/ .
我将调用一个 Servlet(例如每 5 秒一次)来获取更新,并且该 Servlet 将以 json 格式返回项目。这看起来很简单,但是我如何在服务器端管理这一切?
我的想法是:
- 我必须跟踪发送给用户的最后一个项目(按日期),以便下次我可以从数据库中获取新项目。
他们有做此类事情的标准方法吗?
最佳答案
只是一个想法!
我假设您从包含提要的数据库表中创建了一个 bean、dao 和服务层。
<小时/>在加载检索提要的页面时,从 java 函数获取所有提要,然后用提要填充您的 div。
从 Feed 容器中获取 Feed 计数。现在通过 jQuery $.post
传递计数,然后传递到您的 servlet。为此,请执行以下操作:
例如:
//Find divs inside the parent div that will contain your feeds
function getCount(){
return $('#feedContainer').children().find('div').size().toString();
}
//Don't forget to pass it to your jQuery post like this
//(Please, continue reading to understand where to put this)
$.post('/servlet', count:getCount(), function(data){ //manage your new feeds });
您的 servlet 将收到如下内容:
例如:
String count = request.getParameter("count");
现在您已经有了计数、验证或只是解析为Integer
,然后在 java 中创建一个列表。我想您有一个函数可以从数据库获取所有提要。
例如:
//Parse it as integer
int feedCountFromUI = Integer.valueOf(count);
//Do a list and call your function to get all feeds from DB.
MyService myService = new MyService();
List<MyBean> feeds = myService.getAll();
//JSON variable
JSONObject result = new JSONObject();
//Fill your JSON variable
for(MyBean mb : feeds) {
//Build a json with your feeds and fill result
}
假设现在您的 servlet 中有一个名为 result
的 JSON 对象变量,并且您的 Feed 值填充在上面完成的 for
中。现在从声明为 feeds
的列表中获取计数(也从上面开始)。
int feedCountFromDB = feeds.size();
您现在即将完成,请比较 2 个计数。如果 feedCountFromDB
大于 feedCountFromUI
,则意味着有新的 Feed 需要加载。
if(feedCountFromDB > feedCountFromUI){
//Send your json variable (result) to your jquery post callback
out.println(result);
} else {
//Means there is nothing new, print 0
out.println(0);
}
此时,您只需每 5 秒用最后一次 Feed 填充 Feed 容器,如下所示:
(此时您还可以从 jsFiddle 添加 jQuery 动画函数)
setInterval(function(){
$.post('/servlet', count:getCount(), function(data){
//If data has feeds (it's not 0)
if(data != 0) {
var lastFeed = data[data.length - 1];
$('#feedContainer').append('<div>' + lastFeed.title + '<br/>' + lastFeed.description + '</div>';
}
});
}, 5000);
这将始终检查您的网络界面中的计数,然后每 5 秒将其与数据库中的计数进行比较,以获取新的 Feed。
希望这有帮助:-)
关于java - 在 Java EE 和 jquery 中实现新闻提要系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11586125/