这是用户在 2024-9-13 17:26 为 https://jakarta.ee/learn/docs/jakartaee-tutorial/current/web/webapp/webapp.html#_jakarta_servlet_dep... 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?
Cookie settings

Getting Started with Web Applications

The Web Profile allows you to get started developing Java web applications, which typically use Jakarta Servlet API as corner stone.
网络配置文件允许您开始开发 Java 网络应用程序,这些程序通常使用 Jakarta Servlet API 作为基石。

Web Applications

A web application, also known as a web app, is a software application that runs on one or more web servers. It is typically accessed through a web browser over a network, such as the Internet. The advantage over desktop and mobile applications is being platform-independent, as it can be accessed and used on different devices. Web applications are of the following types:
网络应用程序又称网络应用,是在一个或多个网络服务器上运行的软件应用程序。它通常通过网络浏览器在互联网等网络上访问。与桌面和移动应用程序相比,网络应用程序的优势在于不受平台限制,可以在不同的设备上访问和使用。网络应用程序有以下几种类型:

Presentation-oriented

A presentation-oriented web application (also called a "website") generates dynamic web pages in response to HTTP requests. The response is usually represented as a HTML document along with assets, such as Cascading Style Sheets (CSS), JavaScript (JS) and images. Presentation-oriented applications are often directly used by humans. Development of presentation-oriented web applications is covered in "Building Web Services with Jakarta XML Web Services" (available in a previous version of the tutorial↗) through Jakarta Servlet Technology
面向演示的网络应用程序(也称为 "网站")根据 HTTP 请求生成动态网页。响应通常表现为 HTML 文档以及层叠样式表(CSS)、JavaScript(JS)和图像等资产。面向演示的应用程序通常由人类直接使用。通过 Jakarta Servlet 技术,"使用 Jakarta XML Web 服务构建 Web 服务"(可在本教程的上一版本中查阅)中介绍了面向演示的 Web 应用程序的开发。

Service-oriented

A service-oriented web application (also called a "service") generates dynamic data structures in response to HTTP requests. The response is usually represented as a JSON object or as a XML document or even as plain text. Service-oriented applications are often directly used by presentation-oriented web applications or other service-oriented applications. Development of service-oriented web applications is covered in "Building Web Services with Jakarta XML Web Services" (available in a previous version of the tutorial↗)
面向服务的网络应用程序(也称为 "服务")会根据 HTTP 请求生成动态数据结构。响应通常表示为 JSON 对象或 XML 文档,甚至是纯文本。面向服务的应用程序通常直接用于面向表现的网络应用程序或其他面向服务的应用程序。面向服务的网络应用程序的开发在 "使用 Jakarta XML 网络服务构建网络服务"(可在本教程的上一版本中查阅)中有所介绍。

In the Jakarta EE platform, web applications are represented by web components as seen in Jakarta Web Application Request Handling. A web component can be represented by Jakarta Servlet, Jakarta Faces or Jakarta REST.
在 Jakarta EE 平台中,网络应用由网络组件表示,如 Jakarta 网络应用请求处理中所示。网络组件可以用 Jakarta Servlet、Jakarta Faces 或 Jakarta REST 表示。

Diagram of web application request handling. Clients and servlets communicate using HttpServletRequest and HttpServletResponse.
Figure 1. Jakarta Web Application Request Handling
图 1.Jakarta 网络应用程序请求处理
  1. The client sends an HTTP request to the web server.

  2. The web server module that supports Jakarta Servlet-based web components is called a servlet container.
    支持基于 Jakarta Servlet 的网络组件的网络服务器模块称为 servlet 容器。

  3. The servlet container converts the HTTP request into an HttpServletRequest object and prepares the HttpServletResponse object.
    servlet 容器会将 HTTP 请求转换为 HttpServletRequest 对象,并准备好 HttpServletResponse 对象。

  4. These objects are delivered to a web component, which can interact with beans or a database to generate dynamic content.
    这些对象被传送到网络组件,网络组件可与豆类或数据库交互,生成动态内容。

  5. The web component can fill the HttpServletResponse object with the generated dynamic content or can pass the object to another web component to fill it.
    网络组件可以用生成的动态内容填充 HttpServletResponse 对象,也可以将该对象传递给其他网络组件进行填充。

  6. The servlet container ultimately converts the HttpServletResponse object to an HTTP response and the web server returns it to the client.
    servlet 容器最终会将 HttpServletResponse 对象转换为 HTTP 响应,然后由网络服务器返回给客户端。

Jakarta Servlet can be used to build both presentation and service-oriented web applications. It intends to reduce the boilerplate code needed to convert the HTTP request into a Java object and to offer a Java object as an HTTP response, and to manage all the lifecycle around them.
Jakarta Servlet 可用于构建面向表现和面向服务的网络应用程序。它旨在减少将 HTTP 请求转换为 Java 对象和将 Java 对象作为 HTTP 响应所需的模板代码,并管理围绕它们的所有生命周期。

Jakarta Faces is a component-based MVC framework that can be executed on a servlet container and act as a presentation-oriented web application. It intends to reduce the boilerplate code needed to collect the request parameters, convert and validate them, update bean properties with them, invoke bean methods, and generate HTML output as response. It is designed to run in servlet and non-servlet environments such as a portlet container.[1]
Jakarta Faces 是一个基于组件的 MVC 框架,可以在 servlet 容器上执行,并充当面向表现的网络应用程序。它旨在减少收集请求参数、转换和验证这些参数、使用这些参数更新 Bean 属性、调用 Bean 方法以及生成 HTML 输出作为响应所需的模板代码。它设计用于在 servlet 和非 servlet 环境(如 portlet 容器)中运行。 [1]

Jakarta REST is a RESTful web service framework that can be executed on a servlet container and act as a service-oriented web application. It intends to reduce the boilerplate code needed to convert the request parameters to a bean and further convert it to the desired response such as JSON or XML. It is designed to run in servlet and non-servlet environments such as a microservice.[2]
Jakarta REST 是一个 RESTful 网络服务框架,可在 servlet 容器上执行,并作为面向服务的网络应用程序。它旨在减少将请求参数转换为 bean 并进一步转换为所需响应(如 JSON 或 XML)所需的模板代码。它设计用于在 servlet 和非 servlet 环境(如微服务)中运行。 [2]

A servlet container can be part of a Jakarta runtime such as an application server. Certain aspects of web component behavior can be configured when the web application is installed, or deployed, to a servlet container. The configuration information can be specified using annotations or can be maintained in a XML file called a deployment descriptor. A deployment descriptor file must comply to the schema described in the specification associated with the web component. When the same configuration is specified using annotations and in a deployment descriptor file, then the configuration in the deployment descriptor file will always have precedence.
servlet 容器可以是 Jakarta 运行时(如应用服务器)的一部分。当网络应用程序安装或部署到 servlet 容器时,可以对网络组件行为的某些方面进行配置。配置信息可以使用注解指定,也可以保存在称为部署描述符的 XML 文件中。部署描述符文件必须符合与网络组件相关的规范中描述的模式。如果使用注解和在部署描述符文件中指定了相同的配置,那么部署描述符文件中的配置总是优先。

This chapter gives a brief overview of the activities involved in developing Jakarta Servlet-based web applications. It explains how to compile, package, deploy, and run Jakarta Servlet-based web applications in a servlet container.
本章简要介绍了开发基于 Jakarta Servlet 的 Web 应用程序所涉及的活动。它介绍了如何在 servlet 容器中编译、打包、部署和运行基于 Jakarta Servlet 的 Web 应用程序。

The Web Application Archive

A Jakarta Servlet-based web application can contain one or more of the following parts:
基于 Jakarta Servlet 的网络应用可以包含以下一个或多个部分:

  • One or more web components, which can be represented by Jakarta Servlet, Jakarta Faces or Jakarta REST.
    一个或多个网络组件,可以用 Jakarta Servlet、Jakarta Faces 或 Jakarta REST 表示。

  • Assets (also called static resource files), such as Cascading Style Sheets (CSS), JavaScript (JS) and images.
    资产(也称为静态资源文件),如层叠样式表 (CSS)、JavaScript (JS) 和图像。

  • Dependencies (also called helper libraries, third party libraries, "JARs").
    依赖库(也称为辅助库、第三方库、"JAR")。

  • Deployment descriptor files.
    部署描述符文件。

The process for creating, deploying, and executing a Jakarta Servlet-based web application is different from that of Java classes which are packaged and executed as a Java application archive (JAR). It can be summarized as follows:
创建、部署和执行基于 Jakarta Servlet 的网络应用程序的过程不同于将 Java 类打包成 Java 应用程序存档(JAR)并执行的过程。它可以概括如下:

  1. Develop the web component code.
    开发网络组件代码。

  2. Develop the deployment descriptor files, if necessary.
    如有必要,开发部署描述符文件。

  3. Compile the web component code against the libraries of the servlet container and the helper libraries, if any.
    根据 servlet 容器库和辅助库(如有)编译网络组件代码。

  4. Package the compiled code along with helper libraries, assets and deployment descriptor files, if any, into a deployable unit, called a web application archive (WAR).
    将编译后的代码与辅助库、资产和部署描述符文件(如有)打包成一个可部署的单元,称为网络应用程序存档(WAR)。

  5. Deploy the WAR into a servlet container.
    将 WAR 部署到 servlet 容器中。

  6. Run the web application by accessing a URL that references the web component.
    通过访问引用网络组件的 URL 运行网络应用程序。

Developing the web component code and deployment descriptor files is covered in the later chapters. Steps 3 through 6 are expanded on in the following sections and illustrated with two web applications, in Hello World–style. The web applications take a name as an HTTP request parameter, generate the greeting and return it as an HTTP response. This chapter discusses the following simple web applications:
开发网络组件代码和部署描述符文件将在后面的章节中介绍。下文将对步骤 3 至 6 进行扩展,并以 Hello World 风格的两个网络应用程序为例进行说明。这些网络应用程序将名称作为 HTTP 请求参数,生成问候语并将其作为 HTTP 响应返回。本章将讨论以下简单的网络应用程序:

  • hello-servlet, a Jakarta Servlet-based service-oriented web application
    0#,一个基于 Jakarta Servlet 的面向服务的网络应用程序

  • hello-faces, a Jakarta Faces-based presentation-oriented web application
    0#,一个基于 Jakarta Faces 的面向演示的网络应用程序

They are used to illustrate tasks involved in compiling, packaging, deploying, and running a Jakarta Servlet-based web application that contains web component code.
它们用于说明编译、打包、部署和运行包含网络组件代码的基于 Jakarta Servlet 的网络应用程序所涉及的任务。

Building, Deploying and Running The Example Projects
构建、部署和运行示例项目

This describes steps 3 through 6. You need Maven and a servlet container.
本文将介绍第 3 步至第 6 步。您需要 Maven 和 servlet 容器。

Building The Example Projects

This describes steps 3 and 4. Maven is used to build the example projects. Download and install it as per instructions in maven.apache.org. A Maven WAR project has the following basic structure; not all mentioned resources are required, only the pom.xml is required and the rest is optional:
这里介绍步骤 3 和 4。Maven 用于构建示例项目。请按照 maven.apache.org 中的说明下载并安装。Maven WAR 项目的基本结构如下;并非所有提及的资源都是必需的,只有 pom.xml 是必需的,其余都是可选的:

 |-- src
 |    `-- main
 |         |-- java
 |         |    `-- com
 |         |         `-- example
 |         |              |-- controller
 |         |              |    `-- Servlet.java
 |         |              `-- model
 |         |                   `-- Bean.java
 |         |-- resources
 |         |    `-- com
 |         |         `-- example
 |         |              `-- i18n
 |         |                   |-- text.properties
 |         |                   |-- text_en.properties
 |         |                   `-- text_es.properties
 |         `-- webapp
 |              |-- META-INF
 |              |    `-- MANIFEST.MF
 |              |-- resources
 |              |    |-- css
 |              |    |    `-- style.css
 |              |    |-- img
 |              |    |    `-- logo.svg
 |              |    `-- js
 |              |         `-- script.js
 |              |-- WEB-INF
 |              |    |-- beans.xml
 |              |    |-- faces-config.xml
 |              |    `-- web.xml
 |              |-- favicon.ico
 |              `-- index.xhtml
 `-- pom.xml
asciidoc

In a terminal window, go to the folder containing the pom.xml and execute the following command:
在终端窗口中,转到包含 pom.xml 的文件夹,执行以下命令:

mvn install
shell

This command compiles and packages the code as described in steps 3 and 4. After the build, the resulting WAR file will be present in the automatically created target folder. The WAR file is recognizable by having the .war extension.
该命令将按照步骤 3 和 4 所述对代码进行编译和打包。编译完成后,生成的 WAR 文件将出现在自动创建的 target 文件夹中。WAR 文件的扩展名为 .war ,因此可以识别。

Deploying The Example Projects

This describes step 5. You need at least a servlet container in order to deploy a WAR file. The Jakarta EE Compatible Products page lists several Jakarta runtimes having a servlet container. At least those compatible with "Web Profile" and "Jakarta EE Platform" have a servlet container. Examples are Eclipse GlassFish, IBM Open Liberty and Red Hat WildFly. They are available in both "Web Profile" and "Jakarta EE Platform" flavors.
这里介绍步骤 5。要部署 WAR 文件,至少需要一个 servlet 容器。Jakarta EE 兼容产品页面列出了几个具有 servlet 容器的 Jakarta 运行时。至少与 "Web Profile "和 "Jakarta EE Platform "兼容的运行时都有一个 servlet 容器。例如 Eclipse GlassFish、IBM Open Liberty 和 Red Hat WildFly。它们有 "Web Profile "和 "Jakarta EE Platform "两种版本。

There are also partial Jakarta runtimes having a servlet container. Partial as in, they do not fully implement "Web Profile". One example is Apache Tomcat. It does implement Jakarta Servlet, Jakarta Pages, Jakarta Expression Language, Jakarta WebSocket, and Jakarta Security. But it does not implement Jakarta REST, Jakarta CDI, Jakarta Faces nor Jakarta Tags.
也有部分 Jakarta 运行时具有 servlet 容器。部分运行时没有完全实现 "Web Profile"。Apache Tomcat 就是一个例子。它实现了 Jakarta Servlet、Jakarta Pages、Jakarta Expression Language、Jakarta WebSocket 和 Jakarta Security。但它没有实现 Jakarta REST、Jakarta CDI、Jakarta Faces 或 Jakarta Tags。

Deploying a WAR file is generally done by placing the WAR file in the runtime-specific folder dedicated for (automatic) deployments. The exact location depends on the runtime used:
部署 WAR 文件时,通常是将 WAR 文件放到运行时专用文件夹中,以便进行(自动)部署。具体位置取决于所使用的运行时:

  • In case of Eclipse GlassFish that’s the glassfish/domains/domain1/autodeploy folder.
    如果是 Eclipse GlassFish,则是 glassfish/domains/domain1/autodeploy 文件夹。

  • In case of IBM Open Liberty that’s the config/dropins folder.
    如果是 IBM Open Liberty,则是 config/dropins 文件夹。

  • In case of Red Hat WildFly that’s the standalone/deployments folder.
    在 Red Hat WildFly 中,这是 standalone/deployments 文件夹。

  • In case of Apache Tomcat that’s the webapps folder.
    如果是 Apache Tomcat,则是 webapps 文件夹。

Refer to the documentation for your runtime for the most recent information.
有关最新信息,请参阅运行时的文档。

Undeploying a WAR file is generally done by removing the WAR file from the folder.
取消部署 WAR 文件通常是通过从文件夹中删除 WAR 文件来完成的。

Some runtimes offer a graphical user interface (GUI) for administration tasks such as selecting, uploading and a deploying a WAR file. For this you’ll need to start the server first and then open a specific URL in your web browser representing the location of the admin console:
有些运行时提供图形用户界面(GUI),用于管理任务,如选择、上传和部署 WAR 文件。为此,您需要先启动服务器,然后在网络浏览器中打开代表管理控制台位置的特定 URL:

Refer to the documentation for your runtime for the most recent information.
有关最新信息,请参阅运行时的文档。

You can also use an integrated development environment (IDE) to manage runtimes and deployments. Examples are Eclipse IDE, IntelliJ IDEA and Apache NetBeans. They can also automatically build the projects for you.
您还可以使用集成开发环境(IDE)来管理运行和部署。例如 Eclipse IDE、IntelliJ IDEA 和 Apache NetBeans。它们还可以为你自动构建项目。

Running The Example Projects
运行示例项目

This describes step 6. You’ll need to start the server first and then open a specific URL in your web browser representing the location of the WAR deployment. By default, the URL has the following form:
这里描述的是第 6 步。您需要先启动服务器,然后在网络浏览器中打开代表 WAR 部署位置的特定 URL。默认情况下,URL 的形式如下:

http(s)://host:port/context-path
asciidoc

By default, the context-path is represented by the base file name of the WAR file, without the extension. If there is no web component listening on the root of the context path, then you could face an HTTP 404 'Not Found' error page. In that case you would need to use a more specific URL, depending on the configuration of the desired web component. This will be detailed in Mapping URLs to Web Components.
默认情况下, context-path 用 WAR 文件的基本文件名表示,不带扩展名。如果上下文路径的根目录下没有网络组件监听,则可能会出现 HTTP 404 "未找到 "错误页面。在这种情况下,你需要根据所需网络组件的配置,使用一个更具体的 URL。这将在 URL 与网络组件的映射中详细说明。

Hello World Web Application Using Jakarta Servlet

The hello-servlet application is a web application that uses Jakarta Servlet take a name as an HTTP request parameter, generate the greeting and return it as an HTTP response. As a service-oriented web application, the response is in this minimal example represented as plain text.
hello-servlet 应用程序是一个使用 Jakarta Servlet 的网络应用程序,它将名称作为 HTTP 请求参数,生成问候语并作为 HTTP 响应返回。作为一个面向服务的网络应用程序,本示例中的响应以纯文本形式表示。

The source code for this application is in the jakartaee-examples/tutorial/web/servlet/hello-servlet/ directory.
此应用程序的源代码位于 jakartaee-examples/tutorial/web/servlet/hello-servlet/ 目录中。

The Servlet

In a typical Jakarta Servlet-based web application, the class must extend jakarta.servlet.http.HttpServlet and override one of the doXxx() methods where Xxx represents the HTTP method of interest. Such a class is in the Jakarta Servlet world called a Servlet.
在典型的基于 Jakarta Servlet 的 Web 应用程序中,类必须扩展 jakarta.servlet.http.HttpServlet 并覆盖 doXxx() 方法之一,其中 Xxx 代表感兴趣的 HTTP 方法。在 Jakarta Servlet 的世界里,这样的类被称为 Servlet。

For this Hello World web application, the src/main/java/jakarta/tutorial/web/servlet/Greeting.java servlet listens on HTTP GET requests and extracts the name request parameter as input and creates the greeting as output.
在这个 Hello World 网络应用程序中, src/main/java/jakarta/tutorial/web/servlet/Greeting.java 服务程序监听 HTTP GET 请求,提取 name 请求参数作为输入,并创建 greeting 作为输出。

package jakarta.tutorial.web.servlet;

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/greeting")
public class Greeting extends HttpServlet {

    @Override
    public void doGet
        (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        var name = request.getParameter("name");

        if (name == null || name.isBlank()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        var greeting = "Hello, " + name + "!";

        response.setContentType("text/plain");
        response.getWriter().write(greeting);
    }
}
java

Mapping URLs to Web Components
将 URL 映射到网络组件

When the servlet container receives a request, it must determine which web component should handle the request. The servlet container does so by mapping the URL contained in the request to a web component. A URL contains the context path and, optionally, a URL pattern:
当 servlet 容器收到一个请求时,它必须确定由哪个网络组件来处理该请求。为此,Servlet 容器会将请求中包含的 URL 映射到网络组件。URL 包含上下文路径和可选的 URL 模式:

http(s)://host:port/context-path[/url-pattern]
asciidoc

You can set the URL pattern for a servlet by using the @WebServlet annotation in the servlet source file or by using <servlet-mapping> entry in the Jakarta Servlet deployment descriptor file, the src/main/webapp/WEB-INF/web.xml. In the Greeting servlet example the @WebServlet annotation indicates that the URL pattern is /greeting. Therefore, when the servlet is deployed to a local server listening on http://localhost:8080 with the context path set to hello-servlet, it is accessed with the following URL:
您可以通过使用 servlet 源文件中的 @WebServlet 注释或 Jakarta Servlet 部署描述符文件中的 <servlet-mapping> 条目(即 src/main/webapp/WEB-INF/web.xml )来设置 servlet 的 URL 模式。 在 Greeting servlet 示例中, @WebServlet 注释表示 URL 模式为 /greeting 。因此,当 servlet 部署到监听 http://localhost:8080 且上下文路径设置为 hello-servlet 的本地服务器上时,可通过以下 URL 进行访问:

http://localhost:8080/hello-servlet/greeting
asciidoc

The Hello World example will return an HTTP 400 error as response indicating a 'Bad Request'. When specifying the name as a request parameter in the following URL:
Hello World 示例将返回 HTTP 400 错误,表示 "错误请求"。在以下 URL 中指定名称作为请求参数时:

http://localhost:8080/hello-servlet/greeting?name=Duke
asciidoc

Then it will return the response Hello, Duke!.
然后会返回 Hello, Duke!

Running the hello-servlet example application

Build and deploy as instructed in Building, Deploying and Running The Example Projects.

In a web browser, open the following URL:

http://localhost:8080/hello-servlet/greeting?name=Duke
asciidoc

It will return the response Hello, Duke!. You can edit the name parameter into something else to get a different response.

http://localhost:8080/hello-servlet/greeting?name=Joe
asciidoc

This will return the response Hello, Joe!.

Hello World Web Application Using Jakarta Faces

The hello-faces application is a web application that uses Jakarta Faces take a name as an HTTP request parameter, generate the greeting and return it as an HTTP response. As a presentation-oriented web application, the response is represented as a HTML document.

The source code for this application is in the jakartaee-examples/tutorial/web/faces/hello-faces/ directory.

Jakarta Faces is a component-based MVC framework that provides its own servlet as controller (the "C" part of MVC), the FacesServlet. The model and the view are usually provided by you, the web developer.

The Model

In a typical Jakarta Faces application, the model (the "M" part of MVC) is represented by a bean class. Such a bean class is in the Jakarta Faces world called a Backing Bean.

For this Hello World web application, the src/main/java/jakarta/tutorial/web/faces/Hello.java backing bean defines a name property along with a getter and setter, a greeting property along with a getter, and a submit action method which creates the greeting as output-based on name as input.

package jakarta.tutorial.web.faces;

import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Named;

@Named
@RequestScoped
public class Hello {

    private String name;
    private String greeting;

    public void submit() {
        greeting = "Hello, " + name + "!";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGreeting() {
        return greeting;
    }
}
java

Note that a getter is required for output and that a setter is only required for input.

In a typical Jakarta Faces application, CDI is used to manage the backing beans. We’ll briefly go through the CDI annotations that are used here:

  • @Named — gives the backing bean a managed bean name, which is primarily used to reference it in Expression Language (EL). Without any attributes this defaults to the simple class name with the first letter in lowercase. This backing bean will thus be available as a managed bean via #{hello} in EL.

  • @RequestScoped — gives the backing bean a managed bean scope, which essentially represents its lifespan. In this case that lifespan is the duration of an HTTP request. When the HTTP request ends, then the managed bean instance is destroyed.

The View

In a typical Jakarta Faces application, the view (the "V" part of MVC) is represented by a XHTML file. Such a XHTML file is in the Jakarta Faces world called a Facelets File or just Facelet. In Jakarta Faces, the view technology is pluggable and Facelets is used as the default view technology. XHTML markup is being used because it allows the framework to easily use a XML parser to find Jakarta Faces tags of interest and to generate HTML output.

For this Hello World web application, the src/main/webapp/hello.xhtml Facelet defines a form with an input field, a command button and an output field.

<!DOCTYPE html>
<html lang="en"
      xmlns:f="jakarta.faces.core"
      xmlns:h="jakarta.faces.html">
    <h:head>
        <title>Jakarta Faces Hello World</title>
    </h:head>
    <h:body>
        <h1>Hello, what's your name?</h1>
        <h:form>
            <h:inputText value="#{hello.name}" required="true" />
            <h:commandButton value="Submit" action="#{hello.submit}">
                <f:ajax execute="@form" render=":greeting" />
            </h:commandButton>
            <h:messages />
        </h:form>
        <h:outputText id="greeting" value="#{hello.greeting}" />
    </h:body>
</html>
xml

We’ll briefly go through the Jakarta Faces-specific XHTML tags that are used here.

  • <h:head> — generates the HTML <head>. It gives Jakarta Faces the opportunity to automatically include any necessary JS and CSS files in the generated HTML head.

  • <h:body> — generates the HTML <body>. It gives Jakarta Faces the opportunity to automatically include any necessary JS files in the end of the generated HTML body.

  • <h:form> — generates the HTML <form>. It gives Jakarta Faces the opportunity to automatically include a hidden field representing the view state.

  • <h:inputText> — generates the HTML <input>. It gives Jakarta Faces the opportunity to automatically get and set the value as a managed bean property specified in the value attribute, as well as to perform any conversion and validation on it.

  • <h:commandButton> — generates the HTML <input type="submit">. It gives Jakarta Faces the opportunity to automatically invoke the backing bean method specified in the action attribute.

  • <h:messages> — generates the HTML <ul> or <div> or <table> depending on state and configuration. It gives you the opportunity to declare the place where any conversion and validation messages will be displayed.

  • <f:ajax> — generates the necessary JavaScript code for Ajax behavior. If gives you the opportunity to configure the form submit to be performed asynchronously using Ajax.

  • <h:outputText> — generates the HTML <span>. This is the one being updated on completion of the Ajax submit and it will display the current value of the managed bean property specified in the value attribute.

The <h:…​> tags define standard HTML components. The <f:…​> tags define behavior.

The input value is via EL value expression #{hello.name} connected to the name property of the Hello backing bean via its getter and setter. The output value is via EL value expression #{hello.greeting} connected to the greeting property of the Hello backing bean via its getter. The command button is via EL method expression #{hello.submit} connected to the submit method of the Hello backing bean.

Note that for EL value expressions the physical field representing the property doesn’t need to have exactly the same name nor that it needs to exist at all. EL only looks for the getter and setter methods, not for the field.

The Controller

In a typical Jakarta Faces application, the controller (the "C" part of MVC) is registered in the Jakarta Servlet deployment descriptor file, the src/main/webapp/WEB-INF/web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
         version="6.0">
    <servlet>
        <servlet-name>facesServlet</servlet-name>
        <servlet-class>jakarta.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>facesServlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
</web-app>
xml

It basically instructs the servlet container to create an instance of jakarta.faces.webapp.FacesServlet as facesServlet during startup and to execute it when the URL pattern of the HTTP request matches *.xhtml.

Running the hello-faces example application

Build and deploy as instructed in Building, Deploying and Running The Example Projects.

In a web browser, open the following URL:

http://localhost:8080/hello-faces/hello.xhtml
asciidoc

It will show a web page with a form asking for your name. Enter your name in the input field of the form, for example 'Duke', and click Submit. This will show the text Hello, Duke! below the form.

Jakarta Servlet Deployment Descriptor

This section describes the following tasks involved with configuring Jakarta Servlet-based web applications:
本节将介绍配置基于 Jakarta Servlet 的网络应用程序所涉及的以下任务:

  • Preparing deployment descriptor
    准备部署描述符

  • Setting context parameters
    设置上下文参数

  • Declaring welcome files 声明欢迎文件

  • Mapping errors to error screens
    将错误映射到错误屏幕

  • Declaring resource references
    声明资源引用

Preparing Deployment Descriptor
准备部署描述符

The Jakarta Servlet deployment descriptor is represented by the WEB-INF/web.xml file which is in a Maven-based project placed in src/main/webapp folder. It must be a XML file with a <web-app> root element conform the web-app_X_Y.xsd XML schema of the https://jakarta.ee/xml/ns/jakartaee namespace.
Jakarta Servlet 部署描述符由 WEB-INF/web.xml 文件表示,该文件位于 src/main/webapp 文件夹中基于 Maven 的项目中。它必须是一个 XML 文件,其 <web-app> 根元素符合 https://jakarta.ee/xml/ns/jakartaee 命名空间的 web-app_X_Y.xsd XML 架构。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
         version="6.0">

    <!-- Put configuration here -->

</web-app>
xml

Setting Context Parameters

The web components in a web application share an object that represents their application context, the jakarta.servlet.ServletContext. You define context-wide initialization parameters in the web.xml file.
网络应用程序中的网络组件共享一个代表其应用程序上下文的对象,即 jakarta.servlet.ServletContext 。您可以在 web.xml 文件中定义整个上下文的初始化参数。

<context-param>
    <param-name>com.example.THEME</param-name>
    <param-value>blue</param-value>
</context-param>
xml

You can obtain them in application code via getInitParameter(String name) method of the ServletContext instance.
您可以在应用程序代码中通过 ServletContext 实例的 getInitParameter(String name) 方法获取它们。

String theme = servletContext.getInitParameter("com.example.THEME");
java

These context parameters can be used to configure (default) application-wide variables, such as the web application’s project stage, the path to save uploaded files, the path to a more specific configuration file, the maximum size of a cache, the expiration time of a cacheable resource, the name of the tenant/theme/scheme, or even helper library specific parameters, etcetera, but never passwords. It are those variables which you’d normally define as constants in a Java class, but then without the need to recompile Java classes whenever you’d like to edit them.
这些上下文参数可用于配置(默认)应用程序范围内的变量,如网络应用程序的项目阶段、保存上传文件的路径、更具体的配置文件的路径、缓存的最大大小、可缓存资源的过期时间、租户/主题/方案的名称,甚至辅助库的具体参数等,但绝不包括密码。这些变量通常在 Java 类中定义为常量,但在编辑这些变量时无需重新编译 Java 类。

Declaring Welcome Files

The welcome files mechanism allows you to specify a list of files that the servlet container can return as a default resource when any folder is requested which does not map to an existing web component. For example, suppose that you define two welcome files index.xhtml and index.html. So, if for example the / folder is requested, and it does not map to a web component, then it’ll search for /index.xhtml and /index.html files and return the first found one. Or if there is none, then the servlet container will continue to perform the default behavior, which is usually displaying an HTTP 404 error page. Note that this also applies to sub folders, so if for example the /foo folder is requested, then it’ll search for /foo/index.xhtml and /foo/index.html files and return the first found one. You specify welcome files in the web.xml file.
欢迎文件机制允许你指定一个文件列表,当请求的任何文件夹没有映射到现有的网络组件时,Servlet 容器可将其作为默认资源返回。例如,假设您定义了两个欢迎文件 index.xhtmlindex.html 。因此,如果请求 / 文件夹,但它没有映射到网络组件,那么它就会搜索 /index.xhtml/index.html 文件,并返回第一个找到的文件。如果没有找到,那么 servlet 容器将继续执行默认行为,通常是显示 HTTP 404 错误页面。请注意,这也适用于子文件夹,例如,如果请求 /foo 文件夹,那么它将搜索 /foo/index.xhtml/foo/index.html 文件,并返回第一个找到的文件。您可以在 web.xml 文件中指定欢迎文件。

<welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>
xml

A specified welcome file must not have a leading slash (/) as it is interpreted independently of the requested folder.
指定的欢迎文件不能有前导斜线 ( / ) ,因为它的解释与所请求的文件夹无关。

Mapping Errors to Error Pages

When an error occurs during execution of a web application, you can have the application display a specific error page according to the type of error. In particular, you can specify a mapping between the status code returned in an HTTP response or a Java programming language exception returned by any web component and any type of error page. You specify error pages in the web.xml file.
当网络应用程序在执行过程中发生错误时,可以让应用程序根据错误类型显示特定的错误页面。特别是,您可以指定 HTTP 响应中返回的状态代码或任何网络组件返回的 Java 编程语言异常与任何类型的错误页面之间的映射。您可以在 web.xml 文件中指定错误页面。

<error-page>
    <error-code>401</error-code>
    <location>/WEB-INF/error-pages/unauthorized.xhtml</location>
</error-page>
<error-page>
    <error-code>403</error-code>
    <location>/WEB-INF/error-pages/unauthenticated.xhtml</location>
</error-page>
<error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/error-pages/not-found.xhtml</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/error-pages/general-error.html</location>
</error-page>
<error-page>
    <exception-type>jakarta.faces.application.ViewExpiredException</exception-type>
    <location>/WEB-INF/error-pages/view-expired.html</location>
</error-page>
<error-page>
    <!-- No error-code or exception-type, i.e. this will match any other HTTP status than defined above -->
    <location>/WEB-INF/error-pages/unknown-error.html</location>
</error-page>
xml

A specified location must have a leading slash (/) as it is interpreted as an absolute path within the context of the web application deployment. The error page being placed in /WEB-INF folder is not technically required, but it is the best practice as it will prevent the client from being able to request or even bookmark them individually.
指定的位置必须有前导斜线( / ),因为在网络应用程序部署的上下文中,它被解释为绝对路径。技术上并不要求将错误页面放在 /WEB-INF 文件夹中,但这是最好的做法,因为这样可以防止客户端单独请求或甚至将它们添加到书签中。

Declaring Resource References
声明资源引用

If your web application uses external resources, such as data sources or mail sessions, then you can specify it in web.xml and use the @javax.annotation.Resource annotation to inject it into a container-managed object of your web application.
如果您的网络应用程序使用外部资源,如数据源或邮件会话,那么您可以在 web.xml 中指定它,并使用 @javax.annotation.Resource 注解将它注入到网络应用程序的容器管理对象中。

The @Resource annotation can be specified on a class, a method, or a field. The container is responsible for instantiating and injecting references to resources declared by the @Resource annotation in container-managed objects and mapping it to the proper JNDI resources.
@Resource 注解可以在一个类、一个方法或一个字段上指定。容器负责实例化和注入对容器管理对象中由 @Resource 注解声明的资源的引用,并将其映射到适当的 JNDI 资源。

Container-managed objects are primarily those objects which you do not explicitly instantiate yourself as in new ContainerManagedObject() but basically let the container do. For example CDI managed beans in case of a CDI container, and web components in case of a servlet container. CDI managed beans are recognizable as classes having a CDI scope annotation such as @RequestScoped or @Dependent. Web components are recognizable as classes that extend or implement a class or interface of the jakarta.servlet. package, and are registered via an annotation of the jakarta.servlet.annotation. package or an entry in the web.xml file.
容器管理对象主要是指那些您不需要像 new ContainerManagedObject() 中那样显式地实例化自己的对象,而是基本上让容器来实例化的对象。例如,CDI 容器中的 CDI 托管 Bean 和 servlet 容器中的 Web 组件。CDI 托管豆可以识别为具有 CDI 作用域注解(如 @RequestScoped@Dependent )的类。网络组件可识别为扩展或实现 jakarta.servlet. 包的类或接口的类,并通过 jakarta.servlet.annotation. 包的注解或 web.xml 文件中的条目进行注册。

Declaring Data Source References

If your web application uses data sources, then you can specify it in web.xml and use the @Resource annotation to inject it into a container-managed object of your web application as a javax.sql.DataSource instance. The below example specifies a H2 data source listening on JNDI resource name of java:global/YourDataSourceName, using the org.h2.jdbcx.JdbcDataSource as javax.sql.DataSource implementation.
如果您的网络应用程序使用数据源,那么您可以在 web.xml 中指定数据源,并使用 @Resource 注解将其作为 javax.sql.DataSource 实例注入到网络应用程序的容器管理对象中。下面的示例使用 org.h2.jdbcx.JdbcDataSource 作为 javax.sql.DataSource 实现,指定了一个监听 JNDI 资源名 java:global/YourDataSourceName 的 H2 数据源。

<data-source>
    <name>java:global/YourDataSourceName</name>
    <class-name>org.h2.jdbcx.JdbcDataSource</class-name>
    <url>jdbc:h2:mem:test</url>
</data-source>
xml

If you have only one data source reference specified, then you can inject it as a @Resource of javax.sql.DataSource type without an explicit JNDI resource name.
如果只指定了一个数据源引用,则可将其作为 @Resource of javax.sql.DataSource 类型注入,而无需显式 JNDI 资源名。

@Resource
private DataSource dataSource;

public Connection getConnection() {
    return dataSource.getConnection();
}
java

If you have more than one data source reference specified, then you need to explicitly specify the JNDI resource name.
如果指定了多个数据源引用,则需要明确指定 JNDI 资源名称。

@Resource(name="java:global/YourDataSourceName")
private DataSource dataSource;

public Connection getConnection() {
    return dataSource.getConnection();
}
java

Do note that javax.sql.DataSource is not part of Jakarta EE but of Java SE and hence it has still the javax as root package.
请注意, javax.sql.DataSource 并非 Jakarta EE 的一部分,而是 Java SE 的一部分,因此它仍然将 javax 作为根软件包。

Declaring Mail Session References
声明邮件会话引用

If your web application uses mail sessions, then you can specify it in web.xml and use the @Resource annotation to inject it into a container-managed object of your web application as a jakarta.mail.Session instance. The below example specifies a SMTP mail session listening on JNDI name of java:global/YourMailSessionName, using the smtp.example.com host to create jakarta.mail.Session for.
如果您的网络应用程序使用邮件会话,那么您可以在 web.xml 中指定它,并使用 @Resource 注解将它作为 jakarta.mail.Session 实例注入到网络应用程序的容器管理对象中。下面的示例指定了一个 SMTP 邮件会话,监听 JNDI 名称为 java:global/YourMailSessionName ,使用 smtp.example.com 主机创建 jakarta.mail.Session

<mail-session>
    <name>java:global/YourMailSessionName</name>
    <host>smtp.example.com</host>
    <user>user@example.com</user>
</mail-session>
xml

If you have only one mail session reference specified, then you can inject it as a @Resource of jakarta.mail.Session type without an explicit JNDI resource name.
如果只指定了一个邮件会话引用,则可以将其作为 @Resource of jakarta.mail.Session 类型注入,而无需显式 JNDI 资源名。

@Resource
private Session session;

public void sendMail(YourMail mail) throws MessagingException {
    Message message = new MimeMessage(session);
    // ...
}
java

If you have more than one mail session reference specified, then you need to explicitly specify the JNDI resource name.
如果指定了多个邮件会话引用,则需要明确指定 JNDI 资源名称。

@Resource(name="java:global/YourMailSessionName")
private Session session;

public void sendMail(YourMail mail) throws MessagingException {
    Message message = new MimeMessage(session);
    // ...
}
java

Further Information about Web Applications

For more information on web applications, see


1. The portlet container is defined in JSR 286 Portlet specification which is not part of Jakarta EE.
2. Some frameworks use Jakarta REST with non-blocking server such as Eclipse Vert.X or Netty.