Fork me on GitHub

Programming Design Notes

使用 Java 開發 Facebook Web App - 3

| Comments

上一回: 使用 Java 開發 Facebook Web App - 2

今次我們將 IndexServlet 修改一下,不再顯示 Hello World,改為顯示用戶朋友的資料,這個功能應該是非常常用的。

首先將 IndexServlet 的 doGet 清空,並加入以下程式碼:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
FacebookXmlRestClient xmlClient = FacebookFilter.getUserClient(session);
}

首先先取得用戶的 FacebookXmlRestClient,利用 FacebookXmlRestClient 提供的方法去存取用戶資料。而我比較喜歡用 FacebookJaxbRestClient,FacebookJaxbRestClient 可以將 Facebook 回傳的 XML 自動轉為 Java Object。

對這種技術有興趣的朋友可以參考以下網址。
Java Architecture for XML Binding (JAXB): http://java.sun.com/developer/technicalArticles/WebServices/jaxb/

那怎麼將 FacebookXmlRestClient 轉為使用 FacebookJaxbRestClient? 轉換方法非常簡單,加入以下程式碼:
FacebookJaxbRestClient jaxbClient = new FacebookJaxbRestClient(
xmlClient.getApiKey(), xmlClient.getSecret(), xmlClient
.getCacheSessionKey());

設定好 Rest Client 後可以開始進入正題,存取朋友資料前要先知道朋友的 ID 才行,以下程式碼是拿取用戶所有朋友 ID 後再將 ID 放到 List 內。
try {

// Get user friend list
FriendsGetResponse friendResponse = (FriendsGetResponse) jaxbClient
.friends_get(jaxbClient.getCacheUserId());
List<Long> friends = friendResponse.getUid();
} catch (FacebookException e) {
e.printStackTrace();
}

現在有一個 List 裝了所有的 ID,那便可以批次地拿到相對應 ID 的用戶資料。在這裡我只選擇拿取用戶 ID,名稱,性別和生日日期。
// Get friend info
UsersGetInfoResponse userResponse = jaxbClient.users_getInfo(
friends, EnumSet.of(ProfileField.UID, ProfileField.NAME, ProfileField.SEX,
ProfileField.BIRTHDAY));
List<User> friendsInfo = userResponse.getUser();

ProfileField API: ProfileField

現在我們已經拿到用戶資料了。再來便是將資料傳給 JSP,讓 JSP 顯示出來。
Map<String, Object> model = new HashMap<String, Object>();
model.put("friendsInfo", friendsInfo);
request.setAttribute("model", model);

RequestDispatcher dispatcher = request
.getRequestDispatcher("/WEB-INF/pages/index.jsp");

dispatcher.forward(request, response);

完整的 IndexServlet:
package com.blogspot.lawpronotes.servlet;

import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.blogspot.lawpronotes.filter.FacebookFilter;
import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJaxbRestClient;
import com.google.code.facebookapi.FacebookXmlRestClient;
import com.google.code.facebookapi.ProfileField;
import com.google.code.facebookapi.schema.FriendsGetResponse;
import com.google.code.facebookapi.schema.User;
import com.google.code.facebookapi.schema.UsersGetInfoResponse;

/**
* Servlet implementation class IndexServlet
*/
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public IndexServlet() {
super();
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
FacebookXmlRestClient xmlClient = FacebookFilter.getUserClient(session);
FacebookJaxbRestClient jaxbClient = new FacebookJaxbRestClient(
xmlClient.getApiKey(), xmlClient.getSecret(), xmlClient
.getCacheSessionKey());
try {

// Get user friend list
FriendsGetResponse friendResponse = (FriendsGetResponse) jaxbClient
.friends_get(jaxbClient.getCacheUserId());
List<Long> friends = friendResponse.getUid();

// Get friend info
UsersGetInfoResponse userResponse = jaxbClient.users_getInfo(
friends, EnumSet.of(ProfileField.UID, ProfileField.NAME,
ProfileField.SEX, ProfileField.BIRTHDAY));
List<User> friendsInfo = userResponse.getUser();

Map<String, Object> model = new HashMap<String, Object>();
model.put("friendsInfo", friendsInfo);
request.setAttribute("model", model);

RequestDispatcher dispatcher = request
.getRequestDispatcher("/WEB-INF/pages/index.jsp");
dispatcher.forward(request, response);

} catch (FacebookException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

在 JSP 我選擇用 foreach 將所有朋友資料也列印出來,記得要加上:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" 
prefix="c" %>

完整的 JSP:
<?xml version="1.0" encoding="UTF-8"?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Index</title>
</head>
<body>
<table style="text-align:center;">
<thead>
<tr>
<th>
Image
</th>
<th>
Name
</th>
<th>
Sex
</th>
<th>
Birthday
</th>
</tr>
</thead>
<c:forEach var="info" items="${model['friendsInfo']}">
<tr>
<td>
<img src="http://graph.facebook.com/${info['uid']}/picture/" alt="profile image" />
</td>
<td>
${info['name']}
</td>
<td>
${info['sex']}
</td>
<td>
${info['birthday']}
</td>
</tr>
</c:forEach>
</table>
</body>
</html>

打開 http://apps.facebook.com/canvas_name/ 應該可以看到所有朋友的頭像,名稱,性別和生日日期。

下一回繼續

相關書籍: Facebook For DummiesFacebook Cookbook: Building Applications to Grow Your Facebook EmpireBuilding Facebook Applications For Dummies (For Dummies (Computer/Tech))