2015-07-11 34 views
1

我正在为类似于社交中心的课程制作一个Web应用程序,我在Spring中使用了Java以及Spring社交模块。该应用程序的重点是有一个地方,您可以从Facebook和Twitter帐户浏览饲料。所以目前该应用程序允许创建一个帐户,登录,注销和浏览提要。由于该应用程序适用于特定于应用程序的帐户,因此我没有使用Spring社交帐户登录,但登录后用户可以选择将他/她的Facebook或Twitter帐户链接到应用程序。 该应用程序成功连接Facebook和Twitter,并没有问题检索饲料。我将我的项目建立在github Spring social quickstart project的春季社交快速入门中。 问题本身就是,当用户转到提要页面而没有将twitter或Facebook账户链接到应用程序时,它会抛出NullPointerException异常。这是该方法的代码中发生异常Spring Social - Facebook.isAuthorized引发NullPointerException

@RequestMapping(value={"/", "feed"}, method = RequestMethod.GET) 
public String llenarFeed(Principal principal, Model model){ 
    boolean emptyFeed = true; 
    if(facebook != null){ 
      if(facebook.isAuthorized()){ 
       model.addAttribute("fbFeed", facebook.feedOperations().getHomeFeed()); 
       model.addAttribute("perfil", facebook.userOperations().getUserProfile()); 
       emptyFeed = false; 
      } 
    } 
    if (twitter != null) { 
     model.addAttribute("timeline", twitter.timelineOperations().getHomeTimeline()); 
     emptyFeed = false; 
    } 
    model.addAttribute("usuario", usuarioService.loadUsuarioByUsername(principal.getName())); 
    return "feed"; 
} 

在此行中出现的问题,如果(facebook.isAuthorized()) 所以我知道Facebook是不为空,但在调用isAuthorized导致空指针异常时,问题是我该如何解决它?

+0

你是如何实例化Facebook对象的?即私人Facebook的Facebook; @Inject public llenarFeed(Facebook脸书){ this.facebook = facebook; } – smoggers

+0

@smoggers在我的控制器,其中该方法属于我有@Inject注释的属性称为Facebook而言,Bean是在与@Configuration注释和实现SocialConfigurer和bean的方法的SocialConfig类初始化是'@Bean @Scope(value =“request”,proxyMode = ScopedProxyMode.INTERFACES) public Facebook facebook(ConnectionRepository repository){ \t Connection connection = repository.findPrimaryConnection(Facebook.class); \t返回连接!= null? connection.getApi():null; }' – cvalentina

+0

就像我说我没有问题连接到Facebook或Twitter和检索家庭饲料,问题是如何知道用户是否没有连接每个人,因为isAuthorized()抛出Facebook和Twitter的NullPointerException。 – cvalentina

回答

1

我用try-catch解决了。当遇到错误时,它会重定向到连接页面。

@RequestMapping(value={"/", "feed"}, method = RequestMethod.GET) 
public String llenarFeed(Principal principal, Model model){ 
    boolean emptyFeed = true; 
    try{ 
     if(facebook != null){ 
      if(facebook.isAuthorized()){ 
       model.addAttribute("fbFeed", facebook.feedOperations().getHomeFeed()); 
       model.addAttribute("perfil", facebook.userOperations().getUserProfile()); 
       emptyFeed = false; 
      } 
     } 
    } 
    catch{ 
    return "redirect:/connect/facebook"; 
} 
    if (twitter != null) { 
     model.addAttribute("timeline", twitter.timelineOperations().getHomeTimeline()); 
     emptyFeed = false; 
    } 
    model.addAttribute("usuario", usuarioService.loadUsuarioByUsername(principal.getName())); 
    return "feed"; 
} 
相关问题