CHAPTER 12

image

Scala for Web Application

The web continues to evolve in a sort of benign continuum and has become the central town of all applications with its architecture transcending to real-time, due to the emerging new requirements such as asynchrony, reactivity and responsivity, collaborating with both structured and unstructured datastore and so on. The aforementioned factors have made web development a non-trivial undertaking, which means several web frameworks have emerged to address these issues. In this chapter, we begin our journey of the Scala web landscape through one of the highly popular web frameworks Play 2. We elected Play framework, because it enables web development for the modern era using both Scala and Java. We introduce both Play 2 for Scala and Play 2 for Java, because we believe that most Scala developers are experienced in Java through industrial projects or academia. The remaining Scala developers are the ones who transitioned to Scala from Java and so, we believe, having familiarity with Java will make the transition to Play framework much easier and it allows Play framework to position itself in an already established segment of Java web.

Scala Web Frameworks

The Scala web frameworks are rapidly evolving. In the Scala world, alternatives to web development span from micro-frameworks, such as Scalatra, to feature-rich frameworks such as Play. In many ways, these web frameworks concentrate on, addressing the aforementioned complexity of the web development. In Table 12-1 we list the key players in Scala web development. The list presented, however, is not exhaustive because this list is in a perpetual state of evolution as the technology and the web advance.

Lift

Lift is an expressive and elegant framework for writing web applications. Lift stresses the importance of security, maintainability, scalability, and performance, while allowing for high levels of developer productivity. Lift open source software is licensed under an Apache 2.0 license.

The Lift Web Framework has Comet support. That means that state change on the serverside is immediately pushed to the browser. Lift’s Comet support makes chat applications, multiuser games, and other browser-based applications trivial to write. Listing 12-1 has the entire code required to write a multi-user chat application in Lift.

Listing 12-1. Multiuser Chat Application in Lift

case class Messages(msgs: List[String])
object ChatServer extends Actor with ListenerManager {
private var msgs: List[String] = Nil
protected def createUpdate = Messages(msgs)
override def highPriority = {
case s: String if s.length > 0 =>
msgs ::= s
updateListeners()
}
this.start
}
class Chat extends CometActor with CometListenee {
private var msgs: List[String] = Nil
def render =
<div>
<ul>{msgs.reverse.map(m =><li>{m}</li>)}</ul>
{ajaxText("", s => {ChatServer ! s; Noop})}
</div>
protected def registerWith = ChatServer
override def lowPriority = {
case Messages(m) => msgs = m ; reRender(false)
}
}

There’s nothing magic about Lift’s Comet support, but it would be much harder to do in Java. Lift has Comet Actors, which represent server-side state in a section of browser real estate. The real estate is demarcated by a <span> with a GUID. All Lift pages are rendered using Scala’s built-in XML support. After the render phase, but before the page is streamed to the browser, Lift looks through the page to see whether the page contains HTML that points to any Comet Actors. If yes, Lift rewrites the XML and inserts JavaScript to do Comet-style long polling. After the page is loaded, the browser opens an XMLHTTPRequest to the server with the GUIDs of all the Comet components on the page along with the version number of each of the Comet components. The server receives the request and creates an Actor for each GUID, and each Actor registers itself as a listener with the appropriate Comet component. The registration includes the version number of the component as contained by the browser. If the servlet is running in Jetty or a Servlet 3.0 container, Lift automatically invokes the container’s “continuation” mechanism so that the pending request is consuming no threads. It is consuming an NIO socket, and it’s also consuming one Actor per Comet component on the page.

When the Comet component receives the listener registration, it compares the version number with the current version number. If they differ, the Comet component immediately sends the Actor a message containing the diffs between the version that the Actor/browser has and the current version of the Comet component. If the version number is current, the Comet component does nothing. If the Comet component receives a message and updates itself, it notifies the listener of the diff between the old version and the new version of the component.

