Kotlin Web Application Tutorial

Filed Under: Java EE

In this tutorial, we’ll learn how to create Kotlin Web Application. We assume that you’re well versed with Java EE and Kotlin before going down the business end of this tutorial.

Kotlin Web Application

kotlin web app
Java EE is an extension of the Java SE and is used for creating web applications, rest web services and essentially anything related to web (not to forget microservices).

We’re also well aware that Kotlin, the latest language developed by JetBrains is statically typed and is based on JVM. It’s a fact that Kotlin is there with an aim to address the issues that Java Developers face.

Kotlin is concise, clear and has a very friendly syntax to learn and adapt to. Moreover, it is 100% interoperable with Java, compiles easily to Java 6 and Java 8 bytecode.

Knowing that Kotlin has so many advantages over Java, why not adopt it in our Java EE environment.

That’s what this tutorial is all about. We’ll be developing a simple Web Application using Kotlin, Servlets and Tomcat localhost server. Before that let’s see the challenges faced in integrating Kotlin in a Java EE Application.

  • Kotlin classes are final by default : Unless a class is declared as open class, it’s final by default. Most of the time, java ee application classes aren’t final, so instead of defining a class as open class every time (failing to do so can lead to a runtime exception), we can integrate the all-open plugin in our IntelliJ Idea build.gradle file.
  • Kotlin by default has constructors with named arguments: The no-arg compiler plugin generates an additional zero-argument constructor for classes with a specific annotation thereby allowing us to instantiate classes without a constructor explicitly specified.

Following are the modifications to be done in the build.gradle file of our project.


buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
    }
}

apply plugin: "kotlin-noarg"
apply plugin: "kotlin-allopen"

We’ll be creating an Http Web Application using Servlets in Kotlin.
Note: A servlet at its very core is a class which can handle HTTP requests (generally GET and POST requests).
Let’s create our first Hello World Web Application using Kotlin in IntelliJ Ultimate. That’s what is required for creating Java EE Applications.

Kotlin Web App Project

Select Gradle from the side bar, and choose the Kotlin(JVM) and Web in the right.
kotlin web application javaee project type

Setting the group, artifact and gradle settings as shown below.

kotlin javaee project group artifacts

Note: An artifact is an assembly of your project assets that you put together to test, deploy or distribute your software solution or its part. It’ll be invoked when we run our application on the server.

kotlin javaee project gradle settings

Configuring build.gradle


buildscript {
    ext.kotlin_version = '1.2.10'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

group 'com.journaldev.kotlinjavaee'
version '1.0-SNAPSHOT'

apply plugin: 'kotlin-platform-jvm'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    testCompile "junit:junit:4.12"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Let’s add the war plugin and the java ee dependency.


buildscript {
    ext.kotlin_version = '1.2.10'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

group 'com.jour.as'
version '1.0-SNAPSHOT'

apply plugin: 'kotlin-platform-jvm'
apply plugin: 'war'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'javax', name: 'javaee-api', version: '7.0'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    testCompile "junit:junit:4.12"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.11'
}


compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

The War plugin extends the Java plugin to add support for assembling web application WAR files.

Kotlin Web App Project Structure

kotlin javaee project structure
Since we’re dealing with Servlet only in this tutorial, let’s delete the jsp file. Create a new directory inside webapp, namely WEB-INF and add a file web.xml to it.

kotlin-javaee-project-structure-updated

The code for the MyServlet.kt (no .java extension) is given below.


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

@WebServlet(name = "Home", value = "/hello")
class MyServlet : HttpServlet() {
    override fun doGet(req: HttpServletRequest, res: HttpServletResponse) {
        res.writer.write("Hello, World!")
    }
}

The @WebServlet annotation is used to declare a servlet and map it to the specified values (servlet mapping). The value argument is compulsory. The name argument is optional over here.

The doGet function is used to print the input onto the screen.

Thanks to the @WebServlet annotation, deployment descriptor (web.xml file) is not required.

Note: The above annotation doesn’t work for versions below Tomcat 7.

Running the Kotlin Web Application

Edit the Configuration from the top right menu button:
kotlin javaee edit config

Setting Tomcat (a popular servlet container) as the server.
kotlin javaee run edit configuration

We’ve set the port number from 8080 to 8888 since the former was already in use. We’ve added the url path to the Hello World servlet that’ll launch when the project is run.

Let’s set up our artifact that’s needed for deployment.
kotlin javaee deployment

Note: If Tomcat isn’t installed, goto IntelliJ->Applications->Plugins->Tomcat Server

The output when the above project is run is given below.
kotlin web app output

Using web.xml for Servlet Mapping

Instead of setting the annotation, url pattern in the MyServlet.kt file, we can set it in the web.xml file which acts as the deployment descriptor file as shown below.


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

<web-app version="3.1"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         metadata-complete="false">

    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/hello/*</url-pattern>
    </servlet-mapping>

</web-app>

Let’s modify the MyServlet.kt file to display HTML as the input on the screen.


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

//@WebServlet(name = "Home", value = "/hello")
class MyServlet : HttpServlet() {
    override fun doGet(req: HttpServletRequest, res: HttpServletResponse) {
        //res.writer.write("Hello, World!")
        res.setContentType("text/html")
        val out = res.getWriter()

        out.print("<html><body>")
        out.print("<h3>JournalDev Tutorial</h3>")
        out.print("<h4>Servlet App Using Kotlin</h4>")
        out.print("</body></html>")

    }
}

Following is the final output that gets displayed on the screen.
kotlin javaee output 2

This brings an end to kotlin web application tutorial. You can download the final Kotlin web application project from the link below.

Comments

  1. Vad says:

    so what is the point of using kotlin ? didn’t see any benefit ?
    and actually J2ee is not about Web …

  2. Anitha says:

    Nice post about Kotlin Web Application.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages