Google App Engine UserService.CurrentUser()在servlet处理通道中返回null连接/ _ah / channel / connected /

时间:2012-08-29 10:41:35

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

我在adreess / _ah / channel / connected /上使用Google Channel api和注册的servlet来处理用户频道连接。当在post post处理程序中发生连接时,我发现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是:

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

1 个答案:

答案 0 :(得分:3)

/_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.