Derleme Yetkilendirme Geri Çağırma İşleyicisi

Bu dokümanda, Google Tasks API'yı kullanarak kullanıcının görevlerini görüntüleyecek örnek bir web uygulaması üzerinden Java servlet'leri kullanarak bir OAuth 2.0 yetkilendirme geri çağırma işleyicinin nasıl uygulanacağı açıklanmaktadır. Örnek uygulama önce kullanıcının Google Görevler'ine erişmek için yetkilendirme ister ve ardından kullanıcının görevlerini varsayılan görevler listesinde görüntüler.

Kitle

Bu belge, Java ve J2EE web uygulaması mimarisi hakkında bilgi sahibi olan kişiler için hazırlanmıştır. OAuth 2.0 yetkilendirme akışı hakkında biraz bilgi sahibi olmanız önerilir.

İçindekiler

Bu tür eksiksiz bir örneğe sahip olmak için aşağıdakileri yapmanız gerekir:

web.xml dosyasında servlet eşlemelerini bildirme

Uygulamamızda 2 servlet kullanacağız:

  • PrintTasksTitlesServlet (/ ile eşlendi): Kullanıcı kimlik doğrulamasını gerçekleştirecek ve kullanıcının görevlerini görüntüleyecek uygulamanın giriş noktası
  • OAuthCodeCallbackHandlerServlet (/oauth2callback ile eşlenir): OAuth yetkilendirme uç noktasından gelen yanıtı işleyen OAuth 2.0 geri çağırması

Aşağıda, bu 2 servlet'i uygulamamızdaki URL'lerle eşleyen web.xml dosyasını bulabilirsiniz:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <servlet>
   <servlet-name>PrintTasksTitles</servlet-name>
   <servlet-class>com.google.oauthsample.PrintTasksTitlesServlet</servlet-class>
 </servlet>

 <servlet-mapping>
   <servlet-name>PrintTasksTitles</servlet-name>
   <url-pattern>/</url-pattern>
 </servlet-mapping>

 <servlet>
   <servlet-name>OAuthCodeCallbackHandlerServlet</servlet-name>
   <servlet-class>com.google.oauthsample.OAuthCodeCallbackHandlerServlet</servlet-class>
 </servlet>

 <servlet-mapping>
   <servlet-name>OAuthCodeCallbackHandlerServlet</servlet-name>
   <url-pattern>/oauth2callback</url-pattern>
 </servlet-mapping>

</web-app>
/WEB-INF/web.xml dosyası

Sisteminizdeki kullanıcıların kimliğini doğrulama ve sistemin görevlerine erişmek için yetkilendirme isteme

Kullanıcı, uygulamaya kök '/' üzerinden girer PrintTaskListsTitlesServlet servlet ile eşlenen URL. Bu servlet'te aşağıdaki görevler gerçekleştirilir:

  • Kullanıcının sistemde kimliğinin doğrulanıp doğrulanmadığını kontrol eder
  • Kullanıcının kimliği doğrulanmamışsa kimlik doğrulama sayfasına yönlendirilir
  • Kullanıcının kimliği doğrulanırsa veri depolama alanımızda (aşağıdaki OAuthTokenDao tarafından işlenen) bir yenileme jetonu olup olmadığını kontrol ederiz. Kullanıcının depoda yenileme jetonu yoksa bu, kullanıcının henüz görevlerine erişmek için uygulama yetkisi vermediği anlamına gelir. Bu durumda, kullanıcı Google'ın OAuth 2.0 Yetkilendirme uç noktasına yönlendirilir.
ziyaret edin. Aşağıda bunu uygulamanın bir yolu yer almaktadır:

package com.google.oauthsample;

import ...

/**
 * Simple sample Servlet which will display the tasks in the default task list of the user.
 */
@SuppressWarnings("serial")
public class PrintTasksTitlesServlet extends HttpServlet {

  /**
   * The OAuth Token DAO implementation, used to persist the OAuth refresh token.
   * Consider injecting it instead of using a static initialization. Also we are
   * using a simple memory implementation as a mock. Change the implementation to
   * using your database system.
   */
  public static OAuthTokenDao oauthTokenDao = new OAuthTokenDaoMemoryImpl();

  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Getting the current user
    // This is using App Engine's User Service but you should replace this to
    // your own user/login implementation
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    // If the user is not logged-in it is redirected to the login service, then back to this page
    if (user == null) {
      resp.sendRedirect(userService.createLoginURL(getFullRequestUrl(req)));
      return;
    }

    // Checking if we already have tokens for this user in store
    AccessTokenResponse accessTokenResponse = oauthTokenDao.getKeys(user.getEmail());

    // If we don't have tokens for this user
    if (accessTokenResponse == null) {
      OAuthProperties oauthProperties = new OAuthProperties();
      // Redirect to the Google OAuth 2.0 authorization endpoint
      resp.sendRedirect(new GoogleAuthorizationRequestUrl(oauthProperties.getClientId(),
          OAuthCodeCallbackHandlerServlet.getOAuthCodeCallbackHandlerUrl(req), oauthProperties
              .getScopesAsString()).build());
      return;
    }
  }

  /**
   * Construct the request's URL without the parameter part.
   *
   * @param req the HttpRequest object
   * @return The constructed request's URL
   */
  public static String getFullRequestUrl(HttpServletRequest req) {
    String scheme = req.getScheme() + "://";
    String serverName = req.getServerName();
    String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort();
    String contextPath = req.getContextPath();
    String servletPath = req.getServletPath();
    String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
    String queryString = (req.getQueryString() == null) ? "" : "?" + req.getQueryString();
    return scheme + serverName + serverPort + contextPath + servletPath + pathInfo + queryString;
  }
}
PrintTasksTitlesServlet.java dosyası

Not: Yukarıdaki uygulamada, bazı App Engine kitaplıkları kullanılmaktadır. Bu kitaplıklar, sadeleştirme amacıyla kullanılmaktadır. Başka bir platform için geliştirme yapıyorsanız kullanıcı kimlik doğrulamasını gerçekleştiren UserService arayüzünü yeniden uygulayabilirsiniz.

Uygulama, kullanıcının yetkilendirme jetonlarını sürdürmek ve bunlara erişmek için bir DAO kullanır. Aşağıda, bu örnekte kullanılan OAuthTokenDao arayüzü ve OAuthTokenDaoMemoryImpl adlı örnek (bellek içi) uygulama gösterilmiştir:

package com.google.oauthsample;

import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;

/**
 * Allows easy storage and access of authorization tokens.
 */
public interface OAuthTokenDao {

  /**
   * Stores the given AccessTokenResponse using the {@code username}, the OAuth
   * {@code clientID} and the tokens scopes as keys.
   *
   * @param tokens The AccessTokenResponse to store
   * @param userName The userName associated wit the token
   */
  public void saveKeys(AccessTokenResponse tokens, String userName);

  /**
   * Returns the AccessTokenResponse stored for the given username, clientId and
   * scopes. Returns {@code null} if there is no AccessTokenResponse for this
   * user and scopes.
   *
   * @param userName The username of which to get the stored AccessTokenResponse
   * @return The AccessTokenResponse of the given username
   */
  public AccessTokenResponse getKeys(String userName);
}
OAuthTokenDao.java dosyası
package com.google.oauthsample;

import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
...

/**
 * Quick and Dirty memory implementation of {@link OAuthTokenDao} based on
 * HashMaps.
 */
public class OAuthTokenDaoMemoryImpl implements OAuthTokenDao {

  /** Object where all the Tokens will be stored */
  private static Map tokenPersistance = new HashMap();

  public void saveKeys(AccessTokenResponse tokens, String userName) {
    tokenPersistance.put(userName, tokens);
  }

  public AccessTokenResponse getKeys(String userName) {
    return tokenPersistance.get(userName);
  }
}
OAuthTokenDaoMemoryImpl.java dosyası

Ayrıca, uygulamanın OAuth 2.0 kimlik bilgileri bir özellikler dosyasında depolanır. Alternatif olarak, bunları Java sınıflarınızdan birinin bir yerinde sabit değer olarak da kullanabilirsiniz. Yine de, OAuthProperties sınıfı ve örnekte kullanılan oauth.properties dosyasını burada bulabilirsiniz:

package com.google.oauthsample;

import ...

/**
 * Object representation of an OAuth properties file.
 */
public class OAuthProperties {

  public static final String DEFAULT_OAUTH_PROPERTIES_FILE_NAME = "oauth.properties";

  /** The OAuth 2.0 Client ID */
  private String clientId;

  /** The OAuth 2.0 Client Secret */
  private String clientSecret;

  /** The Google APIs scopes to access */
  private String scopes;

  /**
   * Instantiates a new OauthProperties object reading its values from the
   * {@code OAUTH_PROPERTIES_FILE_NAME} properties file.
   *
   * @throws IOException IF there is an issue reading the {@code propertiesFile}
   * @throws OauthPropertiesFormatException If the given {@code propertiesFile}
   *           is not of the right format (does not contains the keys {@code
   *           clientId}, {@code clientSecret} and {@code scopes})
   */
  public OAuthProperties() throws IOException {
    this(OAuthProperties.class.getResourceAsStream(DEFAULT_OAUTH_PROPERTIES_FILE_NAME));
  }

  /**
   * Instantiates a new OauthProperties object reading its values from the given
   * properties file.
   *
   * @param propertiesFile the InputStream to read an OAuth Properties file. The
   *          file should contain the keys {@code clientId}, {@code
   *          clientSecret} and {@code scopes}
   * @throws IOException IF there is an issue reading the {@code propertiesFile}
   * @throws OAuthPropertiesFormatException If the given {@code propertiesFile}
   *           is not of the right format (does not contains the keys {@code
   *           clientId}, {@code clientSecret} and {@code scopes})
   */
  public OAuthProperties(InputStream propertiesFile) throws IOException {
    Properties oauthProperties = new Properties();
    oauthProperties.load(propertiesFile);
    clientId = oauthProperties.getProperty("clientId");
    clientSecret = oauthProperties.getProperty("clientSecret");
    scopes = oauthProperties.getProperty("scopes");
    if ((clientId == null) || (clientSecret == null) || (scopes == null)) {
      throw new OAuthPropertiesFormatException();
    }
  }

  /**
   * @return the clientId
   */
  public String getClientId() {
    return clientId;
  }

  /**
   * @return the clientSecret
   */
  public String getClientSecret() {
    return clientSecret;
  }

  /**
   * @return the scopes
   */
  public String getScopesAsString() {
    return scopes;
  }

  /**
   * Thrown when the OAuth properties file was not at the right format, i.e not
   * having the right properties names.
   */
  @SuppressWarnings("serial")
  public class OAuthPropertiesFormatException extends RuntimeException {
  }
}
OAuthProperties.java dosyası

Aşağıda, uygulamanızın OAuth 2.0 kimlik bilgilerini içeren oauth.properties dosyasını bulabilirsiniz. Aşağıdaki değerleri kendiniz değiştirmeniz gerekiyor.

# Client ID and secret. They can be found in the APIs console.
clientId=1234567890.apps.googleusercontent.com
clientSecret=aBcDeFgHiJkLmNoPqRsTuVwXyZ
# API scopes. Space separated.
scopes=https://www.googleapis.com/auth/tasks
oauth.properties dosyası

OAuth 2.0 İstemci Kimliği ve İstemci sırrı, uygulamanızı tanımlar ve Tasks API'nin uygulamanız için tanımlanmış filtreleri ve kota kurallarını uygulamasına olanak tanır. İstemci kimliği ve gizli anahtar Google API'leri Konsolu'nda bulunabilir. Konsolda şunları yapmanız gerekir:

  • Proje oluşturun veya seçin.
  • Hizmet listesinde Görevler API'sı durumunu AÇIK duruma getirerek Görevler API'sini etkinleştirin.
  • API Erişimi bölümünde, henüz oluşturulmadıysa bir OAuth 2.0 İstemci Kimliği oluşturun.
  • Projenin OAuth 2.0 kod geri çağırma işleyici URL'sinin, Yönlendirme URI'leri bölümünde kayıtlı/beyaz listeye eklendiğinden emin olun. Örneğin, bu örnek projede, web uygulamanız https://www.example.com alanından sunuluyorsa https://www.example.com/oauth2callback adresini kaydetmeniz gerekir.

API Konsolu&#39;ndaki yönlendirme URI&#39;si
API Konsolu'ndaki yönlendirme URI'si

Google Yetkilendirme uç noktasından gelen Yetkilendirme kodunu dinleyin.

