Translation Web App Hello World

Translation Web App Hello World

September 27, 2020

example java google-cloud app-engine post fetch translation

This is a web app that uses Google Translate to analyze some text uploaded by the user.

View the code for this project here.

Download the code as a .zip from DownGit here.

text input


pom.xml is a Maven POM file that defines the project.

<project xmlns=""


    <!-- Java 11 -->

    <!-- Project-specific properties -->

    <!-- Java Servlets API -->

    <!-- Google Cloud Translation -->

    <!-- Jetty -->

      <!-- Copy static resources like html files into the output jar file. -->

      <!-- Package everything into a single executable jar file. -->
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <!-- The Cloud Translation library signs its jar, so exclude its signature in the output jar -->

      <!-- App Engine plugin for deploying to the live site. -->


app.yaml is a config file that sets up App Engine. This hello world project only uses a single property that sets the runtime to Java 11.

runtime: java11 is the main class that sets up the server.

package io.happycoding;

import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;

 * Starts up the server, including a DefaultServlet that handles static files,
 * and any servlet classes annotated with the @WebServlet annotation.
public class ServerMain {

  public static void main(String[] args) throws Exception {

    // Create a server that listens on port 8080.
    Server server = new Server(8080);
    WebAppContext webAppContext = new WebAppContext();

    // Load static content from inside the jar file.
    URL webAppDir =

    // Enable annotations so the server sees classes annotated with @WebServlet.
    webAppContext.setConfigurations(new Configuration[]{
      new AnnotationConfiguration(),
      new WebInfConfiguration(),

    // Look for annotations in the classes directory (dev server) and in the
    // jar file (live server)

    // Handle static resources, e.g. html files.
    webAppContext.addServlet(DefaultServlet.class, "/");

    // Start the server! 🚀
    System.out.println("Server started!");

    // Keep the main thread alive while the server is running.
} is a Java servlet that handles the POST request including the text entered by the user, sends the request for translation, and outputs the result.

package io.happycoding.servlets;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TranslationServlet extends HttpServlet {

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Get the request parameters
    String originalText = request.getParameter("text");
    String languageCode = request.getParameter("languageCode");

    // Get the translation
    Translate translate = TranslateOptions.getDefaultInstance().getService();
    Translation translation =
        translate.translate(originalText, Translate.TranslateOption.targetLanguage(languageCode));
    String translatedText = translation.getTranslatedText();

    // Output the translation
    response.setContentType("text/html; charset=UTF-8");


index.html is an HTML file that shows a form, and includes JavaScript that calls the fetch() function to send the user’s input to the server and show the result in the DOM.

<!DOCTYPE html>
    <meta charset="UTF-8">

      function requestTranslation() {
        // Get the user's input from the UI
        const text = document.getElementById('text').value;
        const languageCode = document.getElementById('language').value;

        // Show a placeholder while waiting for the response
        const resultContainer = document.getElementById('result');
        resultContainer.innerText = 'Loading...';

        // Build the request params
        const params = new URLSearchParams();
        params.append('text', text);
        params.append('languageCode', languageCode);

        // Send a POST request to the server
        fetch('/translate', {
          method: 'POST',
          body: params
        // Convert the response to plain text
        .then(response => response.text())
        // Show the translated text in the page
        .then((translatedMessage) => {
          resultContainer.innerText = translatedMessage;

      #text {
        width: 500px;
        height: 125px;

      #language {
        display: block;
        margin-top: 25px;
        margin-bottom: 25px;

    <p>Type a message and select a language, then click submit to translate it.</p>

    <textarea id="text"></textarea>

    <select id="language">
      <option value="en">English</option>
      <option value="zh">Chinese</option>
      <option value="es">Spanish</option>
      <option value="hi">Hindi</option>
      <option value="ar">Arabic</option>

    <button onclick="requestTranslation();">Translate</button>

    <div id="result"></div>

You can run this locally by executing this command:

mvn package exec:java

Then visit http://localhost:8080 in your web browser, and you should see this:

text input

Learn more in these tutorials:

Translation Examples


Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!