Chapter 1. Introduction

This chapter covers

  • Recognizing what Scalatra is good at
  • Writing a simple Hello World web application
  • Using microframeworks versus full-stack frameworks

Scalatra is a lightweight web framework written in the up-and-coming new language, Scala. It offers extremely fast development and execution speeds for HTTP applications.

If you’re a Java coder who’s curious about Scala or looking for a productivity gain, Scalatra offers a perfect opportunity: it’s easy to get started with, and if you’re already running your web apps in servlet containers, you can drop in a Scalatra application without any fuss. You can be up and running in a few minutes, building simple and intuitive HTTP interfaces to new or existing software.

On the other hand, maybe you’re a Perl, PHP, Python, or Ruby coder looking for a massive performance boost. Perhaps you’ve built a large system and want the refactoring benefits of type safety without Java boilerplate. Scalatra is the simplest way to jump into Scala web development. You get easy access to tens of thousands of battle-tested Java libraries with a simple and familiar HTTP routing DSL wrapped around them.

1.1. What’s Scalatra good at?

Scalatra can replace other web development frameworks for most tasks. This book will guide you through all the major aspects of building a web application, starting with an overview in chapter 2 and breaking down the details in chapters 3 through 11.

Mobile app development on Android and iOS has exploded over the past half decade. At the same time, single-page in-browser development frameworks such as Backbone.js, Ember.js, and AngularJS are rapidly gaining in popularity.

All of this means a lot of clients still make heavy use of web technologies but aren’t the traditional browser clients we’ve seen for the past 20 years. Scalatra is a perfect fit for these clients. It’s easy to install, lightweight, and fast. It lets you design and build out high-performance web APIs quickly, and it’s integrated with special tools to produce beautiful, functional, and correct API documentation.

Another major area of internet innovation recently is in the realm of server-push technologies. Scalatra incorporates advanced constructs for event-driven programming, so you can easily push information into your users’ browsers—they see constantly updated information without having to refresh the page. This technology has the potential to turn the web upside-down.

Finally, in some cases people are using full-sized frameworks for the bulk of their web development functionality, and they bust out Scalatra for specific, high-performance actions. This means it’s relatively easy to try it out in an isolated part of your system. You can use Scalatra to solve performance hotspots or wrap a legacy set of class libraries in a shiny new HTTP layer.

1.2. Hello World

Scalatra is simple. All you need to do is add a small configuration file and download and run one command, and you have a running web application. The following listing illustrates just how simple a Scalatra program can be.

Listing 1.1. Scalatra in action
package com.example.yourapp
import org.scalatra._

class HelloWorld extends ScalatraServlet {
  get("/") {
    "Hello world"
  }
}

When you run this code on your local machine, you can type http://localhost:8080/ into your browser and see the text “Hello world” in return, as shown in figure 1.1.

Figure 1.1. "Hello world" output

There’s a lot more to learn, but that simple code expresses the essence of Scalatra. You define a route, which is a combination of an HTTP verb (get) and a URL route matcher (/), which executes a block of code on the server and returns the result (in this case, the string "Hello world"). The next listing explains things line by line.

Listing 1.2. Anatomy of "Hello world"

As you can see, Scalatra applications can be very small. What do all of these big organizations see in it? The interesting thing is that there isn’t a single answer to that question, because Scalatra is a microframework.

1.3. Microframeworks vs. full-stack frameworks

Most web programmers are used to full-stack frameworks. In general, these try to solve all the problems you’ll commonly encounter, and to do so within the confines of a fairly unified codebase. Despite their obvious differences, Spring, Symfony, Ruby on Rails, Django, and the Play Framework all share something: they make the assumption that you won’t often need (or even want) to step out of the environments they provide.

Microframeworks are different.

Instead of trying to provide for your every need, microframeworks try to do a few things well. In Scalatra’s case, you get a great way of expressing HTTP actions, a lot of optional modules for common tasks, and an easy way to bolt on additional libraries to accomplish whatever you want.

The microframework approach is a candid admission by the Scalatra authors that they don’t have a clue what you’re going to build. It’ll probably be related to HTTP, but your choices beyond that—of data stores, template libraries, testing frameworks, strategies for asynchronous requests and responses, server push, message queuing systems, and API documentation—are up to you. Maybe you don’t need half the things on that list. Maybe you need all of them, but you want to choose each library yourself.

