LoginSignup
3
1

More than 5 years have passed since last update.

Thymeleaf 3.0.8以降ではパーサーレベルコメントが正しく閉じられていないと例外になるよう変更されました

Posted at

Thymeleafのパーサーレベルコメントは、<!--/*から*/-->までがコメントと見なされ、出力されるHTMLには含まれません。

Thymeleafテンプレートの例
<p>FOO1</p>
<!--/* ここがコメント */-->
<p>FOO2</p>
<p>FOO3</p>
<p>FOO4</p>
出力されるHTMLの例
<p>FOO1</p>
<p>FOO2</p>
<p>FOO3</p>
<p>FOO4</p>

もし、*/を忘れるなどしてパーサーレベルコメントが正しく閉じられていなかった場合、Thymeleaf 3.0.7以前では<!--/*より後の内容が全てコメント内と見なされて、HTMLとして出力されないようになっていました。

コメントが正しく閉じられていない例
<p>FOO1</p>
<!--/* 最後の"*/"が抜けているため、このコメントは正しく閉じられていない -->
<p>FOO2</p>
<p>FOO3</p>
<p>FOO4</p>
出力されるHTMLの例(Thymeleaf3.0.7以前)
<p>FOO1</p>

これは挙動として分かりづらい(表示がおかしいのに例外も何も出ない)ので、Thymeleaf 3.0.8以降からは例外がスローされるようになりました。

3.0.8以降で発生する例外
HTTPステータス 500 - Internal Server Error

Type Exception Report

メッセージ Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/templates/hello/index.html]")

説明 The server encountered an unexpected condition that prevented it from fulfilling the request.

例外
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/templates/hello/index.html]")
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:986)
        ...

原因
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/templates/hello/index.html]")
org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241)
...

原因
org.attoparser.ParseException: Unfinished block structure <!--/*...*/-->
    org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
...

原因
java.io.IOException: Unfinished block structure <!--/*...*/-->
    org.thymeleaf.templateparser.reader.BlockAwareReader.read(BlockAwareReader.java:74)
        ...
注意 原因のすべてのスタックトレースは、のログに記録されています

実はコレ、僕がたまたま見つけて、IssueとしてThymeleafのGitHubに報告・提案したものです。

[Improvement] Throwing exception when parser-level comment block is not closed #632

おそらく、本番環境のコードでパーサーレベルコメントが正しく閉じられていないことは無いとは思いますが、互換性のない破壊的変更なので、注意してください。

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