package kr.ac.kumoh.s20210353.w24w05thymeleaf.model
data class Song(
var id: Int,
var title: String,
var singer: String,
)
package kr.ac.kumoh.s20210353.w24w05thymeleaf.repository
import kr.ac.kumoh.s20210353.w24w05thymeleaf.model.Song
import org.springframework.stereotype.Repository
@Repository
class SongRepository {
protected val songs = listOf(
Song(1, "일레븐", "아이브"),
Song(2, "눈의꽃", "박효신"),
Song(3, "사랑에 연습이 있었다면", "임재현"),
)
val songsSize: Int
get() = songs.size
fun getSong(index: Int) = songs[index]
fun fetchSong() = songs
}
package kr.ac.kumoh.s20210353.w24w05thymeleaf.service
import kr.ac.kumoh.s20210353.w24w05thymeleaf.repository.SongRepository
import org.springframework.stereotype.Service
import kotlin.random.Random
@Service
class SongService(val repository: SongRepository)
{
fun getRandomSong() = repository.getSong(Random.nextInt(repository.songsSize))
fun getAllSongs() = repository.fetchSong()
}
package kr.ac.kumoh.s20210353.w24w05thymeleaf.controller
import kr.ac.kumoh.s20210353.w24w05thymeleaf.service.SongService
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
@Controller
class SongController(val service: SongService)
{
@GetMapping("/song/random")
fun getRandomSong(model: Model): String
{
model.addAttribute("song", service.getRandomSong()) //이렇게 주면 json 형식으로 나옴
//model.addAttribute("singer", service.getRandomSong().singer)
//model.addAttribute("id", service.getRandomSong().id)
return "random"
}
}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Thymeleaf</title>
</head>
<body>
<h2>추천 노래</h2>
<p>제목 : [[${song.title}]]</p>
<p>가수 : [[${song.singer}]]</p>
<p>순서 : [[${song.id}]]</p>
</body>
</html>