# Java Application Configuration Using app.yaml - Google App Engine - Google Code

English ▼
Skip to page content Skip to main navigation
e.g. "templates" or "datastore"

# Java Application Configuration Using app.yaml

With `app.yaml`, you can configure your Java application more easily, and with fewer files, than with the standard `web.xml` configuration. You can use `app.yaml` as long as your application does not need to be portable to other Java application servers.

- About app.yaml for Java
- Required Elements
- Static Files and Resource Files
  - Including and Excluding Files
  - Setting the Browser Cache Expiration
  - Changing the MIME Type for Static Files
  - Changing the Root Directory
- System Properties, Environment Variables, and Context Parameters
- Servlet Context Listeners
- Secure URLs
- Required Login or Administrator Status
- The Welcome File List
- Reserved URLs
- Inbound Services
- Administration Console Custom Pages
- Enabling Sessions
- Disabling Precompilation
- Custom XML Output
- Custom Error Responses

## About app.yaml for Java

`app.yaml` specifies how URL paths correspond to request handlers and static files. It also contains information about the application code, such as the application ID and the latest version identifier. This file is stored in the application's `WEB-INF` directory.

One of the benefits of using `app.yaml` is that it automatically generates `web.xml` and `appengine-web.xml` for you. It overwrites any content you may have written in those files. If you need to include a feature in `web.xml` that `app.yaml` doesn't support, simply specify it in `app.yaml` using web_xml.

