在Java EE和jquery中实现新闻源系统

时间:2012-07-20 19:53:47

标签: java jquery feed

我将实施新闻Feed通知系统,我将在我的网页上显示新项目。像这样:http://jsfiddle.net/8ND53/

我将调用Servlet说每5秒获取更新,servlet将以json格式返回项目。这似乎很简单,但我如何在服务器端管理所有这些?

我的想法是:

  • 我必须跟踪发送给用户的最后一项(按日期),以便下次我可以从数据库中获取新项目。

他们做这些事情的标准方式是什么?

1 个答案:

答案 0 :(得分:1)

只是一个想法!

我假设您从db表中创建包含feed的bean,dao和service层。


首次检索Feed的网页加载时,从java函数中获取所有Feed,然后使用Feed填充div。

从Feed容器中获取Feed计数。现在通过jQuery $.post传递计数,然后传递给你的servlet。要实现此目的,请执行以下操作:

e.g:

//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将收到以下内容:

e.g:

String count = request.getParameter("count");

现在你有了计数,验证或只是解析为Integer,然后在java中做一个列表。我想你有一个功能来从DB获取你的所有信息。

e.g:

//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 animate函数)

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。

希望这会有所帮助: - )

相关问题