Getting started with xsbt-web-plugin

May 27, 2013

This project shows how to build a basic Scala Web application using sbt and xsbt-web-plugin. To get started, either clone this project or follow the steps below to recreate it.

Starting from scratch

Create a new empty project:

$ mkdir xwp-template
$ cd xwp-template

Set up the project structure:

$ mkdir project
$ mkdir -p src/main/scala
$ mkdir -p src/main/webapp/WEB-INF

Configure sbt:

project/build.properties:

sbt.version=0.13.6

project/build.sbt:

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "3.0.1")

build.sbt:

name := "xwp-template"

organization := "com.earldouglas"

version := "0.1.0-SNAPSHOT"

scalaVersion := "2.10.2"

libraryDependencies += "javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided"

enablePlugins(JettyPlugin)

Add a servlet:

src/main/scala/XwpTemplateServlet.scala:

package com.earldouglas.xwptemplate

import scala.xml.NodeSeq
import javax.servlet.http.HttpServlet

class XwpTemplateServlet extends HttpServlet {

  import javax.servlet.http.HttpServletRequest
  import javax.servlet.http.HttpServletResponse

  override def doGet(req: HttpServletRequest, res: HttpServletResponse) {

    res.setContentType("text/html")
    res.setCharacterEncoding("UTF-8")

    val resBody: NodeSeq =
      <html>
        <head>
          <title>Hello, world!</title>
        </head>
        <body>
          <h1>Hello, world!</h1>
        </body>
      </html>

    res.getWriter.write(resBody.toString)
  }
}

src/main/webapp/WEB-INF/web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>

  <servlet>
    <servlet-name>xwp template</servlet-name>
    <servlet-class>
      com.earldouglas.xwptemplate.XwpTemplateServlet
    </servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>xwp template</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

</web-app>

Launching from sbt

From sbt, run the command jetty:start:

> jetty:start
2017-04-03 21:44:14.496:INFO:oejr.Runner:main: Runner
2017-04-03 21:44:14.620:INFO:oejs.Server:main: jetty-9.4.1.v20170120
2017-04-03 21:44:14.838:INFO:oejs.AbstractConnector:main: Started \
  ServerConnector@30b8a058{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2017-04-03 21:44:14.838:INFO:oejs.Server:main: Started @456ms

The Web application is now running at http://localhost:8080. Take a look with a Web browser, or via curl:

$ curl -i localhost:8080
HTTP/1.1 200 OK
Date: Tue, 04 Apr 2017 03:45:23 GMT
Content-Type: text/html;charset=utf-8
Content-Length: 154
Server: Jetty(9.4.1.v20170120)

<html>
  <head>
    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>
  </body>
</html>

Deploying to a servlet container

To build a WAR file suitable for deployment, run the command package from sbt:

> package
[success] Total time: 0 s, completed Apr 3, 2017 9:46:03 PM

The WAR file can be found in target/scala-2.10/xwp-template_2.10-0.1.0-SNAPSHOT.war.