java - 在 Java EE 和 jquery 中实现新闻提要系统

标签 java jquery feed

我将实现一个新闻提要通知系统,我将在网页上显示新项目。像这样: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/

相关文章:

java - SVNKIT doExport 方法 - 什么是 pegRevision?

java - 使用 JFrame 和 JPanel 的简单 Java 动画

javascript - SlickGrid 不能删除添加的行,只能删除现有的行。我究竟做错了什么?

javascript - 加入重复项并添加数量

php - 将 Feedly 特色图片类 "webfeedsFeaturedVisual"添加到 Wordpress 中的特色图片

ios - 是否可以使用 Django 评论构建事件源?

java - 如何使用instanceof函数打印继承中的某个类别?

java - 是否可以使用 h :outputLink? 对带有 # anchor 的 URL 进行组件编码

javascript - jQuery:获取未检查表行的ID

c# - 可用于 ASP.NET Core 的 RSS/Atom 提要阅读器