使用google appengine的UserService的问题

时间:2010-07-27 12:06:41

标签: java google-app-engine gwt

public class MyServlet扩展HttpServlet {     public void doGet(HttpServletRequest request,HttpServletResponse response)             抛出IOException {         UserService userService = UserServiceFactory.getUserService();

    String thisURL = request.getRequestURI();
    if (request.getUserPrincipal() != null) {
        response.getWriter().println("<p>Hello, " +
                                     request.getUserPrincipal().getName() +
                                     "!  You can <a href=\"" +
                                     userService.createLogoutURL(thisURL) +
                                     "\">sign out</a>.</p>");
        System.out.println("<p>Hello, " +
                request.getUserPrincipal().getName() +
                "!  You can <a href=\"" +
                userService.createLogoutURL(thisURL) +
                "\">sign out</a>.</p>");
    } else {
        response.getWriter().println("<p>Please <a href=\"" +
                                     userService.createLoginURL(thisURL) +
                                     "\">sign in</a>.</p>");
    }
}

}

我应该从哪里调用这个servlet?

3 个答案:

答案 0 :(得分:0)

web.xml文件中配置servlet后,调用您在servlet映射中定义的URL。

答案 1 :(得分:0)

请使用生成的代码创建新的AppEngine项目,您可以找到它的工作原理......

您必须创建LoginService(在GWT客户端上)并在服务器(类LoginServiceImpl)上实现它。然后你可以调用LoginService.getCurrentUser()...

检查出来:http://code.google.com/intl/vi/appengine/docs/java/users/overview.html

答案 2 :(得分:0)

Google App Engine提供用户服务以获取登录的当前用户。因此,您可以在应用程序启动时使用上述代码。您只需编写一个名为登录过滤器的简单servlet过滤器 您可以检查用户是否登录的每个请求。因此,通过在web.xml中配置的Login过滤器传递所有初始servlet。

我希望这会对你有所帮助。

您可以按照以下示例

public class LoginFilter implements Filter {
  final Logger log = Logger.getLogger(LoginFilter.class.getName());

  @Override
  public void destroy() {

  }

  @Override
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
      throws IOException, ServletException {
    long before = System.currentTimeMillis();

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    HttpServletRequest httpReq = (HttpServletRequest)req;
    String uri = httpReq.getRequestURI();
    if (user == null) {
      log.info("There is no user logged in yet");
      if (uri == null || uri.equals("")) {
          uri = "/servletpath";
      }
      String destUrl = "destUri=" + uri;
      RequestDispatcher dispatcher = req.getRequestDispatcher("/yourlogin.jsp" + "?" + destUrl);
      dispatcher.forward(req, resp);
      return;
    } 
    chain.doFilter(req, resp);
    long after = System.currentTimeMillis();
    String name = "";
    if (req instanceof HttpServletRequest) {
      name = ((HttpServletRequest) req).getRequestURI();
    }
    log.info(name + ": " + (after - before) + "ms");
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {

  }

}