JSP and Kotlin


#1

Can I create a JSP page using Kotlin?


#2

JSP is a syntactic sugar over Java. While it is possible to create a KSP standard that translates to Kotlin instead of Java it does not exist as core Kotlin. However as JSP pages are just a different way to write servlets (working well for html, not that useful if most of the code is Java anyway) you can use servlets directly. If you combine that with kotlinx.html you can use the DSL to generate HTML in an actual typesafe way.


#3

Two things to note here:

  1. Even though JSP’s cannot contain scriptlets written in Kotlin, they can contain scriptlets written in Java and that Java can easily call Kotlin classes thanks to Kotlins’s nice two-way interop. Sweet!!
  2. JSP EL expressions can reference DTO’s written in Kotlin. And DTO’s are much easier to write in Kotlin.

#4

I use JSP technology once in a blue moon - but I am perplexed as to how much/what it will take to compile JSP with Kotlin instead of Java. (in all honesty… when I do Kotlin I think Kotlin, and I really don’t want to jump between the 2)

If one looks at the page directive it even makes provision (in concept to my eye) by having a language=“java” attribute; or am I missing the bus somewhere.


#5

This is a follow up to my original post.

We have 3 use-cases of JSP in our legacy app:

Simple Templates.
Simply using JSP as a template language to transform DTOs into HTML snippets. Very small amount of logic/java in the JSP page.

The conversion process was very painless because Kotlin classes appear to Java as JavaBeans and work seamlessly from JSP.

Complex Template
Same use-case as #1 but with much more complex logic (in the form of JSTL logic tags or java-in-the-jsp) to transform the DTOs into HTML.

For these pages, I replaced the JSP with [Kotlin HTML Builder (https://github.com/Kotlin/kotlinx.html). This was a wonderful experience. In the future I plan to convert all server-side HTML generation to this technique.

HTTP Handler. As a general way to create server-side http handlers that serve up JSON. (I have always thought this is a highly underrated technique for creating REST APIs with no additional frameworks.)

This was also painless, because most of the JSP pages look like this:

<% processCustomerRequest(request,response); %>

Where processCustomerRequest is written in Kotlin.