The following is an example of a basic `app.yaml` file:

    application: myapp
    version: 1
    runtime: java

    handlers:
    - url: /admin/*
      login: admin

The syntax of `app.yaml` is the YAML format. For more information about this syntax, see the YAML website.

Tip: To add comments in YAML, begin the comment with a pound (#) character. `# This is a comment.`

## Required Elements

An `app.yaml` file must include one of each of the following elements:

`application`
  The application identifier. This is the identifier you selected when you created the application in the Administration Console.

      application: myapp

`version`
  A version specifier for the application code. App Engine retains a copy of your application for each version used. An administrator can change which major version of the application is default using Administration Console, and can test non-default versions before making them default. The version specifier can contain letters, digits, and hyphens.

  Each version of an application retains its own copy of `app.yaml`. When an application is uploaded, the version mentioned in the `app.yaml` file being uploaded is the version that gets created or replaced by the upload.

      version: 2-0-test

`runtime`
  The name of the App Engine runtime environment used by this application. To specify Java, use java. Other runtimes are available; please refer to the runtime's documentation for more info. Other JVM languages can customize `app.yaml` based on the specified runtime.

      runtime: java

`handlers`
  `handlers` define mappings between URL paths and a `servlet`, `filter`, or `jsp` that handle requests with those paths. All handler definitions begin by declaring a `url` pattern:
  url
    Defines the URL pattern for the mapping. This pattern can use an asterisk (`*`) at the beginning or end of the pattern to indicate zero or more of any character. The Java runtime does not support wildcards in the middle of a string, and does not allow multiple wildcards in one pattern. The pattern matches the full path of the URL, starting with and including the forward slash (`/`) following the domain name.

        handlers:
          - url: /red/*

    After declaring the URL, define the mapping with the following elements:
    `servlet`
      Declares a servlet class to map to the specified URL. The servlet is further defined by a name that other elements in the file use to refer to the servlet, and initialization parameters (`init_params`). The name for each servlet must be unique within the YAML file. Using unique names, you can declare multiple servlets of the same class with different initialization parameters.
    `filter`
      Declares a filter class to map to the specified URL in applications that use the javax.servlet.Filter package. A filter is a class that acts on a request like a servlet, but may allow the handling of the request to continue with other filters or servlets. A filter may perform an auxiliary task such as logging, performing specialized authentication checks, or annotating the request or response objects before calling the servlet. Filters allow you to compose request processing tasks from the deployment descriptor. A single URL mapping can include either a filter or a servlet, but not both.
    `init_params`
      Declares the initialization parameters for this mapping.
    `name`
      Declares a name used to refer to the servlet by other elements in the file. The name for each servlet must be unique across the deployment descriptor.
    `jsp`
      Declares a custom mapping to a JSP file from the WAR root. The servlet element for the JSP can contain initialization parameters.
      Note that App Engine supports automatic compilation and URL mapping for JSPs. A JSP file in the application's WAR (outside of WEB-INF/), whose filename ends in .jsp, is compiled into a servlet class automatically, and mapped to the URL path equivalent to the path to the JSP file from the WAR root. For example, if an app has a JSP file named start.jsp in a subdirectory named register/ in its WAR, App Engine compiles it and maps it to the URL path /register/start.jsp. You don't need to use this element unless you want more control over how the JSP is mapped to a URL.
    The following example demonstrates a handler mapping containing all of these elements:

        handlers:
          - url: /red/*
             servlet: mysite.server.TeamServlet
             init_params:
               teamColor: red
               bgColor: "#CC0000"
             name: redteam
          - url: /blue/*
             servlet: mysite.server.TeamServlet
             init_params:
               teamColor: blue
               bgColor: "#0000CC"
             name: blueteam
          - url: /register/*
             jsp: /register/start.jsp
          - url: *.special
             filter: mysite.server.LogFilterImpl
             init_params:
               logType: special

threadsafe

  Configures your application to use concurrent requests.

      threadsafe: [true | false]

  Note: The `threadsafe` directive is required for Python 2.7 applications.

## Static Files and Resource Files

Many web applications have files that are served directly to the user's browser, such as images, CSS style sheets, or browser JavaScript code. These are known as static files because they do not change, and can benefit from web servers dedicated just to static content. App Engine serves static files from dedicated servers and caches that are separate from the application servers.

Files that are accessible by the application code using the filesystem are called resource files. These files are stored on the application servers with the app.

By default, all files in the WAR are treated as both static files and resource files, except for JSP files, which are compiled into servlet classes and mapped to URL paths, and files in the `WEB-INF/` directory, which are never served as static files and always available to the app as resource files.

You can adjust which files are considered static files and which are considered resource files using elements in the `app.yaml` file. The `static_files` element specifies patterns that match file paths to include and exclude from the list of static files, overriding or amending the default behavior. Similarly, the `resource_files` element specifies which files are considered resource files.

### Including and Excluding Files

Path patterns are specified using zero or more `include` and `exclude` elements. In a pattern, `*` represents zero or more of any character in a file or directory name, and `**` represents zero or more directories in a path.

An `include` element overrides the default behavior of including all files. An `exclude` element applies after all `include` patterns (as well as the default if no explicit `include` is provided).

The following example demonstrates how to designate all `.png` files as static files (except those in the `data/` directory and all of its subdirectories):

    static_files:
      - include: /**.png
      - exclude: /data/**.png

Similarly, the following sample demonstrates how to designate all `.xml` files as resource files (except those in the `feeds/` directory and all of its subdirectories):

    resource_files:
      - include: /**.xml
      - exclude: /feeds/**.xml

### Setting the Browser Cache Expiration

You can specify a browser cache expiration time for static files. To do so, provide an `expiration` attribute to `static_files include ...`. The value is a string of numbers and units, separated by spaces, where units can be `d` for days, `h` for hours, `m` for minutes, and `s` for seconds. For example, `"4d 5h"` sets cache expiration to 4 days and 5 hours after the file is first loaded by the browser. If the expiration time is omitted, the production server defaults to 10 minutes.

    static_files:
      - include: /**.png
        expiration: 4d 5h

### Changing the MIME Type for Static Files

By default, static files are served using a MIME type selected based on the filename extension. You can associate custom MIME types with filename extensions for static files in web.xml using `mime_mapping` elements.

### Changing the Root Directory

Static files are served from the `public_root` directory. For the `java` runtime, this defaults to `/`. The following example changes public root from `/static/` to `/`, such that the application file `/static/index.html` is served as `/index.html`:

    public_root: /static

## System Properties, Environment Variables, and Context Parameters

The `app.yaml` file can define system properties, environment variables, and context parameters that are set when the application is running.

    system_properties:
      myapp.maximum-message-length: 140
      myapp.notify-every-n-signups: 1000
      myapp.notify-url: http://www.example.com/signupnotify
    env_variables:
      DEFAULT_ENCODING: UTF-8
    context_params:
      rack.env: production

## Servlet Context Listeners

The `listeners` element maps a servlet context listener to the specified URL, allowing you to set up a static state independent of your various servlets. Note that App Engine does not implement the `contextDestroyed` aspect of the listener.

    listeners:
       - com.example.MyListener
       - com.example.MyOtherListener

## Secure URLs

Google App Engine supports secure connections via HTTPS for URLs using the *.appspot.com domain. When a request accesses a URL using HTTPS, and that URL is configured to use HTTPS in the `app.yaml` file, both the request data and the response data are encrypted by the sender before they are transmitted, and decrypted by the recipient after they are received. Secure connections are useful for protecting customer data, such as contact information, passwords, and private messages.

Warning: Google Apps domains do not currently support HTTPS. HTTPS support is limited to apps accessed via *.appspot.com domains. Accessing an HTTPS URL on a Google Apps domain returns a "host not found" error, and accessing a URL whose handler only accepts HTTPS (see below) using HTTP returns an HTTP 403 "Forbidden" error. You can link to an HTTPS URL with the *.appspot.com domain for secure features, and use the Apps domain and HTTP for the rest of the site.

To declare a secure URL, specify the `secure` element. It has 2 possible values:

`optional`
  Both HTTP and HTTPS requests with URLs that match the handler succeed without redirects. The application can examine the request to determine which protocol was used, and respond accordingly. This is the default when secure is not provided for a handler.
`always`
  Requests for a URL that match this handler that do not use HTTPS are automatically redirected to the HTTPS URL with the same path. Query parameters are preserved for the redirect.

Any URL handler can use the `secure` element.

The following example shows you how to configure a URL to accept secure connections:

    handlers:

    - url: /youraccount/*
      login: required
      secure: always

To disallow the use of HTTPS for the application, use `ssl_enabled` as follows:

    ssl_enabled: false

There is no way to disallow HTTPS for some URL paths and not others in the Java runtime environment. The development web server does not support HTTPS connections. It ignores the secure parameter, so paths intended for use with HTTPS can be tested using regular HTTP connections to the development web server.

When you test your app's HTTPS handlers using the versioned appspot.com URL, such as `https://1.latest.your_app_id.appspot.com/`, your browser warns you that the HTTPS certificate was not signed for that specific domain path. If you accept the certificate for that domain, pages will load successfully. Users will not see the certificate warning when accessing `https://your_app_id.appspot.com/`.

You can also use an alternate form of the versioned appspot.com URL designed to avoid this problem by replacing the periods separating the subdomain components with the string "`-dot-`". For instance, the previous example could be accessed without a certificate warning at `https://1-dot-latest-dot-your_app_id.appspot.com/`.

Google Accounts sign-in and sign-out always use a secure connection, unrelated to how the application's URLs are configured.

## Required Login or Administrator Status

Any URL handler can use a `login` setting to restrict access only to visitors who have signed in, or who are administrators. This includes handlers that specify a servlet or those that simply add login restrictions to a URL matching another handler.

When a URL handler with a `login` setting matches a URL, the handler first checks whether the user has signed in to the application using its authentication option. If not, by default, the handler redirects the user to the Google sign-in page (or `/_ah/login_required` for applications using OpenID authentication). The handler then redirects the user back to the application URL after they sign in.

You can configure the `login:` setting to simply reject requests for a handler from users who are not properly authenticated, instead of redirecting the user to the sign-in page. `login:` has two possible values:

`required`
  The handler proceeds normally once the user has signed in.
`admin`
  Once the user has signed in, the handler checks whether the user is an administrator for the application. If not, the user receives an error message. If the user is an administrator, the handler proceeds.

If an application needs different behavior, the application can implement the user handling itself. See Users API for more information.

The following example requires a login for the `/profile/` directory and an admin login for the `AdminServlet in the` `/admin/` directory:

    handlers:

    - url: /profile/*
      login: required

    - url: /admin/*
      servlet: com.example.AdminServlet
      login: admin

## The Welcome File List

When the URLs for your site represent paths to static files or JSPs in your WAR, it is often a good idea for paths to directories to do something useful as well.

A user visiting the URL path `/help/accounts/password.jsp` for information on account passwords may try to visit `/help/accounts/` to find a page introducing the account system documentation. The deployment descriptor can specify a list of filenames that the server should try when the user accesses a path that represents a WAR subdirectory (that is not already explicitly mapped to a servlet). The servlet standard calls this the "welcome file list."

For example, if the user accesses the URL path `/help/accounts/`, the following `welcome_file` list in `app.yaml` tells the server to check for `help/accounts/index.jsp` and `help/accounts/index.html` before reporting that the URL does not exist:

    welcome_files:
      - index.jsp
      - index.html

## Reserved URLs

App Engine reserves several URL paths for features or administrative purposes. Script handler and static file handler paths can never match these paths.

The following URL paths are reserved:

- `/_ah/`
- `/form`

## Inbound Services

Before an application can receive email or XMPP messages, the application must be configured to enable the service. You enable the service for a Java app by including an `inbound_services` section in `app.yaml`.

To enable incoming email and XMPP messages, add the following to `app.yaml`:

    inbound_services:
    - xmpp_message
    - mail

### Warmup Requests

App Engine frequently needs to load application code into a fresh instance. This happens when you redeploy the application, when the load pattern has increased beyond the capacity of the current instances, or simply due to maintenance or repairs of the underlying infrastructure or physical hardware.

Loading new application code on a fresh instance can result in loading requests. Loading requests can result in increased request latency for your users, but you can avoid this latency using warmup requests. Warmup requests load application code into a new instance before any live requests reach that instance.

App Engine attempts to detect when your application needs a new instance, and (assuming that warmup requests are enabled for your application) initiates a warmup request to initialize the new instance. However, these detection attempts do not work in every case. As a result, you may encounter loading requests, even if warmup requests are enabled in your app. For example, if your app is serving no traffic, the first request to the app will always be a loading request, not a warmup request.

Warmup requests use instance hours like any other request to your App Engine application. In most cases, you won't notice an increase in instance hours, since your application is simply initializing in a warmup request instead of a loading request. Your instance hour usage will likely increase if you decide to do more work (such as precaching) during a warmup request. If you set a minimum number of idle instance, you may encounter warmup requests when those instances first start, but they will remain available after that time.

In Java applications configured with `app.yaml`, warmup requests are disabled by default. To enable them, add the `warmup` argument to the `inbound_services` directive:

    inbound_services:
    - warmup

## Administration Console Custom Pages

You can configure your application so that administrator-only pages appear in the Administration Console. The Administration Console includes the name of the page in its sidebar, and displays the page in an HTML iframe. To add a page to the Administration Console, add an `admin_console`: section in your app's `app.yaml` file:

    admin_console:
      pages:
      - name: Blog Comment Admin
        url: /blog/admin/comments
      - name: Create a Blog Post
        url: /blog/admin/newentry

This has an inner `pages:` section, with an entry for each page. The name appears in the Administration Console navigation, and the url is the URL path to the page.

At this time, page names must contain only characters in the ASCII character set.

You can use configuration to restrict access to custom administration pages to only users that are administrators of the app. See Required Login or Administrator Status.

## Enabling Sessions

App Engine includes an implementation of sessions, using the servlet session interface. The implementation stores session data in the App Engine datastore for persistence, and also uses memcache for speed. As with most other servlet containers, the session attributes that are set with `session.setAttribute()` during the request are saved to the datastore at the end of the request.

This feature is turned off by default. To turn it on, add the following to `app.yaml`:

        sessions_enabled: true

The implementation creates datastore entities of the kind `_ah_SESSION`, and memcache entries using keys with a prefix of `_ahs`.

Note: Because App Engine stores session data in the datastore and memcache, all values stored in the session must implement the `java.io.Serializable` interface.

## Disabling Precompilation

App Engine uses a "precompilation" process with the Java bytecode of an app to enhance the performance of the app in the Java runtime environment. Precompiled code functions identically to the original bytecode.

To turn off precompilation, add the following to your `app.yaml` file:

      precompilation_enabled: false

## Custom XML Output

If you need to use features of the Java web.xml which are not directly supported in `app.yaml`, you can include a block of XML that will be included directly into web.xml

    web_xml: |
      <error-page>
        <error-code>500</error-code>
        <location>/errors/servererror.jsp</location>
      </error-page>

## Custom Error Responses

When certain errors occur, App Engine serves a generic error page. You can configure your app to serve a custom static file instead of these generic error pages. You can set up different static files to be served for each supported error code by specifying the files in your app's `app.yaml` file.

To serve custom error pages, add an `error_handlers` section to your `app.yaml`, as in this example:

    error_handlers:
      - file: default_error.html

      - error_code: over_quota
        file: over_quota.html

Warning!: Make sure that the path to the error response file does not overlap with static file handler paths.

Each `file` entry indicates a static file that should be served in place of the generic error response. The `error_code` indicates which error code should cause the associated file to be served. Supported error codes are as follows:

- `over_quota`, which indicates the app has exceeded a resource quota;
- `dos_api_denial`, which is served to any client blocked by your app's DoS Protection configuration;
- `timeout`, served if a deadline is reached before there is a response from your app.

The `error_code` is optional; if it's not specified, the given file is the default error response for your app.

You can optionally specify a `mime_type` to use when serving the custom error. See http://www.iana.org/assignments/media-types/ for a complete list of MIME types.