During the “no changes” phase, the only system resources being consumed are memory and an NIO connection. No threads or stacks are involved. When the Actor receives an update from the Comet component (or after 120 seconds), the Actor creates a response to the Ajax request. It then invokes the continuation and sends the response to the browser (either JavaScript containing commands to perform the diffs or a Noop). The browser executes the JavaScript, waits 100 milliseconds, and restarts the process. You could implement all this in Java. In fact, there is a Comet library that sits on top of Jetty and Dojo that has the same scaling characteristics. However, the amount of code to implement this scheme in Scala contains roughly the same number of characters as the preceding description.

Play 2

Play 2 provides an asynchronous HTTP API leveraging on the Actor model by means of Akka,1  to handle highly concurrent systems. Akka is the implementation of Actor model for both Scala and Java.

Play 1 used the Java language and provided support for Scala by means of plugins. Play 2.0 was released in 2012 in concurrence with the Typesafe2 Stack and was built using Scala as the core language. Table 12-2 lists the key features of Play 2.  

Table 12-2. Key Features of Play 2

Feature

Description

Asynchronous I/O

Service of long requests asynchronously using JBoss Netty3 as its web server.

Built-in Web server

JBoss Netty web server out of the box, but Play web applications can also be packaged to be distributed to Java EE application servers.

Dependency management

SBT for dependency management

Hot reloading

In the development mode, the code is verified for updates upon new requests, and modified files are automatically recompiled and in case of error, the error is displayed in the browser directly unlike the classic web applications where the errors are displayed in the console of application server.

In-memory database

Support for embedded database like H2 out of the box.

Native Scala support

Native support for Scala natively at the same time complete interoperability with Java.

ORM

Ebean4 as the ORM replacement of JPA to access database.

Stateless

Fully RESTful and  without the Java EE session per connection

Templating

Use of Scala for the template engine.

Testing framework

Built-in test framework such as JUnit and Selenium5 for unit and functional testing

WebSocket

Out of the box WebSocket implementation  to enable a bi-directional connection between a client and the server

Play 2 exists in two flavors—the classic Play 2 standalone distribution and Typesafe Activator-based distribution. Because classic Play 2 was very popular and you may still find it in legacy applications, we will introduce both classic and Typesafe distribution; however, you can choose to migrate from classic Play 2 to activator-based Play 2. If you want learn about migration to Play 2.3, check the Play 2.3 migration guideat https://www.playframework.com/documentation/2.3.x/Migration23.

Getting Started with the Standalone Distribution

To run the Play framework, you need JDK 6 or later. If you are using Linux, make sure to use either the Sun JDK or OpenJDK (and not gcj, which is the default Java command on many Linux distros). If you are using Windows, just download and install the latest JDK package. If you are using MacOS, Java comes built-in.

On Windows you’ll need to set the PATH in environment variables. On UNIX systems do the following:

export PATH=$PATH:/relativePath/to/play

You can enter the following command in the command line tool to check whether Play is correctly installed:

> play

If Play is correctly installed, you will see the output on the console as illustrated in Figure 12-1.

9781484202333_Fig12-01.jpg

Figure 12-1. Verifying whether Play 2 is correctly installed

You can also get help by means of the help command as illustrated in the Figure 12-2.

> play help

9781484202333_Fig12-02.jpg

Figure 12-2. Help in Play 2

Now that Play is correctly installed, you can go on to create your first Scala web application with Play. Let’s Play! You can create a helloworld-scala application as illustrated in Figure 12-3. To create a new application, you just have to use the play command-line tool with the parameter new followed by the name of the new application—helloworld as illustrated in Figure 12-3.

9781484202333_Fig12-03.jpg

Figure 12-3. Creating helloworld application

As mentioned earlier, Play 2 allows you to create both Java- and Scala-based web applications. Play 2 asks you to specify whether your application is a Scala or Java application as illustrated in Figure 12-4.

9781484202333_Fig12-04.jpg

Figure 12-4. Specifying whether the application is a Scala or a Java application

You have to specify 1 because you want to create a Scala application. Specifying 1 creates the source files and the structure of the application for the Scala as illustrated in Figure 12-5.

