開始使用:處理表單資料

瞭解如何建立使用 HTTP POST 方法的 HTML 表單,以將使用者提供的資料提交至在 App Engine 上執行的 Java Servlet。

事前準備

設定開發環境及建立 App Engine 專案

建立表單

使用 JavaServer Pages (JSP) 建立 HTML 表單。

下方的 JSP 程式碼可產生用於建立網誌文章的表單。這個範本會使用三個文字輸入欄位 titleauthorcontent,並且有 Save 按鈕,可將資料提交至 servlet:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<div class="container">
  <h2>
    Create a new blog post
  </h2>

  <form method="POST" action="/create">

    <div>
      <label for="title">Title</label>
      <input type="text" name="title" id="title" size="40" value="${fn:escapeXml(blog.title)}" class="form-control" />
    </div>

    <div>
      <label for="author">Author</label>
      <input type="text" name="author" id="author" size="40" value="${fn:escapeXml(blog.author)}" class="form-control" />
    </div>

    <div>
      <label for="description">Post content</label>
      <textarea name="description" id="description" rows="10" cols="50" class="form-control">${fn:escapeXml(blog.content)}</textarea>
    </div>

    <button type="submit">Save</button>
  </form>
</div>

這份表單會將表單資料傳送至 /create 網址的處理常式。您應使用 JSP 的 escapeXml 功能來因應跨網站指令碼 (XSS) 攻擊,如程式碼片段所示。後續章節將提供建立表單處理常式的操作說明。

處理表單資料

使用者提交表單資料之後,資料會交由表單處理常式處理。在下方程式碼片段中,表單處理程序是名為 createBlogPost 的 Servlet:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
@WebServlet(name = "createBlogPost", value="/create")
public class createBlogPost extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    PrintWriter out = resp.getWriter();

    out.println(
        "Article with the title: " + req.getParameter("title") + " by "
            + req.getParameter("author") + " and the content: "
            + req.getParameter("description") + " added.");
  }
}

請注意註解 @WebServlet(name = "createBlogPost", value="/create"),它會將 Servlet 對應至處理要求的 URI:/create。對於熟悉 App Engine Java 7 執行階段的開發人員,此註解會取代先前在 web.xml 檔案中建立的對應項目。

部署至 App Engine

您可以透過 Maven 將應用程式部署至 App Engine。

請前往專案的根目錄,並輸入以下內容:

mvn package appengine:deploy -Dapp.deploy.projectId=PROJECT_ID

PROJECT_ID 替換為您的 Google Cloud 專案 ID。如果 pom.xml 檔案已指定專案 ID,您就不需要在執行的指令中加入 -Dapp.deploy.projectId 屬性。

請在 Maven 部署應用程式後輸入下列指令,以便在新的應用程式中自動開啟網路瀏覽器分頁:

gcloud app browse

後續步驟

如要進一步處理使用者資料,您可以使用 Cloud SQL、Cloud Datastore 或 Cloud Storage 來儲存資料: