Introduction To Play In Java – Java中的游戏简介

最后修改: 2016年 10月 9日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

The purpose of this intro tutorial is to explore the Play Framework and figure out how we can create a web application with it.

这个介绍性教程的目的是探索Play框架,并弄清楚我们如何用它创建一个网络应用。

Play is a high-productivity web application framework for programming languages whose code is compiled and run on the JVM, mainly Java and Scala. It integrates the components and APIs we need for modern web application development.

Play是一个高生产力的网络应用框架,适用于代码在JVM上编译和运行的编程语言,主要是Java和Scala。它集成了我们在现代网络应用程序开发中需要的组件和API。

2. Play Framework Setup

2.播放框架设置

Let’s head over to the Play framework’s official page and download the latest version of the distribution. At the time of this tutorial, the latest is version 2.7.

让我们前往Play框架的官方页面,下载最新版本的发行版。在编写本教程时,最新的版本是2.7。

We’ll download the Play Java Hello World tutorial zip folder and unzip the file into a convenient location. At the root of this folder, we’ll find an sbt executable that we can use to run the application. Alternatively, we can install sbt from their official page.

我们将下载Play Java Hello World教程的压缩文件,并将文件解压到一个方便的位置。在这个文件夹的根部,我们会发现一个sbt可执行文件,我们可以用它来运行这个应用程序。或者,我们可以从他们的官方网页中安装sbt

To use sbt from the downloaded folder, let’s do the following:

要从下载的文件夹中使用sbt,让我们做以下工作。

cd /path/to/folder/
./sbt run

Note that we are running a script in the current directory, hence the use of the ./ syntax.

注意,我们是在当前目录下运行一个脚本,因此要使用./语法。

If we install sbt, then we can use it instead:

如果我们安装了sbt,那么我们可以用它来代替。

cd /path/to/folder/
sbt run

After running this command, we’ll see a statement that says “(Server started, use Enter to stop and go back to the console…)”. This means that our application is ready, therefore we can now head over to http://localhost:9000 where we’ll be presented with a Play Welcome page:

运行这个命令后,我们会看到一条语句:”(服务器已启动,使用回车键停止并回到控制台…)”。这意味着我们的应用程序已经准备好了,因此我们现在可以前往http://localhost:9000,在那里我们将看到一个播放欢迎页面。

play1

3. Anatomy of Play Applications

3.游戏应用的剖析

In this section, we’ll get a better understanding of how a Play application is structured and what each file and directory in that structure is used for.

在本节中,我们将更好地了解Play应用程序的结构,以及该结构中每个文件和目录的用途。

If you would like to challenge yourself to a simple example right away, then skip to the next section.

如果你想马上用一个简单的例子来挑战自己,那么就跳到下一节。

These are the files and folders we find in a typical Play Framework application:

这些是我们在一个典型的Play Framework应用程序中发现的文件和文件夹。

├── app                      → Application sources
│   ├── assets               → Compiled Asset sources
│   │   ├── javascripts      → Typically Coffee Script sources
│   │   └── stylesheets      → Typically LESS CSS sources
│   ├── controllers          → Application controllers
│   ├── models               → Application business layer
│   └── views                → Templates
├── build.sbt                → Application build script
├── conf                     → Configurations files and other non-compiled resources (on classpath)
│   ├── application.conf     → Main configuration file
│   └── routes               → Routes definition
├── dist                     → Arbitrary files to be included in your projects distribution
├── lib                      → Unmanaged libraries dependencies
├── logs                     → Logs folder
│   └── application.log      → Default log file
├── project                  → sbt configuration files
│   ├── build.properties     → Marker for sbt project
│   └── plugins.sbt          → sbt plugins including the declaration for Play itself
├── public                   → Public assets
│   ├── images               → Image files
│   ├── javascripts          → Javascript files
│   └── stylesheets          → CSS files
├── target                   → Generated files
│   ├── resolution-cache     → Information about dependencies
│   ├── scala-2.11            
│   │   ├── api              → Generated API docs
│   │   ├── classes          → Compiled class files
│   │   ├── routes           → Sources generated from routes
│   │   └── twirl            → Sources generated from templates
│   ├── universal            → Application packaging
│   └── web                  → Compiled web assets
└── test                     → source folder for unit or functional tests

3.1. The app Directory

3.1.app目录

This directory contains Java source code, web templates, and compiled assets’ sources — basically, all sources and all executable resources.

这个目录包含了Java源代码、网络模板和编译的资产来源–基本上,所有的来源和所有的可执行资源。

The app directory contains some important subdirectories, each of which packages one part of the MVC architectural pattern:

app目录包含一些重要的子目录,每个目录都打包了MVC架构模式的一个部分。

  • models – this is the application business layer, the files in this package will probably model our database tables and enable us to access the persistence layer
  • views – all HTML templates that can be rendered to the browser are contained this folder
  • controllers – a subdirectory in which we have our controllers. Controllers are Java source files that contain actions to be executed for each API call. Actions are public methods that process HTTP requests and return results of the same as HTTP responses
  • assets– a subdirectory that contains compiled assets such as CSS and javascript. The above naming conventions are flexible, we can create our packages e.g. an app/utils package. We can also customize the package naming app/com/baeldung/controllers

It also contains optional files and directories as needed by the particular application.

它还包含特定应用程序所需的可选文件和目录。

3.2. The public Directory

3.2.公共目录

Resources stored in the public directory are static assets that are served directly by the Web server.

存储在public目录中的资源是静态资产,由Web服务器直接提供。

This directory usually has three subdirectories for images, CSS, and JavaScript files. It’s recommended that we organize the asset files like this for consistency in all Play applications.

这个目录通常有三个子目录,分别是图片、CSS和JavaScript文件。建议我们这样组织资产文件,以便在所有Play应用程序中保持一致。

3.3. The conf Directory

3.3.conf目录

The conf directory contains application configuration files. The application.conf is where we’ll put most of the configuration properties for the Play application. We’ll define endpoints for the app in routes.

conf目录包含应用程序的配置文件。application.conf是我们为Play应用程序放置大部分配置属性的地方。我们将在routes中为应用程序定义端点。

If the application needs any extra configuration files, they should be put in this directory.

如果应用程序需要任何额外的配置文件,它们应该被放在这个目录下。

3.4. The lib Directory

3.4.lib目录

The lib directory is optional and contains unmanaged library dependencies. If we have any jars that are not specified in the build system, we put them in this directory. They’ll be added automatically to the application classpath.

lib目录是可选的,它包含非管理的库依赖。如果我们有任何jars没有在构建系统中指定,我们就把它们放在这个目录中。它们会被自动添加到应用程序的classpath中。

3.5. The build.sbt File

3.5.build.sbt文件

The build.sbt file is the application build script. This is where we list dependencies necessary to run the application, such as test and persistence libraries.

build.sbt文件是应用程序的构建脚本。在这里我们列出了运行应用程序所需的依赖项,如测试和持久性库。

3.6. The project Directory

3.6.项目目录

All the files that configure the build process based on SBT are found in the project directory.

所有基于SBT配置构建过程的文件都可以在project目录下找到。

3.7. The target Directory

3.7.target目录

This directory contains all files generated by the build system — for example, all .class files.

这个目录包含由构建系统生成的所有文件–例如,所有.class文件。

Having seen and explored the directory structure for the Play Framework Hello World example we just downloaded, we can now go through the fundamentals of the framework using an example.

在看到并探索了我们刚刚下载的Play Framework Hello World例子的目录结构后,我们现在可以用一个例子来了解该框架的基本原理。

4. Simple Example

4.简单的例子

In this section, we’ll create a very basic example of a web application. We’ll use this application familiarize ourselves with the fundamentals of the Play framework.

在本节中,我们将创建一个非常基本的Web应用程序的例子。我们将用这个应用来熟悉Play框架的基本原理。

Instead of downloading an example project and building up from it, let’s see another way we can create a Play Framework application, using the sbt new command.

与其下载一个示例项目并从中建立起来,让我们看看另一种创建Play Framework应用程序的方法,使用sbt new命令

Let’s open a command prompt, navigate to our location of choice, and execute the following command:

让我们打开一个命令提示符,导航到我们选择的位置,并执行以下命令。

sbt new playframework/play-java-seed.g8

For this one, we’ll need to have installed sbt already as explained in Section 2.

对于这个问题,我们需要已经安装了sbt,正如第2节中解释的那样。

The above command will prompt us for a name for the project first. Next, it will ask for the domain (in reverse, as is the package naming convention in Java) that will be used for the packages. We press Enter without typing a name if we want to keep the defaults which are given in square brackets.

上面的命令首先会提示我们为项目取一个名字。接下来,它将询问将用于包的域(与Java中的包命名惯例相反)。如果我们想保留方括号中的默认值,就按Enter不输入名字。

The application generated with this command has the same structure as the one generated earlier. We can, therefore, proceed to run the application as we did previously:

用这个命令生成的应用程序的结构与之前生成的应用程序相同。因此,我们可以像之前那样继续运行该应用程序。

cd /path/to/folder/ 
sbt run

The above command, after completion of execution, will spawn a server on port number 9000 to expose our API, which we can access through http://localhost:9000. We should see the message “Welcome to Play” in the browser.

上述命令在执行完成后,将在端口号9000上生成一个服务器,以暴露我们的API,我们可以通过http://localhost:9000访问。我们应该在浏览器中看到 “Welcome to Play “的信息。

Our new API has two endpoints that we can now try out in turn from the browser. The first one – which we have just loaded – is the root endpoint, which loads an index page with the “Welcome to Play!” message.

我们的新API有两个端点,我们现在可以从浏览器中依次尝试。第一个–我们刚刚加载的–是根端点,它加载一个带有 “欢迎来到游戏!”信息的索引页面。

The second one, at http://localhost:9000/assets, is meant for downloading files from the server by adding a file name to the path. We can test this endpoint by getting the favicon.png file, which was downloaded with the application, at http://localhost:9000/assets/images/favicon.png.

第二个,http://localhost:9000/assets,是用来从服务器上下载文件的,在路径中添加一个文件名。我们可以通过获取favicon.png文件来测试这个端点,这个文件是和应用程序一起下载的,地址是http://localhost:9000/assets/images/favicon.png

5. Actions and Controllers

5.行动和控制器

A Java method inside a controller class that processes request parameters and produces a result to be sent to the client is called an action.

控制器类中处理请求参数并产生结果发送给客户端的一个Java方法被称为一个动作。

A controller is a Java class that extends play.mvc.Controller that logically groups together actions that may be related to results they produce for the client.

控制器是一个扩展了play.mvc.Controller的Java类,它在逻辑上将可能与它们为客户产生的结果有关的动作分组。

Let’s now head over to app-parent-dir/app/controllers and pay attention to HomeController.java.

现在让我们前往app-parent-dir/app/controllers,关注HomeController.java

The HomeController‘s index action returns a web page with a simple welcome message:

HomeController的index动作返回一个带有简单欢迎信息的网页。

public Result index() {
    return ok(views.html.index.render());
}

This web page is the default index template in the views package:

这个网页是视图包中默认的index模板。

@main("Welcome to Play") {
  <h1>Welcome to Play!</h1>
}

As shown above, the index page calls the main template. The main template then handles the rendering of the page header and body tags. It takes two arguments: a String for the title of the page and an Html object to insert into the body of the page.

如上所示,index页调用main模板。主模板然后处理页面标题和正文标签的渲染。它需要两个参数:一个String用于页面的标题,一个Html对象用于插入到页面的主体。

@(title: String)(content: Html)

<!DOCTYPE html>
<html lang="en">
    <head>
        @* Here's where we render the page title `String`. *@
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/main.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon.png")">
    </head>
    <body>
        @* And here's where we render the `Html` object containing
         * the page content. *@
        @content

        <script src="@routes.Assets.versioned("javascripts/main.js")" type="text/javascript"></script>
    </body>
</html>

Let’s change the text in the index file a little:

让我们稍微改变一下index文件中的文字。

@main("Welcome to Baeldung") {
  <h1>Welcome to Play Framework Tutorial on Baeldung!</h1>
}

Reloading the browser will give us a bold heading:

重新加载浏览器会给我们一个粗体标题。

Welcome to Play Framework Tutorial on Baeldung!

We can do away with the template completely by removing the render directive in the index() method of the HomeController so that we can return plain text or HTML text directly:

我们可以通过移除HomeController方法中的render指令来完全取消模板,这样我们就可以直接返回纯文本或HTML文本:

public Result index() {
    return ok("REST API with Play by Baeldung");
}

After editing the code, as shown above, we’ll have only the text in the browser. This will just be plain text without any HTML or styling:

如上图所示,编辑完代码后,我们在浏览器中就只有文本了。这将只是纯文本,没有任何HTML或样式。

REST API with Play by Baeldung

We could just as well output HTML by wrapping the text in the header <h1></h1> tags and then passing the HTML text to the Html.apply method. Feel free to play around with it.

我们也可以通过将文本包裹在标题<h1></h1>标签中,然后将HTML文本传递给Html.apply方法来输出HTML。请自由发挥吧。

Let’s add a /baeldung/html endpoint in routes:

让我们在routes中添加一个/baeldung/html端点。

GET    /baeldung/html    controllers.HomeController.applyHtml

Now let’s create the controller that handles requests on this endpoint:

现在让我们创建一个控制器,处理这个端点的请求。

public Result applyHtml() {
    return ok(Html.apply("<h1>This text will appear as a heading 1</h1>"));
}

When we visit http://localhost:9000/baeldung/html we’ll see the above text formatted in HTML.

当我们访问http://localhost:9000/baeldung/html时,我们会看到上述文本的HTML格式。

We’ve manipulated our response by customizing the response type. We’ll look into this feature in more detail in a later section.

我们通过自定义响应类型来操作我们的响应。我们将在后面的章节中更详细地研究这一功能。

We have also seen two other important features of the Play Framework.

我们还看到了游戏框架的另外两个重要特征。

First, reloading the browser reflects the most recent version of our code; that’s because our code changes are compiled on the fly.

首先,重新加载浏览器会反映出我们代码的最新版本;这是因为我们的代码变化是即时编译的。

Secondly, Play provides us with helper methods for standard HTTP responses in the play.mvc.Results class. An example is the ok() method, which returns an OK HTTP 200 response alongside the response body we pass to it as a parameter. We’ve already used the method displaying text in the browser.

其次,Play在play.mvc.Results类中为我们提供了标准HTTP响应的辅助方法。一个例子是ok()方法,它在我们作为参数传递给它的响应体旁边返回一个OK HTTP 200响应。我们已经使用了在浏览器中显示文本的方法。

There are more helper methods such as notFound() and badRequest() in the Results class.

Results类中有更多的辅助方法,如notFound()badRequest()

6. Manipulating Results

6.操纵结果

We have been benefiting from Play’s content negotiation feature without even realizing it. Play automatically infers response content type from the response body. This is why we have been able to return the text in the ok method:

我们一直在受益于Play的内容协商功能,甚至没有意识到这一点。Play会自动从响应体中推断出响应内容类型。这就是为什么我们能够在ok方法中返回文本。

return ok("text to display");

And then Play would automatically set the Content-Type header to text/plain. Although this works in most cases, we can take over control and customize the content type header.

然后Play会自动将Content-Type头设置为text/plain。虽然这在大多数情况下是有效的,但我们可以接管控制权并定制内容类型头。

Let’s customize the response for HomeController.customContentType action to text/html:

让我们自定义HomeController.customContentType动作的响应为text/html

public Result customContentType() {
    return ok("This is some text content").as("text/html");
}

This pattern cuts across all kinds of content types. Depending on the format of the data we pass to the ok helper method, we can replace text/html by text/plain or application/json.

这种模式跨越了所有种类的内容类型。根据我们传递给ok辅助方法的数据格式,我们可以用text/html替换text/plainapplication/json

We can do something similar to set headers:

我们可以做类似的事情来设置标题。

public Result setHeaders() {
    return ok("This is some text content")
            .as("text/html")
            .withHeader("Header-Key", "Some value");
}

7. Conclusion

7.结论

In this article, we have explored the basics of the Play Framework. We’ve also been able to create a basic Java web application using Play.

在这篇文章中,我们已经探讨了Play框架的基本知识。我们也已经能够使用Play创建一个基本的Java网络应用。

As usual, the source code for this tutorial is available over on GitHub.

像往常一样,本教程的源代码可在GitHub上获得over 。