Spring MVC Setup with Kotlin

1. Overview

In this quick tutorial, we’ll take a look at what it takes to create a simple Spring MVC project with the Kotlin language.

This article focuses on Spring MVC. Our article Spring Boot and Kotlin describes how to set up a Spring Boot application with Kotlin.

2. Maven

For the Maven configuration, we need to add the following Kotlin dependencies:

<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib-jre8</artifactId>
    <version>1.1.4</version>
</dependency>

We also need to add the following Spring dependencies:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.10.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.10.RELEASE</version>
</dependency>

To compile our code, we need to specify our source directory and configure the Kotlin Maven Plugin in the build section of our pom.xml:

<plugin>
    <artifactId>kotlin-maven-plugin</artifactId>
    <groupId>org.jetbrains.kotlin</groupId>
    <version>1.1.4</version>
    <executions>
        <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
        <execution>
            <id>test-compile</id>
            <phase>test-compile</phase>
            <goals>
                <goal>test-compile</goal>
            </goals>
        </execution>
    </executions>
</plugin>

3. Spring MVC Configuration

We can use either the Kotlin annotation configuration or an XML configuration.

3.1. Kotlin Configuration

The annotation configuration is pretty simple. We setup view controllers, the template resolver, and the template engine. Thereafter we can use them to configure the view resolver:

@EnableWebMvc
@Configuration
open class ApplicationWebConfig : WebMvcConfigurerAdapter(), 
  ApplicationContextAware {

    private var applicationContext: ApplicationContext? = null

    override fun setApplicationContext(applicationContext: 
      ApplicationContext?) {
        this.applicationContext = applicationContext
    }

    override fun addViewControllers(registry:
      ViewControllerRegistry?) {
        super.addViewControllers(registry)

        registry!!.addViewController("/welcome.html")
    }
    @Bean
    open fun templateResolver(): SpringResourceTemplateResolver {
        return SpringResourceTemplateResolver()
          .apply { prefix = "/WEB-INF/view/" }
          .apply { suffix = ".html"}
          .apply { templateMode = TemplateMode.HTML }
          .apply { setApplicationContext(applicationContext) }
    }

    @Bean
    open fun templateEngine(): SpringTemplateEngine {
        return SpringTemplateEngine()
          .apply { setTemplateResolver(templateResolver()) }
    }

    @Bean
    open fun viewResolver(): ThymeleafViewResolver {
        return ThymeleafViewResolver()
          .apply { templateEngine = templateEngine() }
          .apply { order = 1 }
    }
}

Next, let’s create a ServletInitializer class. The class should extend AbstractAnnotationConfigDispatcherServletInitializer. This is a replacement for the traditional web.xml configuration:

class ApplicationWebInitializer: 
  AbstractAnnotationConfigDispatcherServletInitializer() {

    override fun getRootConfigClasses(): Array<Class<*>>? {
        return null
    }

    override fun getServletMappings(): Array<String> {
        return arrayOf("/")
    }

    override fun getServletConfigClasses(): Array<Class<*>> {
        return arrayOf(ApplicationWebConfig::class.java)
    }
}

3.2. XML Configuration

The XML equivalent for the ApplicationWebConfig class is:

<beans xmlns="...">
    <context:component-scan base-package="com.maixuanviet.kotlin.mvc" />

    <mvc:view-controller path="/welcome.html"/>

    <mvc:annotation-driven />

    <bean id="templateResolver" 
      class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".html" />
        <property name="templateMode" value="HTML" />
    </bean>

    <bean id="templateEngine"
          class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver" />
    </bean>


    <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />
        <property name="order" value="1" />
    </bean>

</beans>

In this case, we do have to specify the web.xml configuration as well:

<web-app xmlns=...>

    <display-name>Spring Kotlin MVC Application</display-name>

    <servlet>
        <servlet-name>spring-web-mvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-web-config.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-web-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

4. The Html Views

The corresponding HTML resource is located under the /WEB-INF/view directory. In the above view controller configuration, we defined a basic view controller, welcome.html. The content of the corresponding resource is:

<html>
    <head>Welcome</head>

    <body>
        <h1>Body of the welcome view</h1>
    </body>
</html>

5. Conclusion

After running the project, we can access the configured welcome page at http://localhost:8080/welcome.html.

In this article, we configured a simple Spring MVC project using both a Kotlin and XML configuration.

The complete source code is available over on GitHub.Comments are closed on this article!

Related posts:

Giới thiệu Google Guice – Dependency injection (DI) framework
Java Program to Implement Fenwick Tree
The Difference Between Collection.stream().forEach() and Collection.forEach()
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
An Intro to Spring Cloud Vault
OAuth2.0 and Dynamic Client Registration
Java Program to Implement Min Hash
Quick Guide to @RestClientTest in Spring Boot
Java Program to Implement the MD5 Algorithm
Java – File to Reader
Introduction to the Java ArrayDeque
Simplify the DAO with Spring and Java Generics
Introduction to Spring Boot CLI
Lập trình mạng với java
Apache Commons Collections OrderedMap
Spring Autowiring of Generic Types
Convert XML to JSON Using Jackson
New in Spring Security OAuth2 – Verify Claims
Spring MVC and the @ModelAttribute Annotation
Quản lý bộ nhớ trong Java với Heap Space vs Stack
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Java Program to Check whether Graph is a Bipartite using BFS
Encode/Decode to/from Base64
Java Program to Find Shortest Path Between All Vertices Using Floyd-Warshall’s Algorithm
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Perform Quick Sort on Large Number of Elements
How to Remove the Last Character of a String?
Java String to InputStream
Java Program to Implement Pagoda
Chương trình Java đầu tiên