DEV Community

kaede
kaede

Posted on

Kotlin Springboot -- Part 3 Controller を Resource 層にして Usecase につなげる

HTMLController を SpringbootResource にする

package com.example.springboot import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.ui.set import org.springframework.web.bind.annotation.GetMapping @Controller class HtmlController { @GetMapping("/") fun nanika(model: Model): String { model["title"] = "SpringBlog" return "index" } } 
Enter fullscreen mode Exit fullscreen mode

これが HtmlContorller.kt というファイルで書かれていて

Image description

アプリを起動すると index に渡したものを表示する

MVC のアーキにしたがってコントローラーと名付けていた

CA に変えるので リソースにする

@Controller class SpringbootResource { @GetMapping("/") fun root(model: Model): String { model["title"] = "Springboot Root" return "index" } } 
Enter fullscreen mode Exit fullscreen mode

これでリソースとして使う。


Usecase を呼びやすくする

fun getTaroHanakoName():String { val taroName = taro.findName() val hanakoName = hanako.findName() return "$taroName,$hanakoName"; } 
Enter fullscreen mode Exit fullscreen mode

Usecase の関数を呼びやすいまとめるものにする


SpringbootResource で Model と Template を噛ませながら Usecase を呼ぶ

 @GetMapping("/names") fun taro(model:Model): String { model["title"] = getTaroHanakoName() return "index" } 
Enter fullscreen mode Exit fullscreen mode

model と index のテンプレートを噛ませて
Usecase からの値を出力する

Image description

これで /names にアクセスした時に Usecase -> Driver まで動いて
中身を web に出せた。

2022-08-29 00:14:57.777 ERROR 1463816 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "Taro": Error resolving template [Taro], template might not exist or might not be accessible by any of the configured Template Resolvers 
Enter fullscreen mode Exit fullscreen mode

なお、 Thymleaf を使ってしまっているので
Template と Model ナシで直接 Usecase を
Getmapping に噛ませ用途すると失敗する。

まとめ

Kotlin Springboot で Rest/Resource 層から
Usecase -> Driver としてデータをとってくるためには

旧来の Controller の書き方で書いて、名前を Resource にして
Usecase の呼び出しの結果を model に渡して
template で表示する。

Top comments (0)