Kullanıcının henüz uygulamaya görevlerine erişmesi için yetki vermemişse ve dolayısıyla Google'ın OAuth 2.0 Yetkilendirme uç noktasına yönlendirildiği durumda, kullanıcıya Google'dan, uygulamanızın görevlerine erişmesi için izin vermesini isteyen bir yetkilendirme iletişim kutusu gösterilir:

Google&#39;ın yetkilendirme iletişim kutusu
Google'ın yetkilendirme iletişim kutusu

Erişim izninin verilmesi veya reddedilmesinin ardından kullanıcı, Google yetkilendirme URL'si oluşturulurken bir yönlendirme/geri çağırma olarak belirtilen OAuth 2.0 kod geri çağırma işleyicisine yönlendirilir:

new GoogleAuthorizationRequestUrl(oauthProperties.getClientId(),
      OAuthCodeCallbackHandlerServlet.getOAuthCodeCallbackHandlerUrl(req), oauthProperties
          .getScopesAsString()).build()

OAuth 2.0 kod geri çağırma işleyicisi (OAuthCodeCallbackHandlerServlet), Google OAuth 2.0 uç noktasından gelen yönlendirmeyi işler. İlgilenilmesi gereken 2 durum vardır:

  • Kullanıcı erişim izni verdi: URL parametrelerinden OAuth 2.0 kodunu almak için isteği ayrıştırır.
  • Kullanıcı erişimi reddetti: Kullanıcıya bir mesaj gösterilir

package com.google.oauthsample;

import ...

/**
 * Servlet handling the OAuth callback from the authentication service. We are
 * retrieving the OAuth code, then exchanging it for a refresh and an access
 * token and saving it.
 */
@SuppressWarnings("serial")
public class OAuthCodeCallbackHandlerServlet extends HttpServlet {

  /** The name of the Oauth code URL parameter */
  public static final String CODE_URL_PARAM_NAME = "code";

  /** The name of the OAuth error URL parameter */
  public static final String ERROR_URL_PARAM_NAME = "error";

  /** The URL suffix of the servlet */
  public static final String URL_MAPPING = "/oauth2callback";

  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Getting the "error" URL parameter
    String[] error = req.getParameterValues(ERROR_URL_PARAM_NAME);

    // Checking if there was an error such as the user denied access
    if (error != null && error.length > 0) {
      resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: \""+error[0]+"\".");
      return;
    }
    // Getting the "code" URL parameter
    String[] code = req.getParameterValues(CODE_URL_PARAM_NAME);

    // Checking conditions on the "code" URL parameter
    if (code == null || code.length == 0) {
      resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "The \"code\" URL parameter is missing");
      return;
    }
  }

  /**
   * Construct the OAuth code callback handler URL.
   *
   * @param req the HttpRequest object
   * @return The constructed request's URL
   */
  public static String getOAuthCodeCallbackHandlerUrl(HttpServletRequest req) {
    String scheme = req.getScheme() + "://";
    String serverName = req.getServerName();
    String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort();
    String contextPath = req.getContextPath();
    String servletPath = URL_MAPPING;
    String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
    return scheme + serverName + serverPort + contextPath + servletPath + pathInfo;
  }
}
OAuthCodeCallbackHandlerServlet.java dosyası

Yenileme ve erişim jetonu için yetkilendirme kodunu değiştirin

Ardından OAuthCodeCallbackHandlerServlet, yenileme ve erişim jetonları için Auth 2.0 kodunu alıp verir, kodu veri deposunda tutar ve kullanıcıyı tekrar PrintTaskListsTitlesServlet URL'sine yönlendirir:

Aşağıdaki dosyaya eklenen kod söz dizimi vurgulanmıştır, mevcut kod ise devre dışıdır.

package com.google.oauthsample;

import ...

/**
 * Servlet handling the OAuth callback from the authentication service. We are
 * retrieving the OAuth code, then exchanging it for a refresh and an access
 * token and saving it.
 */
@SuppressWarnings("serial")
public class OAuthCodeCallbackHandlerServlet extends HttpServlet {

  /** The name of the Oauth code URL parameter */
  public static final String CODE_URL_PARAM_NAME = "code";

  /** The name of the OAuth error URL parameter */
  public static final String ERROR_URL_PARAM_NAME = "error";

  /** The URL suffix of the servlet */
  public static final String URL_MAPPING = "/oauth2callback";
. /** Geri çağırmayı işledikten sonra kullanıcının yönlendirileceği URL. Dikkatlice * Kullanıcıları Google'a yönlendirmeden önce bir çereze kaydederek * yetkilendirme URL'si. */ public static final String REDIRECT_URL = "/"; /** OAuth Jetonu DAO uygulaması. Şunu kullanmak yerine enjekte etmeyi düşünebilirsiniz: * statik başlatma. Aynı zamanda 300x250 boyutunda basit bir hafıza uygulaması kullanıyoruz. * örnek olarak verilebilir. Uygulamayı, veritabanı sisteminizi kullanacak şekilde değiştirin. */ herkese açık statik OAuthTokenDao oauthTokenDao = yeni OAuthTokenDaoMemoryImpl();
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Getting the "error" URL parameter
    String[] error = req.getParameterValues(ERROR_URL_PARAM_NAME);

    // Checking if there was an error such as the user denied access
    if (error != null && error.length > 0) {
      resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: \""+error[0]+"\".");
      return;
    }

    // Getting the "code" URL parameter
    String[] code = req.getParameterValues(CODE_URL_PARAM_NAME);

    // Checking conditions on the "code" URL parameter
    if (code == null || code.length == 0) {
      resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "The \"code\" URL parameter is missing");
      return;
    }
. // Gelen istek URL'sini oluştur String requestUrl = getOAuthCodeCallbackHandlerUrl(req); // OAuth jetonları için kod değişimi AccessTokenResponse accessTokenResponse = exchangeCodeForAccessAndRefreshTokens(kod[0], requestUrl); // Geçerli kullanıcıyı alma // Bu komut App Engine'in User Service'i (Kullanıcı Hizmeti) kullanıyor ancak bunu şununla değiştirmeniz gerekir: // kendi kullanıcı/giriş uygulamanız UserService userService = UserServiceFactory.getUserService(); Dize e-postası = userService.getCurrentUser().getEmail(); // Jetonları kaydedin oauthTokenDao.saveKeys(accessTokenResponse, e-posta); resp.sendRedirect(REDIRECT_URL); }
  /**
   * Construct the OAuth code callback handler URL.
   *
   * @param req the HttpRequest object
   * @return The constructed request's URL
   */
  public static String getOAuthCodeCallbackHandlerUrl(HttpServletRequest req) {
    String scheme = req.getScheme() + "://";
    String serverName = req.getServerName();
    String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort();
    String contextPath = req.getContextPath();
    String servletPath = URL_MAPPING;
    String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
    return scheme + serverName + serverPort + contextPath + servletPath + pathInfo;
  }