9781484202333_Fig12-05.jpg

Figure 12-5. Creation of the helloworld project

You can run the application using the run command from the helloworld directory. To do this, enter the Play Console as illustrated in the Figure 12-6.

> cd helloworld
>play

9781484202333_Fig12-06.jpg

Figure 12-6. Entering the Play console

Now type run. This starts the server that runs your application.

$ run

The output on the console is shown here.

[helloworld] $ run
[info] Updating {file:/F:/play2_workspace/helloworld/}helloworld...
[info] Resolving org.scala-lang#scala-library;2.10.2 ...
[info] Resolving com.typesafe.play#play-jdbc_2.10;2.2.0 ...
  [info] Resolving com.typesafe.play#play_2.10;2.2.0 ...
  [info] Resolving com.typesafe.play#sbt-link;2.2.0 ...
  [info] Resolving org.javassist#javassist;3.18.0-GA ...
  [info] Resolving com.typesafe.play#play-exceptions;2.2.0 ...
.................
.................
[info] Resolving org.scala-lang#scala-compiler;2.10.2 ...
  [info] Resolving org.scala-lang#jline;2.10.2 ...
  [info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
--- (Running the application from SBT, auto-reloading is enabled) ---
[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
(Server started, use Ctrl+D to stop and go back to the console...)

As you can see, the console says that it has started the application and an HTTP server is listening for HTTP request on the port 9000. You can now send the request to this server by going to the URL http://localhost:9000/. Upon requesting the server, a welcome screen is displayed as illustrated in the Figure 12-7.

9781484202333_Fig12-07.jpg

Figure 12-7. Default Welcome page of Play 2 framework

Image Tip  The default welcome page of the application provides impressive practical information and it is recommended you read the welcome page.

Anatomy of Play Application

The run command creates the structure of the application inside the helloworld directory. The structure is illustrated in Figure 12-8.

9781484202333_Fig12-08.jpg

Figure 12-8. The directory structure of the helloworld application

Here are the contents of each folder in Figure 12-8:

  • app: This is the root of all the server-side source files such as Java and Scala source code, templates, and compiled assets’ sources. Only two subfolders, controllers and views, for Controller and View component of the MVC architectural pattern are created. You can add the directory app/models for the Model component of the MVC. There is also an optional directory called app/assets for compiled assets such as LESS6 sources and CoffeeScript7 sources.
  • conf: The conf directory contains the application’s configuration files. These configuration files are meant to, as the name suggests, configure the application, external services, and so on. There are two main configuration files:
  • application.conf: The main configuration file for the application, that comprises standard configuration parameters
  • routes: The routes definition file.
  • project: The project folder comprises all the necessary files to configure the Scala built tool SBT.
  • public: This directory comprises three standard sub-directories for images, CSS stylesheets, and JavaScript files.

Image Note  Resources stored in the public directory are static assets that are served directly by the web server.

  • target: The target directory comprises artifacts generated by the build system such as:
  • classes: All compiled classes (from both Java and Scala sources).
  • classes_managed: Only the classes that are managed by the framework (such as the classes generated by the router or the template system).
  • resource_managed: Generated resources, typically compiled assets such as LESS CSS and CoffeeScript compilation results.
  • src_managed: Generated sources, such as the Scala sources generated by the template system.
  • test: Comprises all test files along with some samples provided by the framework.

MVC in Play 2

A Play 2 application follows the MVC architecture pattern. In a Play 2 application these MVC layers are defined in the app directory, each one in a separate package as shown in Figure 12-9.

9781484202333_Fig12-09.jpg

Figure 12-9. MVC in Play 2

The request flow in the MVC architecture illustrated in Figure 12-9 constitutes following:

  • The Router intermediates the HTTP request.
  • The Router determines the action defined in the controller to process this request.
  • The Controller listens for HTTP requests, extracts appropriate data from the requests, and applies changes to the model.
  • Controller renders a template file to generate the view.
  • The result of the action method is finally sent as an HTTP response.

Router

The router constitutes the main entry point of the web application through the conf/routes file, which defines the routes required by the application. Each route comprises an HTTP method and a URI pattern. A call to an action method is associated with the URI. Conf/routes is the configuration file used by the built-in component called Router that translates each incoming HTTP request to an action call.

Image Note  The HTTP method can be any of the valid methods supported by HTTP (GET, POST, PUT, DELETE, HEAD).

The router is responsible for mediating and translating an incoming HTTP request to an Action. The MVC framework sees the HTTP request as an event comprising the request path, including the query string and the HTTP method (e.g., GET, POST, ...). Routes are defined in the conf/routes file. This file is compiled and if there are any errors, you see them in your browser directly without recompiling your code or restarting the server. When the route file is modified, it is automatically reloaded. This feature is called hot reloading. We will now test this feature by introducing an error in form or unclosed string literal as illustrated in Listing 12-2.

Listing 12-2. Testing Hot Reload

def index = Action {
  Ok("Hello world)
}

When you reload the home page in your browser, the compilation error is displayed (see Figure 12-10).

9781484202333_Fig12-10.jpg

Figure 12-10. Installing the Eclipse plug-in for Scala-IDE

As you see errors are directly displayed in your browser and you do not have to go to the console to check the error. But if you want to check the error on the console, it is also available on the console as shown.

[error] F:play2_workspacehelloworldappcontrollersApplication.scala:9: unclo
sed string literal
[error]   Ok("Hello world)
[error]      ^
[error] F:play2_workspacehelloworldappcontrollersApplication.scala:10: ')'
expected but '}' found.
[error] }
[error] ^
[error] two errors found
[error] (compile:compile) Compilation failed
[error] application -! @6kmmbl6fg - Internal server error, for (GET) [/] ->play.PlayExceptions$CompilationException: Compilation error[unclosed string literal]
at play.PlayReloader$$anon$1$$anonfun$reload$2$$anonfun$apply$14$$anonfun$apply$16.apply(PlayReloader.scala:304) ~[na:na]
at play.PlayReloader$$anon$1$$anonfun$reload$2$$anonfun$apply$14$$anonfun$apply$16.apply(PlayReloader.scala:304) ~[na:na]
at scala.Option.map(Option.scala:145) ~[scala-library.jar:na]at play.PlayReloader$$anon$1$$anonfun$reload$2$$anonfun$apply$14.apply(PlayReloader.scala:304) ~[na:na]
at play.PlayReloader$$anon$1$$anonfun$reload$2$$anonfun$apply$14.apply(PlayReloader.scala:298) ~[na:na]
at scala.Option.map(Option.scala:145) ~[scala-library.jar:na]

Controller

The Controller responds to requests, processes them, and invokes changes on the model. A Controller in Play 2 is an object in Scala that extends the Controller type. This Controller type is provided in the play.api.mvc package. A Controller in Play 2 comprises a function called an action to process the request parameters, and produce a result to be sent to the client. Controllers are, by default, defined in the controllers package under the source root—the app folder. A Controller in Java is a class and comprises public, static method called an action

Image Note  A controller is a type that extends a Controller provided in the play.api.mvc package.

Model

The Model is the domain-specific representation of the information (in the form of data structures and operations) on which the application operates. The most commonly used object for such representation is the JavaBean. However the JavaBean leads to plenty of boilerplate code. Play 2 reduces this boilerplate code by generating the getters and setters for you by means of byte-code enhancement. The model objects might contain persistence artifacts, such as JPA annotations if they need to be saved into persistent storage.

View

In a Java EE−based web application the view is usually developed using JSP. That is, the view in JavaEE−based web applications consists of JSP elements and template text. As Play is not Java EE−centric, the view comprises the template that contains a mix of HTML and Scala code. In Play 1 the templates were based on Groovy but starting with Play 2, templates are Scala based. Using Play 2 you can develop both Java- and Scala-based web applications and the templates are exactly the same in both Java- and Scala-based web applications.

Image Note  In Play 1 the templates were based on Groovy but starting from Play 2, templates are Scala based.

Now let’s look at the controller generated by Play 2 for helloworld-scala. You can find the controller in helloworld-scalaappcontrollers (see Listing 12-3).

Listing 12-3. Application Controller in Scala

package controllers

import play.api._
import play.api.mvc._

object Application extends Controller {

def index = Action {
 Ok(views.html.index("Your new application is ready."))
          }

}

In Scala, the controller is an object and an action is a function. Now that you have seen the controller in Scala, it is time to see the template in helloworld-scala, which you can find in helloworld-scalaappviews (see Listing 12-4).

Listing 12-4. Template in helloworld-scala

@(message: String)

@main("Welcome to Play") {

@play20.welcome(message)

}

The action in Listing 12-3 returns a 200 OK response filled with HTML content. The HTML content is provided by a template in Listing 12-4. The Scala templates in Play 2 are compiled to Scala functions. A template is like a function, and thus it needs parameters, which are declared at the top of the template file. The Scala statement starts with the special @ character. The first line defines the function signature, which takes a single String parameter. Then the template content mixes HTML (or any text-based language) with Scala statements. The Scala statements start with the special @ character. A function named main with one string argument is invoked.  The welcome, provided by Play 2 to render the default welcome HTML page. This page is located in the file named main.scala.html in apps/views folder. Now let’s modify the application by modifying the response as shown in Listing 12-5.

Listing 12-5. Modifying the Response

def index = Action {
  Ok("Hello world")
}

Now the index action responds with a text/plain Hello world response because of the modification. Refresh the home page in your browser to test this modification (see Figure 12-11).

9781484202333_Fig12-11.jpg

Figure 12-11. Changed content of the response

Configuring Eclipse for Scala

The Scala IDE is an Eclipse plug-in and you can install this plug-in from Help image Install New Software. In the Work with field, enter the path for the plug-in (http://scala-ide.org/download/current.html) as shown in the Figure 12-12. You can find detailed instructions for configuring Eclipse for Scala at http://scala-ide.org/documentation.html.

9781484202333_Fig12-12.jpg

Figure 12-12. Installing the Eclipse plug-in for Scala-IDE

You can use the Eclipse IDE with Play 2. To do this you need to ask Play 2 to generate the Eclipse project configuration. You can do this by invoking Eclipse in the play console as illustrated in Figure 12-13.

9781484202333_Fig12-13.jpg

Figure 12-13. Generating the project for Eclipse

To import the project, go to File image Import, then select General image Existing Projects into Workspace and click Next as illustrated in the Figure 12-14.

9781484202333_Fig12-14.jpg

Figure 12-14. Importing the project

Now browse your file system, select the project folder helloworld, click OK, and then click Finish.

All the files necessary to configure an Eclipse project are generated.

HelloWorld Java Application with Play

Now let’s create a Java application with Play 2. You can follow the same steps as when you created the Scala application as illustrated in Figure 12-15.

9781484202333_Fig12-15.jpg

Figure 12-15. Creating the helloworld application

Play 2 asks you to specify whether your application is a Scala or Java application as illustrated in Figure 12-16.

9781484202333_Fig12-16.jpg

Figure 12-16. Specifying whether the application is a Scala or a Java application

To create a Java application, you have to specify 2 as illustrated in Figure 12-17 and the source files and the structure of the application for the Java will be created.

9781484202333_Fig12-17.jpg

Figure 12-17. Creation of the helloworld project

Run the application using the run command from the helloworld directory. To do this, enter the Play Console as illustrated in the Figure 12-18.

> cd helloworld
>play

9781484202333_Fig12-18.jpg

Figure 12-18. Entering the Play console

Now type run to start the server to run your application.

$ run

The output on the console is shown here.

[helloworld] $ run
[info] Updating {file:/E:/ModernJava/play2-workspace/helloworld/}helloworld...
[info] Resolving org.scala-lang#scala-library;2.10.2 ...
[info] Resolving com.typesafe.play#play-java-jdbc_2.10;2.2.0 ...
  [info] Resolving com.typesafe.play#play-jdbc_2.10;2.2.0 ...
  [info] Resolving com.typesafe.play#play_2.10;2.2.0 ...
...............................................
  [info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
--- (Running the application from SBT, auto-reloading is enabled) ---
[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
(Server started, use Ctrl+D to stop and go back to the console...)

As you can see, the console says that it has started the application and an HTTP server is listening for HTTP request on the port 9000. You can now send request to this server by going to the URL http://localhost:9000/. Figure 12-19 illustrates the default Play 2 welcome page.

9781484202333_Fig12-19.jpg

Figure 12-19. Default welcome page of Play 2 framework

Now you will see what the Java controllers.Application.index method looks like in comparison to the Scala controller. Open the app/controllers/Application.java source file. This file is illustrated in the Listing 12-6.

Listing 12-6. Application Controller

package controllers;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {

public static Result index() {
return ok(index.render("Your new application is ready."));
}

}

The Java Application controller class extends play.mvc.Controller. The public static index() action returns a Result. The Result represents the HTTP response to be sent back to the browser. Here, the action returns a 200 OK response with an HTML response body.

Image Note  All action methods return a Result.

The HTML content is provided by a template. An action always returns an HTTP response, which is represented in Play 2 by the Result type. The Result type must be a valid HTTP response, so it must include a valid HTTP status code. OK sets it to 200. The render() references a template file in Play 2.

You can now configure Eclipse for Java in the same way you learned when configuring Eclipse for Scala. To import the project, you can repeat the steps that you performed earlier in generating the project configuration for Eclipse in the helloworld Java application.

You saw how to create a project and import it to your development environment. Now you will modify the application. In Application.java change the content of the response in the index action as illustrated in Listing 12-7.

Listing 12-7. Modifying the index Action

public static Result index() {
  return ok("Hello world");
}

The index action now responds with Hello world (as illustrated in Figure 12-20) when accessed using http://localhost:9000/.

9781484202333_Fig12-20.jpg

Figure 12-20. Running Hello world application

Play 2 provides several sample applications in the samples folder in play-2.2.0samplesjava.  You can run the helloworld application as illustrated in the Figure 12-21.

9781484202333_Fig12-21.jpg

Figure 12-21. The sample Helloworld application provided by Play 2

When you click Submit Query the user’s name is displayed based on the selection (as illustrated in the Figure 12-22).

9781484202333_Fig12-22.jpg

Figure 12-22. Running the sample Helloworld application

You can go through the code to improve the application on your own.

Getting Started with the Activator Distribution

In this section you will create a Scala web application using the Typesafe Activator. The Typesafe Activator is a web and command-line tool that aids developers when working on the Typesafe platform. From Play 2.3 onward, Play is distributed as an activator distribution that comprises all the dependencies of the Play framework. Play 2.3 is the latest activator distribution and in this distribution the play command from the classic distribution has now become the activator command. Activator comes with a rich library of project templates. You can extend the templates or add new templates. Activator provides a rich web UI for creating web applications.

Image Note  The play command features of the classic distributions are still available with the activator command. Because the activator command and the play command are both wrappers around SBT, if you prefer, you can directly use the SBT commands.

To get started with activator distribution, perform the following steps:

  • Access the Typesafe page URL at http://www.typesafe.com/platform/getstarted.
  • Download the Typesafe Activator. If you prefer, you can also download a minimal (1MB) version of Activator from the Activator site. The minimal version of Activator downloads dependencies only when they’re needed.
  • Extract the downloaded zip archive to your system in a directory of your choice.
  • Locate the activator script within the extracted archive.
  • Right-click on it and select Open if you are running Windows or just go to the Typesafe Activator installation directory and enter the following command:
    > ./activator ui

This launches the activator in a browser window, similar to Figure 12-23.

9781484202333_Fig12-23.jpg

Figure 12-23. Launching the Activator in the browser

Image Note  The minimal version of Activator downloads dependencies only when they’re needed.

The basic starter Scala project is found in the hello-scala template.

  1. Select the template.
  2. Note the default location that indicates where the project will be created.
  3. Click Create, which takes you to the screen shown in Figure 12-24.

    9781484202333_Fig12-24.jpg

    Figure 12-24. Creating the new app

    Image Note  The default location where the project will be created before clicking on Create.

    Now run the project by entering the following command on the command prompt:

    > ./activator run

Open the http://localhost:9000/ URL in a browser. It may take a few seconds for the application to open as shown in the Figure 12-25.

9781484202333_Fig12-25.jpg

Figure 12-25. Compiling the project definition

Figure 12-26 illustrates the running hello-scala application.

9781484202333_Fig12-26.jpg

Figure 12-26. Running the helloscala application

Actions, Controllers, and Results

Earlier when you created the helloworld project, you saw the controller in helloworld-scalaappcontrollers. Here is the controller code (see Listing 12-8) again for quick reference.

Listing 12-8. Application Controller

package controllers
import play.api._
import play.api.mvc._

object Application extends Controller {

  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }

}

You see that controllers.Application.index returns an Action. A controller is something that generates an action. A controller is a singleton object as illustrated in Listing 12-8. The action handles the requests received by a Play application and generates a Result, which is then sent to the client. An action in Play is a function that returns a play.api.mvc.Result value as illustrated in the Listing 12-9.

Listing 12-9. index.scala.html

def index = Action {
  Ok("Hello world!")
}

An action must always return a result. The result value embodies the HTTP response. In Listing 12-9, Ok constructs a 200 OK response to be sent to the client.

The Action is a companion object that provides helper methods to construct an action. Listing 12-10 shows a simple way to construct an action.

Listing 12-10. index.scala.html

Action {
  Ok("Hello world")
}

In Listing 12-10, the reference to the request is not available. More often you need the access to request. When you need the reference to the request you can construct the action as illustrated in Listing 12-11.

Listing 12-11. index.scala.html

Action { req =>
  Ok("request access [" + req + "]")
}

The actions can return several types of results. Table 12-3 shows some of the common results. A complete list of results can be found at https://www.playframework.com/documentation/2.3.x/api/scala/index.html#play.api.mvc.Results.

Table 12-3. Commonly Used Results

Results

Description

BadRequest

Generates a ‘400 BAD_REQUEST’ result

InternalServerError

Generates a ‘500 INTERNAL_SERVER_ERROR’ result

NotFound

Generates a ‘404 NOT_FOUND’ result.

Ok

Generates a ‘200 OK’ result.

Redirect

Generates a redirect simple result.

Status

Generates a simple result.

We present the ways in which results can be used in Listing 12-12 through Listing 12-17.

Listing 12-12. Using BadRequest

val badReq= BadRequest(views.html.form(formWithErrors))

Listing 12-13. Using InternalServerError

val error = InternalServerError("some error")

Listing 12-14. Using NotFound

val notFound = NotFound

Listing 12-15. Using OK

val ok = Ok("Hello world!")

Listing 12-16. Using Status

val  status = Status(488)("response")

Listing 12-17. Using Redirect

defredirect = Action {
Redirect("/adminPage")
}

One chapter is not enough to cover all the features of the Play 2 framework (or any framework for that matter). The best way to learn any framework is to play with it. We recommend you spending some time playing with Play 2.

Summary

This chapter took a high-level look at the Play 2 framework, covering the basics that are common to all the Play 2−based web applications. This chapter provided a brief introduction to both the classic and Typesafe Activator distribution. You developed a Hello World web application for both Scala and Java. You learned to write controllers and actions, and examined the differences between Scala and Java controllers.

_________________________________

1http://akka.io/

2https://typesafe.com/

3http://netty.io/

4http://www.avaje.org/

5http://www.seleniumhq.org/

6http://lesscss.org/

7http://jashkenas.github.io/coffee-script/

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset