Following is the code snipp开发者_运维百科et which is used to get the online roster from gtalk
if (status == true) {
Roster roster =connection.getRoster();
Collection<RosterEntry> entries =roster.getEntries();
System.out.println(roster.getEntryCount());
int count1 = 0;
int count2 = 0;
for(RosterEntry r:entries)
{
Presence presence = roster.getPresence(r.getUser());
if(presence.getType() == Presence.Type.unavailable)
{
// System.out.println(user + "is offline");
count1++;
}
else
{
String rosterNamesJson = new Gson().toJson(r.getName());
String rosterUserJson =new Gson().toJson(r.getUser());
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
//array of 2 elements
String rosterInfoJson=response.getWriter().write("rosterNamesJson"+"rosterUserJson"]);
response.sendRedirect("Roster.jsp");
//System.out.println(name+user + "is online");
count2++;
}
}
}
Now in my jsp page I want to populate the roster as name and his jid i.e xoxoxo:xoxoxo@gmail.com jjj:jjj@gmail.com and so on. How do I achieve this?
Should I construct Json element i.e
users
{
name:
jid:
}
and then write function in my JSP page to access the data?
The function I have is
$(function() {
$.getJSON('xxxServlet', function(rosterInfoJson) {
var $ul = $('<ul>').appendTo($('#roster'));
$.each(rosterInfoJson, function(index, rosterEntry) {
$('<li>').text(rosterEntry.user).appendTo($ul);
});
});
});
yes. you should construct your JSON as
users
{
name:
jid:
}
You may want to define a Java class mapping the JSON.
public class MyUser{
public String name;
public String jid;
public MyUser(String name, String jid){
this.name=name;
this.jid=jid;
}
}
And then, just append all the online uses to a List or something
ArrayList<MyUser> mul = new ArrayList<MyUser>();
if (status == true) {
...
...
for(RosterEntry r:entries) {
if(...){
...
}
else
{
mul.add(new MyUser(r.getName(),r.getUser());
count2++;
}
}
response.setContentType("application/json");
response.getWriter().write(new Gson().toJSON(mul));
response.setCharacterEncoding("utf-8");
response.sendRedirect("Roster.jsp");
In your JavaScript
...
$('<li>').text(rosterEntry.name +":"+rosterEntry.jid).appendTo($ul);
...
精彩评论