This lean way of doing things allows you to build up exactly the right capabilities for the job at hand and keeps the amount of extra code in your project to a minimum. If you’re building a full-sized web application, like a social network app or an e-commerce application, you can use Scalatra as a full model-view-controller stack, with an HTML templating system and an object-relational mapper for database access. Conversely, if you’re building a small, high-performance system, such as an API that routes incoming request data to other systems, or an authorization server, you can import only what’s needed to do so.

The lean nature of the resulting codebases means fewer lines of code to maintain. If you structure things well, this can mean speedier development, better performance, and lower maintenance costs than a full-stack framework.

1.4. How does Scalatra compare with other Scala web frameworks?

Scalatra isn’t your only choice when it comes to HTTP development in Scala. Other popular frameworks include Lift and Play. Of these three, why would you choose Scalatra? It comes down to trade-offs in several main areas: application development style, the aforementioned microframework versus full-stack approach, and deployment.

1.4.1. Scalatra is a lean MVC framework

Let’s consider Scalatra versus Lift first. Unlike the other frameworks, Lift doesn’t use the popular model-view-controller (MVC) pattern for organizing code. Instead, it offers a view-first approach, which many programmers aren’t familiar with. Whatever the merits of view-first versus MVC, sometimes familiarity is a big win, especially if you’re coming from another MVC framework.

Both Play and Scalatra, in contrast, use the more popular MVC pattern. With Play, you get a larger and more featureful framework than Scalatra. Play favors convention over configuration, so it seeks to decrease the number of decisions you’ll typically need to make. Stay on the happy path, and it arguably provides more initial development speed than Scalatra.

But if you stray from Play’s application structure or library choices, you may find yourself wanting more flexibility. Scalatra gives you the freedom to curate every library choice and be in complete control of your application’s structure.

The other main thing to consider is how you’ll host your application when it’s built.

1.4.2. Scalatra runs on servlets

Once you build your application, you’ll need to deploy it to a server in order to make it available to the world. Lift and Scalatra are both designed to be deployed in standard Java servlet containers: Tomcat, JBoss, and Jetty are popular examples. Play, on the other hand, deploys on newer technology: the Netty network application framework. Again, there are various pros and cons to consider.

Netty, which uses the new Java NIO APIs, is a relatively fresh technology and is theoretically more performant. But the subject is complicated, with Netty winning against servlets for some workloads and losing for others.

In contrast to Netty, servlet containers aren’t sexy, but they’re battle-hardened and have great tooling. Additionally, many people know how to configure them, tune them, and keep them running in production.

One last consideration: many workplaces still mandate servlets for web deployments. In these cases, the ability to deploy on servlets may be make-or-break for Scala adoption.

We hope this is enough to provide a fair overview of possible choices. Now let’s write some Scalatra code.

How much Scala do you need to know to read this book?

We write this book under the assumption that Scala is a new language and that there aren’t many Scala programmers yet. We suspect that we’ll need to teach you a bit about Scala at the same time we teach you Scalatra. We know how daunting it can be to be suddenly thrust not just into the land of Scala, but also into the world of the JVM, if you’re coming from another environment. We’ll provide a well-lit path for you.

At the same time, Scala is a large language with many concepts that may be unfamiliar to you. Unfortunately, we don’t have enough room in this book to provide a full language reference. You should get a copy of Scala in Action (Manning, 2013) to read alongside this book if you haven’t yet read an introductory book on the Scala language.

1.5. Installing Scalatra

Before we can move on to the rest of the book, you’ll need to have a running installation of Scalatra. You can find installation instructions in the appendix. It includes full instructions for getting Scalatra installed and for setting up your development environment. If you haven’t yet installed Scalatra, take some time now to get set up.

Once you’re ready, let’s generate, build, and run a traditional Hello World example. The first thing you’ll need to do is generate an application skeleton. How does project generation work?

Although you can set up your project almost any way you want, the normal thing to do when starting a new project is to use a tool called giter8 (or g8 for short). giter8 retrieves project templates from Git repositories. The standard Scalatra project template lives in a repository on the popular coding website GitHub, at https://github.com/scalatra/scalatra-sbt.g8.

When you run the g8 command, giter8 will ask you a series of questions about the project you’d like to create. It will then retrieve the standard project skeleton from GitHub, inject the information you provided into the retrieved files, and save them on your machine.

1.5.1. Generating a new project

Run the following code in your terminal:

g8 scalatra/scalatra-sbt

This checks out a prebuilt application skeleton for you (from GitHub) and asks you some questions about your application. giter8 will ask you the following questions when generating a project. Press Enter to accept the default value for each question:

$ g8 scalatra/scalatra-sbt
          organization [com.example]:
          name [My Scalatra Web App]:
          version [0.1.0-SNAPSHOT]:
          servlet_name [MyScalatraServlet]:
          package [com.example.app]:
          scala_version [2.11.6]:
          sbt_version [0.13.8]:
          scalatra_version [2.4.0]:

giter8 will take your answers to these questions and write them into the build.sbt file for your application, so you can change them in that file later. Table 1.1 gives a basic rundown of what the questions mean.

Table 1.1. Generating a project

g8 question

What it means

organization Used for publishing. Should be the reverse of a domain name you control. If you don’t own a domain, com.github.username is a popular choice.
package All Scala code belongs in a package. The Scala Style Guide recommends that your packages start with your organization. This convention is used across multiple JVM languages and gives your project a globally unique namespace.
name The name of your project. g8 generates a project into a folder of this name, and the artifacts you publish will be based on this name.
servlet_name The name of your servlet. This might be something like BlogServlet, BlogController, or just Blog.
scala_version The version of Scala your project is built with. When in doubt, use the default.
version The version number of your project. This is entirely up to you, but we like semantic versioning.

Once you’ve answered the questions, your answers are applied to the giter8 templates, and the project skeleton is saved on your local system.

Check for giter8 templates to speed things up

Quite a few Scalatra giter8 templates are available for various purposes. If you’re looking to find out how to integrate Scalatra with some other library, do a bit of searching on GitHub, and you may be pleasantly surprised.

1.5.2. Downloading dependencies and building the app

Enter the top-level directory of your new application, and type ./sbt. sbt will take a while to respond, especially the first time. sbt looks at the dependencies defined in the file project/build.scala and downloads Scala, a Scala compiler, Scalatra, and a small set of dependencies of the Scalatra application. That single three-letter command gives you a full web development environment! Once sbt has finished downloading everything, you’ll get an sbt prompt, which looks like this: >.

1.5.3. Starting the Hello World application

Let’s start the Hello World application:

jetty:start

That will compile the application and start a web server running on http://localhost:8080. When you see some output like this, you’ll know it’s running:

Started
ServerConnector@5f164c1{HTTP/1.1}{0.0.0.0:8080}

Visit it in your browser—you’ll see output similar to that in figure 1.2. The first request will be slow, because the application sets itself up for the first time; subsequent requests will get faster and faster as the JVM optimizes code paths for your machine.

Figure 1.2. Hello World in your browser

We can now take a quick look at the application code. Open the file src/main/scala/com/example/app/MyScalatraServlet.scala. You’ll see the code in the following listing; this is a simple Scalatra app containing a single HTTP route.

Listing 1.3. Your first Scalatra application
package com.example.app

import org.scalatra._
import scalate.ScalateSupport

class MyScalatraServlet extends MyScalatraWebAppStack {

  get("/") {
    <html>
      <body>
        <h1>Hello, world!</h1>
        Say <a href="hello-scalate">hello to Scalate</a>.
      </body>
    </html>
  }

}

1.5.4. Making changes and seeing them in your browser

Let’s change the code so that the response is the same as the original Hello World example that started this chapter. Change the output from an XML literal to a string:

get("/") {
  "Hello world"
}

Save the file and refresh your browser. The example hasn’t changed.

Scala needs to recompile the program in order to make your changes appear. Doing this manually every time you make a change to your source code would be pretty awful, so there’s a handy way to make your changes appear automatically.

Back at the sbt console, type this:

~jetty:start

From this point on, every time you change your code, sbt will automatically recompile the application code to make your changes visible. It will then reload the server. When that’s done, you’ll see this information in your console:

[success] Total time: 1 s, completed 01-Feb-2014 23:38:44
3. Waiting for source changes... (press enter to interrupt)

Click Refresh in your browser, and you should see your changes. When you’re only modifying web assets, you can run the ~webappPrepare task, which leads to faster turnaround times.

How do I stop?

When you want to stop the reloader, press the Enter key. If you want to stop serving your application, type jetty:stop. To get out of the sbt console, type exit.

Finally, let’s change the URL matcher. Change this

get("/") {
  "Hello world!"
}

to this:

get("/hello") {
  "Hello world!"
}

Visit it in your browser, at http://localhost:8080/hello. You’re done!

1.6. Summary

  • Microframeworks let you structure things exactly to your liking.
  • Scalatra applications are generated using the command g8.
  • The Scala build command sbt will download a functioning Scala environment.
  • Scalatra comes prebundled with a web server so you can get started coding without a lot of setup.
  • You can define HTTP actions with very little code.
..................Content has been hidden....................

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