1

我正在尝试实现 Twitter 登录过程。在登录过程中,用户需要被重定向到 Twitter 网站以输入他/她的凭据,然后他/她将被重定向到我的网站 URL。在第一次重定向之前,应在请求之间存储和保留 RequestToken 对象(Twitter4J 库)的实例。

为此,我决定使用 ConverstaionScoped bean,但不幸的是,请求之间没有保留引用的值。

这是我的 JSF 页面:

推特.xhtml:

<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      >

    <f:event listener="#{twitterLoginPageController.login()}" type="preRenderView" />

</html>

twitterRedirect.xhtml:

<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      >

    <f:event listener="#{twitterLoginPageController.onRedirect(param.oauth_token, param.oauth_verifier)}" type="preRenderView" />

</html>

我的 Twitter 登录控制器:

@Named
@ConversationScoped
public class TwitterLoginPageController implements Serializable {


    @Inject
    private Conversation conversation;

    // These objects should be retained between requests
    Twitter twitter;
    RequestToken requestToken;

    public void login() {

        try {
            twitter = new TwitterFactory().getInstance();
            requestToken = twitter.getOAuthRequestToken("...");


            conversation.begin();
            conversation.setTimeout(30000);
            // Navigate to Twitter here
        } catch (TwitterException ex) {
             ...
        }

    }

    public void onRedirect(String oauthToken, String oauthVerifier) {      
        try {
            // twitter reference is null here
            twitter.getOAuthAccessToken(requestToken, oauthVerifier);
            ...
        } catch (TwitterException e) {
            ...
        } finally {
            conversation.end();
        }

    }
}

在我看来,我正在密切关注使用 @ConverstaionScope 的示例,但我没有得到预期的结果。我应该怎么做才能在请求之间保留对象?

4

1 回答 1

5

我不熟悉 Twitter auth 或 Twitter4J,但由于是 twitter 将用户重定向回您的应用程序,因此您必须将对话 id 传递给 twitter,以便 twitter 将用户重定向回包含该 id 的 URL。

Java EE 容器通过传递参数来维护会话状态,cid=...这对于 JSF 导航会自动发生,但您必须另外处理它。因此,请确保在开始对话后获取对话 id并将其传递给 Twitter,以便 twitter 将用户重定向到twitterRedirect.xhtml?cid=....

于 2013-10-05T16:07:06.400 回答