1. 概要

このクイックチュートリアルでは、Kotlin言語を使用して単純なSpringMVCプロジェクトを作成するために必要なものを見ていきます。

この記事では、SpringMVCに焦点を当てています。 私たちの記事SpringBoot and Kotlin では、Kotlinを使用してSpringBootアプリケーションをセットアップする方法について説明しています。

2. Maven

Maven構成の場合、次のKotlin依存関係を追加する必要があります。

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

また、次のSpring依存関係を追加する必要があります。

<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>

コードをコンパイルするには、ソースディレクトリを指定し、pom.xmlのビルドセクションでKotlinMavenプラグインを構成する必要があります。

<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. SpringMVC構成

Kotlinアノテーション構成またはXML構成のいずれかを使用できます。

3.1. Kotlinの構成

注釈の構成は非常に簡単です。 ビューコントローラー、テンプレートリゾルバー、およびテンプレートエンジンをセットアップします。 その後、それらを使用してビューリゾルバーを構成できます。

@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 }
    }
}

次に、ServletInitializerクラスを作成しましょう。 クラスを拡張する必要があります AbstractAnnotationConfigDispatcherServletInitializer。 これは従来の代替品です web.xml 構成:

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構成

ApplicationWebConfigクラスに相当するXMLは次のとおりです。

<beans xmlns="...">
    <context:component-scan base-package="com.baeldung.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>

この場合、web.xml構成も指定する必要があります。

<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. HTMLビュー

対応するHTMLリソースは、 / WEB-INF /viewディレクトリの下にあります。 上記のViewController構成では、基本的なViewControllerwelcome.htmlを定義しました。 対応するリソースの内容は次のとおりです。

<html>
    <head>Welcome</head>

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

5. 結論

プロジェクトを実行した後、 http:// localhost:8080 /welcome.htmlで構成されたウェルカムページにアクセスできます。

この記事では、Kotlin構成とXML構成の両方を使用して単純なSpringMVCプロジェクトを構成しました。

完全なソースコードは、GitHubから入手できます。