0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

@ModelAttributeでちょっとはまった話。

Posted at

使用環境

  • フレームワーク springBoot:3.1.1
  • 使用言語:Kotlin

メモで記載します。学習中Formオブジェクトをバインドしてタイムリーフ表示を実施したところ、エラーが発生しました。

エラー

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sat Jul 08 22:40:05 JST 2023
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "URL [file:src/main/resources/templates/issues/creationForm.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "URL [file:src/main/resources/templates/issues/creationForm.html]")

ソースコード

Controller

com/example/its/web/issue/IssueController.kt
@Controller
@RequestMapping("/issues")
class IssueController() {
    @GetMapping("/creationForm")
    fun register(@ModelAttribute form: IssueForm): String {
        return "issues/creationForm"
    }
}

Form

com/example/its/web/issue/IssueForm.kt
data class IssueForm(
    val summary: String?,
    val description: String?
)

Thymeleaf

templates/issues/creationForm.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>課題作成 | 課題管理アプリケション</title>
</head>
<body>
<h1>課題作成</h1>
<form th:action="@{/issues}" th:method="post" th:object="${form}">
    <div>
        <label for="summaryInput">概要</label>
        <input type="text" id="summaryInput" th:field="*{summary}">
    </div>
    <div>
        <label for="descriptionInput">説明</label>
        <input type="textarea"  row="10" id="descriptionInput" th:field="*{description}">
    </div>
    <div>
        <input type="submit">
    </div>
</form>
</body>
</html>

解決策

Thymeleafのth:object="${form}th:object="${issueForm}"とすることで改善

原因

コントローラーメソッドの引数名として form を指定した場合でも、@ModelAttribute("issueForm") のように明示的に指定しない限り、デフォルトの名前はクラス名の先頭を小文字にしたものになるため(この場合は "issueForm")。

普通にmodel.addAttributeでもいけるんでしょうが、へーとなった夜でした

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?