Kotlin でサーブレット

f:id:Naotsugu:20150502164325p:plain

Kotlin で簡単なサーブレットを。

HelloWorld.kt
package example

import javax.servlet.annotation.WebServlet
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

[WebServlet(name = "HelloWorld", urlPatterns = array("/HelloWorld"))]
class HelloWorld : HttpServlet() {

  protected override fun doGet(request : HttpServletRequest?, 
                               response : HttpServletResponse?) {
    val text = """
      <html>
      <html><head><title>HelloServlet</title></head>
      <body><h1>Hello Servlet</h1></body>
      </html>
      """
    response?.setContentType("text/html; charset=UTF-8")
    response?.getWriter()?.println(text)
  }
}

kotlin のシンタックスハイライト効かないので読みにくいかもしれません。

Java だと以下のようになります。

@WebServlet(name = "HelloWorld", urlPatterns = { "/HelloWorld" })
public class HelloWorld extends HttpServlet {

  protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter writer = response.getWriter();
    writer.println("<html>");
    writer.println("<html><head><title>HelloServlet</title></head>");
    writer.println("<body><h1>Hello Servlet</h1></body>");
    writer.println("</html>");
  }
}


ビルドスクリプトは以下です。

build.gradle
buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:0.11.91.2'
        classpath 'com.bmuschko:gradle-cargo-plugin:2.1'
    }
}

apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'war'
apply plugin: 'com.bmuschko.cargo'

sourceCompatibility = 1.8
targetCompatibility = 1.8

[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

repositories {
  mavenCentral()
}

dependencies {
  compile 'org.jetbrains.kotlin:kotlin-stdlib:0.11.91.2'
  providedCompile 'org.jboss.spec:jboss-javaee-all-7.0:1.0.2.Final'
  testCompile 'junit:junit:4.11'
}

cargo {
  containerId = 'wildfly8x'
  deployable {
    file = file(war.archivePath)
  }
  local {
    installer {
      installUrl = 'http://download.jboss.org/wildfly/8.2.0.Final/wildfly-8.2.0.Final.zip'
      downloadDir = new File(buildDir, "download")
      extractDir = file("wildfly")
    }
    containerProperties { property 'cargo.jboss.configuration', 'standalone-full' }
  }
}

cargo で wildfly 8.2 を準備しています。

実行

cargoRunLocal すれば良いです。

$ ./gradlew war cargoRunLocal

:compileKotlin
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:war
:cargoRunLocal
Press Ctrl-C to stop the container...

f:id:Naotsugu:20150502190809p:plain

簡単ですね。