Java Servlets Written in Clojure

Yes, you can write Java Servlets in Clojure.

Create a Clojure Servlet project with the following command.

The important parts of the command are ‘luminus’, which is the framework used to create the Servlet, and ‘+war’, which adds uberwar and Servlet routes to the project. This creates a file called ‘handler.clj’ that replaces the traditional Java Servlet file. The configurations for the Clojure Servlet are found in ‘project.clj’ in the :uberwar  section of the configurations.

By default the lein command above creates a project that will build a WAR file called my-clj-servlet.war, and when deployed will deploy in the my-clj-servlet context, meaning on a default installation of Tomcat you would find the link at http://localhost:8080/my-clj-servlet/

It is important to note that the resulting project from the above lein command actually won’t work as a Servlet, yet. But, we’ll fix that below. The project is configured in the hopes that you can run it from a Servlet container or as a standalone app, and with some massaging, you could. However, this tutorial only focuses on how to get the project compiling as a Java Servlet written in Clojure. If there is enough interest, I’ll write another tutorial on how to get the default project working as a standalone app, and a Servlet.

Any initialization code you want to write for your Clojure Servlet goes in the ‘handler.clj’ file in the ‘init’ function. The init function starts out looking like this…

The shutdown code for your Clojure Servlet goes in the ‘destroy’ function in ‘handler.clj’. The destroy function starts out like this …

The Java Servlet code that normally goes in the Servlet’s doGet() or doPost() methods, goes in the handler.clj file in the app function. The app function should take a request argument and return a response of some sort. For example, this one returns a simple web page.

Notice the app function takes a request argument. This is an important change from the default project produced from the initial project template.

Build your WAR file with the command lein uberwar . This creates a WAR files and places it in target/my-clj-servlet.war. Deploy the resulting war file to Tomcat or any other servlet container to enjoy the fruits of your labor.

But there’s more!

Remember the request parameter our app function takes? It contains all kinds of goodies. Specifically, it has the following keys

As you have probably already guessed, :servlet-request is your HttpServletRequest implementation. You can use it to grab incoming parameters and use them in your Servlet. For example, if you called your servlet with the following link,

then your app function could be rewritten as follows.

Just for reference, your entire handler.clj probably looks like this.

Need more details? Checkout the lein-uberwar project on github, or the Luminus framework documentation.

Leave a Reply

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