2010-03-02 50 views

回答

1

要预处理请求,您需要创建Servlet并实施doGet()方法。在此方法内部,您可以随意编写/调用Java代码,而无需使用scriptlet混淆JSP文件。利用doGet()方法中的java.net.URL和/或java.net.URLConnection通过HTTP请求访问Facebook API并获取数据作为HTTP响应。最后以List<Friend>的风格处理这些数据,并将请求转发到JSP页面进行显示。

开球例如:

public class FacebookServlet extends HttpServlet { 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     URL url = new URL("http://url/to/some/facebook/API/to/get/list/of/friends"); // Read Facebook API doc for the correct URL. 
     InputStream input = url.openStream(); 
     List<Friend> friends = extractFriends(input); // Do your job here. 
     request.setAttribute("friends", friends); // It's then available as ${friends} in JSP. 
     request.getRequestDispatcher("/WEB-INF/friends.jsp").forward(request, response); 
    } 
} 

地图这个servlet在web.xml上的例如/friends,这样就可以通过http://example.com/contextname/friends调用它的url-pattern

然后,在你/WEB-INF/friends.jsp(在JSP被放置在/WEB-INF防止直接访问,而无需使用servlet),利用JSTL(刚落,在/WEB-INF/libjstl-1.2.jarc:forEach标签遍历List<Friend>和打印HTML表(<tr>):

<table> 
    <c:forEach items="${friends}" var="friend"> 
     <tr> 
      <td>${friend.name}</td> 
      <td>${friend.age}</td> 
      <td>${friend.email}</td> 
      <td>etc..</td> 
     </tr> 
    </c:forEach> 
</table> 
+0

你应该提供一个url示例的例子吗? – JohnRaja 2010-03-02 12:52:28

+0

阅读Facebook API文档以获取正确的URL。 http://wiki.developers.facebook.com/index.php/API – BalusC 2010-03-02 17:12:19