Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Este guia mostra como escrever um serviço da Web Java para ser executado no ambiente padrão
do App Engine. Para saber mais sobre o ambiente de execução do Java e como ele funciona, consulte Ambiente de execução do Java.
Faça o download
e instale
o Apache Maven para criar, executar e implantar o aplicativo de exemplo.
Pontos principais
O App Engine inicia seu aplicativo fazendo upload de um aplicativo JAR executável.
Seu aplicativo precisa ter uma classe principal que inicie um servidor da Web que
responda às solicitações HTTP na porta especificada pela variável
de ambiente PORT, normalmente 8080.
Você precisa de um arquivo app.yaml
para implantar seu serviço no App Engine.
O núcleo do serviço da Web é o servidor HTTP. O código de exemplo neste guia
usa o framework Spring Boot
para lidar com solicitações HTTP, mas você está livre para usar um framework da Web de
sua preferência.
Gerar um projeto Spring Boot para Java que use o sistema de compilação do Maven e com
dependências do Spring Web. Para começar, clique neste link:
No Spring Initializer, clique no botão Generate para gerar e fazer o download do seu projeto.
No projeto baixado, edite o arquivo springboot/src/main/java/com/example/appengine/springboot/DemoApplication.java
para adicionar algumas importações Java e um manipulador de saudação REST:
A classe modificada é um controlador que inicia o servidor Tomcat
incorporado do Spring Boot e responde com solicitações GET no caminho raiz ('/') com o texto "Hello world!"
Executar o servidor localmente
Para executar o servidor no local:
Inicie um servidor da Web local usando o plug-in Spring Boot Maven.
A mensagem Hello World do app de amostra é exibida na página. Na janela do terminal, pressione Ctrl+C para sair do servidor da Web.
Crie o arquivo app.yaml.
Para especificar as configurações do aplicativo no ambiente de execução do App Engine:
Crie um arquivo chamado app.yaml no seguinte diretório: springboot/src/main/appengine/
Adicione o seguinte conteúdo ao arquivo:
Java 21
runtime: java21
O arquivo app.yaml também pode especificar configurações de rede, configurações de escalonamento
etc. Para mais informações, consulte a
referência de app.yaml.
Se você usou o link Spring Initializer acima, deve ter uma estrutura de arquivo como a seguinte:
springboot/
pom.xml
src/main/
appengine/
app.yaml
java/com/example/appengine/springboot/
DemoApplication.java
Também é possível adicionar ao pom.xml do projeto o plug-in do Maven que permite a implantação do aplicativo:
Agora que você criou um servidor da Web Java simples com listener na porta
correta e especificou o ambiente de execução em um arquivo app.yaml,
implante o serviço no App Engine.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-19 UTC."],[[["\u003cp\u003eThis guide outlines how to create a Java web service for the App Engine standard environment, starting with a recommendation to consider Cloud Run for new Java web service deployments on Google Cloud.\u003c/p\u003e\n"],["\u003cp\u003eApp Engine requires an executable JAR application with a main class that launches a web server, listening for HTTP requests on the port defined by the PORT environment variable, typically 8080.\u003c/p\u003e\n"],["\u003cp\u003eThe deployment of a web service to App Engine necessitates an \u003ccode\u003eapp.yaml\u003c/code\u003e file for configuration, in addition to listing any dependencies in a \u003ccode\u003epom.xml\u003c/code\u003e file.\u003c/p\u003e\n"],["\u003cp\u003eA sample Spring Boot project is provided as an example, which includes generating the project through Spring Initializr and modifying a specific file, \u003ccode\u003eDemoApplication.java\u003c/code\u003e, to include the code for a Rest controller.\u003c/p\u003e\n"],["\u003cp\u003eAfter creating a web server that listens on the correct port and specifying the runtime environment in \u003ccode\u003eapp.yaml\u003c/code\u003e, the next step is deploying your service to App Engine.\u003c/p\u003e\n"]]],[],null,["# Write your web service\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\n| **Note:** If you are deploying a new Java web service to Google Cloud, we recommend getting started with [Cloud Run](/run/docs/quickstarts/build-and-deploy/deploy-java-service).\n\nThis guide shows how to write a Java web service to run in the App Engine\nstandard environment. To learn more about the Java runtime and how it\nworks, see [Java Runtime Environment](/appengine/docs/standard/java-gen2/runtime).\n\nBefore you begin\n----------------\n\nIf you haven't already:\n\n1. [Install the latest version of the Java Development Kit (JDK)](http://www.oracle.com/technetwork/java/javase/downloads/index.html) for the App Engine runtime version you plan to use.\n2. [Download](https://maven.apache.org/download.cgi) and [install](https://maven.apache.org/install.html) Apache Maven to build, run, and deploy the sample app.\n\nKey points\n----------\n\n- App Engine starts your application by uploading an executable JAR application.\n- Your application must have a main class that starts a web server which responds to HTTP requests on the port specified by the PORT environment variable, typically 8080.\n- You need an [`app.yaml`](/appengine/docs/standard/java-gen2/configuring-your-app-with-app-yaml) file to deploy your service to App Engine.\n- You can use dependencies by listing them in your [`pom.xml`](https://maven.apache.org/pom.html) file. For more information, see [Using Java libraries](/appengine/docs/standard/java-gen2/specifying-dependencies).\n\nCreate a main class\n-------------------\n\nThe core of your web service is the HTTP server. The sample code in this guide\nuses the [Spring Boot](https://spring.io/)\nframework to handle HTTP requests, but you are free to use a web framework of\nyour choice.\n\n1. Generate a Spring Boot project for Java that uses the Maven build system and contains the\n Spring Web dependency. To get started, click the following link:\n\n [Go to Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&packaging=jar&jvmVersion=21&groupId=com.example.appengine&artifactId=springboot&packageName=com.example.appengine.springboot&dependencies=web)\n2. In Spring Initializer, click the **Generate** button to generate and download your project.\n\n3. In the downloaded project, edit the file `springboot/src/main/java/com/example/appengine/springboot/DemoApplication.java`\n to add some java imports and a REST hello handler:\n\n package com.example.appengine.springboot;\n import org.springframework.boot.SpringApplication;\n import org.springframework.boot.autoconfigure.SpringBootApplication;\n import org.springframework.web.bind.annotation.GetMapping;\n import org.springframework.web.bind.annotation.RestController;\n @SpringBootApplication\n @RestController\n public class DemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(DemoApplication.class, args);\n }\n @GetMapping(\"/\")\n public String hello() {\n return \"Hello world!\";\n }\n }\n\n The modified class is a controller that starts Spring Boot's embedded Tomcat\n server and responds to `GET` requests at the root path (`'/'`) with the text \"Hello world!\"\n\nRun the server locally\n----------------------\n\nTo run the server locally:\n\n1. Start a local web server using the Spring Boot Maven plugin.\n\n mvn spring-boot:run\n\n2. In your web browser, enter the following address: \n\n \u003chttp://localhost:8080\u003e\n\nThe **Hello World** message from the sample app displays on the page. In your\nterminal window, press **Ctrl+C** to exit the web server.\n\nCreate the `app.yaml` file\n--------------------------\n\nTo specify settings for your app in the App Engine runtime environment:\n\n1. Create a file named `app.yaml` in the following directory: \n\n `springboot/src/main/appengine/`\n\n2. Add the following contents to the file:\n\n ### Java 21\n\n runtime: java21\n\n The `app.yaml` file can also specify network settings, scaling settings,\n and more. For more information, see the\n [`app.yaml` reference](/appengine/docs/standard/reference/app-yaml).\n\nIf you used the *Spring Initializr* link above, you should now have a file structure like the following:\n\n- `springboot/`\n - `pom.xml`\n - `src/main/`\n - `appengine/`\n - `app.yaml`\n - `java/com/example/appengine/springboot/`\n - `DemoApplication.java`\n\nYou can also add in the project pom.xml the Maven plugin that allows deployment of the application: \n\n \u003cplugin\u003e\n \u003cgroupId\u003ecom.google.cloud.tools\u003c/groupId\u003e\n \u003cartifactId\u003eappengine-maven-plugin\u003c/artifactId\u003e\n \u003cversion\u003e2.8.1\u003c/version\u003e\n \u003cconfiguration\u003e\n \u003cprojectId\u003eYOUR_PROJECT_NAME\u003c/projectId\u003e\n \u003cversion\u003eYOUR_VERSION\u003c/version\u003e\n \u003cpromote\u003efalse\u003c/promote\u003e\n \u003c/configuration\u003e\n \u003c/plugin\u003e\n\nNext steps\n----------\n\nNow that you've created a simple Java web server that listens to the correct\nport and you've specified the runtime in an `app.yaml` file, you're ready to\n[deploy your service on App Engine](/appengine/docs/standard/java-gen2/building-app/deploying-web-service)."]]