Edit Page

Creating Web Applications with Http Servlets

Last Updated 1 November 2015
Source On GitHub
This tutorial walks us through the process of creating a simple controller using HttpServlet to display Hello World.

Java EE Http servlets can be used from Kotlin much like any other Java library or framework. We'll see how to make a simple controller that returns "Hello, World!".

Defining the project and dependencies

In this tutorial we're going to be using Gradle but the same can be accomplished using either IntelliJ IDEA project structure or Maven. For details on setting up Gradle to work with Kotlin, see Using Gradle. The main dependency required for using HTTP servlets is the JavaEE API:

dependencies {
    compile group: 'javax', name: 'javaee-api', version: '7.0'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

We also need to use the war plugin that helps us generate the corresponding WAR artifacts for running/deploying

apply plugin: war

To see the full Gradle script check out the source of the project on GitHub.

Creating a Home Controller

Once we have the build script defined with the correct dependencies, we can now create a controller

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

Running the application

Using IntelliJ IDEA we can easily run and debug the application in any of the possible application servers defined such as Tomcat, Glassfish or WildFly. In this case we're going to use Tomcat which has previously been defined as an application server in IntelliJ IDEA

In order to run, we need the corresponding WAR(s) for deploying. We can generate these using the war task in Gradle which can easily be executed via the Gradle tool window in IntelliJ IDEA.

Gradle Tasks

Alternatively, we can build it using the command line:

gradle war

The next step is to create a Run Configuration in IntelliJ IDEA under Tomcat / Local which deploys the WAR and starts up Tomcat.

Run Config

Once we run the application (using this previous run configuration), and on successful deployment, we should be able to navigate to the browser with the correct url and see the response:

Browser Run