用javaee和jquery实现新闻提要系统
我将实现一个新闻提要通知系统,在那里我将在我的网页上显示新项目。像这样: 我将每隔5秒调用一个Servlet来获取更新,Servlet将以json格式返回项目。这看起来很简单,但是我如何在服务器端管理这些呢 我认为:用javaee和jquery实现新闻提要系统,java,jquery,feed,Java,Jquery,Feed,我将实现一个新闻提要通知系统,在那里我将在我的网页上显示新项目。像这样: 我将每隔5秒调用一个Servlet来获取更新,Servlet将以json格式返回项目。这看起来很简单,但是我如何在服务器端管理这些呢 我认为: 我必须跟踪发送给用户的最后一个项目(按日期),以便下次我可以从数据库获取新项目 他们做这些事情有什么标准的方法吗?只是个想法 我将假设您从包含提要的db表中创建bean、dao和服务层 当将检索提要的页面加载时,首先从java函数获取所有提要,然后用提要填充div 从提要容器
- 我必须跟踪发送给用户的最后一个项目(按日期),以便下次我可以从数据库获取新项目李>
当将检索提要的页面加载时,首先从java函数获取所有提要,然后用提要填充div 从提要容器中获取提要计数。现在通过jQuery
$传递计数。post
然后传递到servlet。要实现此目标,请执行以下操作:
e、 g:
您的servlet将收到如下内容:
e、 g:
现在您已经有了计数,请验证或只是将其解析为一个整数
,然后用java编写一个列表。我想您有一个函数可以从DB获取所有提要
e、 g:
您现在接近完成,比较两个计数。如果feedCountFromDB
大于feedCountFromUI
,则表示要加载新的提要
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秒用最后一次提要填充提要容器,如下所示:
(此时还可以从JSFIDLE添加jQuery动画函数)
setInterval(函数(){
$.post('/servlet',count:getCount(),函数(数据){
//如果数据有提要(不是0)
如果(数据!=0){
var lastFeed=data[data.length-1];
$(“#feedContainer”).append(“+lastFeed.title+”
“+lastFeed.description+”;
}
});
}, 5000);
这将始终检查来自web界面的计数,然后每5秒将其与来自DB的计数进行比较,以获得新的提要
希望这有帮助:-)只是个主意
我将假设您从包含提要的db表中创建bean、dao和服务层
当将检索提要的页面加载时,首先从java函数获取所有提要,然后用提要填充div 从提要容器中获取提要计数。现在通过jQuery
$传递计数。post
然后传递到servlet。要实现此目标,请执行以下操作:
e、 g:
您的servlet将收到如下内容:
e、 g:
现在您已经有了计数,请验证或只是将其解析为一个整数
,然后用java编写一个列表。我想您有一个函数可以从DB获取所有提要
e、 g:
您现在接近完成,比较两个计数。如果feedCountFromDB
大于feedCountFromUI
,则表示要加载新的提要
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秒用最后一次提要填充提要容器,如下所示:
(此时还可以从JSFIDLE添加jQuery动画函数)
setInterval(函数(){
$.post('/servlet',count:getCount(),函数(数据){
//如果数据有提要(不是0)
如果(数据!=0){
var lastFeed=data[data.length-1];
$(“#feedContainer”).append(“+lastFeed.title+”
“+lastFeed.description+”;
}
});
}, 5000);
这将始终检查来自web界面的计数,然后每5秒将其与来自DB的计数进行比较,以获得新的提要
希望这有帮助:-)
//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
}
int feedCountFromDB = feeds.size();
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);
}
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);