/** * Verilen kodu bir exchange ve yenileme jetonuyla değiştirir. * * @param kodu Yetkilendirme hizmetinden geri alınan kod * @param currentUrl Geri çağırmanın URL'si * @param oauthProperties OAuth yapılandırmasını içeren nesne * @return Hem erişim hem de yenileme jetonu içeren nesne * @IOException fırlatır */ herkese açık AccessTokenResponse exchangeCodeForAccessAndRefreshTokens(Dize kodu, Dize currentUrl) throws IOException { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = yeni JacksonFactory(); // oauth yapılandırma dosyasını yükleme OAuthProperties oauthProperties = new OAuthProperties(); yeni GoogleAuthorizationCodeGrant(httpTransport, jsonFactory, oauthProperties) döndür .getClientId(), oauthProperties.getClientSecret(), kod, currentUrl).execute(); } }
OAuthCodeCallbackHandlerServlet.java dosyası

Not: Yukarıdaki uygulamada, bazı App Engine kitaplıkları kullanılmaktadır. Bu kitaplıklar, sadeleştirme amacıyla kullanılmaktadır. Başka bir platform için geliştirme yapıyorsanız kullanıcı kimlik doğrulamasını gerçekleştiren UserService arayüzünü yeniden uygulayabilirsiniz.

Kullanıcının görevlerini okuma ve görüntüleme

Kullanıcı, uygulamanın görevlerine erişmesine izin verdi. Uygulama, OAuthTokenDao aracılığıyla erişilebilen veri deposuna kaydedilen bir yenileme jetonuna sahiptir. PrintTaskListsTitlesServlet servlet, artık kullanıcının görevlerine erişmek ve bunları görüntülemek için bu jetonları kullanabilir:

Aşağıdaki dosyaya eklenen kod söz dizimi vurgulanmıştır, mevcut kod ise devre dışıdır.

package com.google.oauthsample;

import ...

/**
 * Simple sample Servlet which will display the tasks in the default task list of the user.
 */
@SuppressWarnings("serial")
public class PrintTasksTitlesServlet extends HttpServlet {

  /**
   * The OAuth Token DAO implementation, used to persist the OAuth refresh token.
   * Consider injecting it instead of using a static initialization. Also we are
   * using a simple memory implementation as a mock. Change the implementation to
   * using your database system.
   */
  public static OAuthTokenDao oauthTokenDao = new OAuthTokenDaoMemoryImpl();

  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Getting the current user
    // This is using App Engine's User Service but you should replace this to
    // your own user/login implementation
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    // If the user is not logged-in it is redirected to the login service, then back to this page
    if (user == null) {
      resp.sendRedirect(userService.createLoginURL(getFullRequestUrl(req)));
      return;
    }

    // Checking if we already have tokens for this user in store
    AccessTokenResponse accessTokenResponse = oauthTokenDao.getKeys(user.getEmail());

    // If we don't have tokens for this user
    if (accessTokenResponse == null) {
      OAuthProperties oauthProperties = new OAuthProperties();
      // Redirect to the Google OAuth 2.0 authorization endpoint
      resp.sendRedirect(new GoogleAuthorizationRequestUrl(oauthProperties.getClientId(),
          OAuthCodeCallbackHandlerServlet.getOAuthCodeCallbackHandlerUrl(req), oauthProperties
              .getScopesAsString()).build());
      return;
    }
. // Kullanıcının görev listelerinin yanıttaki başlıkları yazdırılır resp.setContentType(&quot;text/plain&quot;); resp.getWriter().append("Kullanıcı için Görev Listeleri başlıkları + user.getEmail() + ":\n\n"); PrintTasksTitles(accessTokenResponse, resp.getWriter( sırası)
  }

  /**
   * Construct the request's URL without the parameter part.
   *
   * @param req the HttpRequest object
   * @return The constructed request's URL
   */
  public static String getFullRequestUrl(HttpServletRequest req) {
    String scheme = req.getScheme() + "://";
    String serverName = req.getServerName();
    String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort();
    String contextPath = req.getContextPath();
    String servletPath = req.getServletPath();
    String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
    String queryString = (req.getQueryString() == null) ? "" : "?" + req.getQueryString();
    return scheme + serverName + serverPort + contextPath + servletPath + pathInfo + queryString;
  }
/** * Varsayılan olarak kullanıcıların görevlerinin listesini almak için Google Tasks API'yi kullanır * görev listesi. * * @param accessTokenResponse OAuth 2.0 AccessTokenResponse nesnesi * Erişim jetonunu ve yenileme jetonunu içerir. * @param, görev listeleri başlıklarının ilişkilendirileceği çıkış akışı yazıcısının çıktısını verir * @return Varsayılan görev listesindeki kullanıcıların görev başlıklarının listesi. * @IOException fırlatır */ public void printTasksTitles(AccessTokenResponse accessTokenResponse, Writer output) throws IOException { // Görevler hizmetini başlatma HttpTransport aktarımı = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); OAuthProperties oauthProperties = new OAuthProperties(); GoogleAccessProtectedResource accessProtectedResource = yeni GoogleAccessProtectedResource( accessTokenResponse.accessToken, taşıma, jsonFactory, oauthProperties.getClientId(), oauthProperties.getClientSecret(), accessTokenResponse.refreshToken); Görevler hizmeti = yeni Görevler(transport, accessProtectedResource, jsonFactory); // Görev listeleri listesini sorgulamak için ilk kullanıma hazır Görevler API'sını kullanma com.google.api.services.tasks.model.Tasks tasks = service.tasks.list(&quot;@default&quot;).execute(); for (Task task : tasks.items) { exit.append(task.title + "\n"); } } }
PrintTasksTitlesServlet.java dosyası

Kullanıcı, görevleriyle birlikte gösterilir:

Kullanıcının görevleri
Kullanıcının görevleri

Örnek uygulama

Bu örnek uygulamanın kodunu buradan indirebilirsiniz. Göz atabilirsiniz.