【问题标题】:Google App Engine UserServiceget.CurrentUser() returns null in servlet handling channel connect at /_ah/channel/connected/Google App Engine UserServiceget.CurrentUser() 在 /_ah/channel/connected/ 的 servlet 处理通道连接中返回 null
【发布时间】:2012-08-29 10:41:35
【问题描述】:

我使用 Google Channel api 和在 adreess /_ah/channel/connected/ 注册的 servlet 来处理用户通道连接。当在发布消息处理程序中发生连接时,我发现 UserServiceget.CurrentUser() 返回 null,而在我的应用程序的其他 servlet 中它返回用户。请问是什么情况告诉我。 servlet 代码是这样的:

@SuppressWarnings("serial")
public class ConnectServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                    throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if( user != null ){        
        String user_name = user.getNickname();
        Logger.getLogger("server").log( Level.WARNING, "User " + user_name + "  connected" );
       }
    }
}

安全约束是:

<security-constraint>
    <web-resource-collection>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>*</role-name>
    </auth-constraint>
</security-constraint>

【问题讨论】:

    标签: java google-app-engine channel-api


    【解决方案1】:

    /_ah/channel/connected/ 的调用是由内部 Google 频道服务服务器发出的,而不是由用户直接发出的。所以这个请求没有与之关联的用户。

    这是example how to handle Channel API

    1. 服务器:在服务器上创建一个唯一的客户端 ID。您可以使用用户 ID:

      String clientId = userService.getCurrentUser().getUserId();
      
    2. 服务器:从客户端 ID 创建通道令牌并将其传递回客户端:

      ChannelService channelService = ChannelServiceFactory.getChannelService();
      String token = channelService.createChannel(clientId);
      
    3. 在客户端的 Javascript 中使用令牌:

      // --token-- a token received from server
      channel = new goog.appengine.Channel('--token--');
      
    4. 然后在/_ah/channel/connected/ 处理程序中你可以这样做:

      ChannelService channelService = ChannelServiceFactory.getChannelService();
      ChannelPresence presence = channelService.parsePresence(req);
      String clientId = presence.clientId();
      // clientId equals userId as set in point 1. 
      

    【讨论】:

    猜你喜欢
    • 2019-04-26
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 2011-05-23
    相关资源
    最近更新 更多