みなさんこんにちは masa です。Java のフレームワークは何かと Spring ばかり触っていますが、久しぶりにプロジェクトをやってみると忘れてしまってる事ばかり(汗
Spring をやっている方ならテンプレートエンジンは Thymeleaf をお使いだと思いますが、以前ハマったポイントを記事に書き忘れていたので今回備忘録として残しておきます。
HTML を書き終わり、プロジェクトをビルドして画面を開こうとすると・・・エラーが発生
2015-09-29 22:47:58.030 ERROR 3372 --- [tp2117193231-14] o.thymeleaf.templateparser.ErrorHandler : [THYMELEAF][qtp2117193231-14] Fatal error during parsing org.xml.sax.SAXParseException: The element type "link" must be terminated by the matching end-tag "</link>". at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source) (以下スタックトレース)
Thymeleaf の HTML 解析は XMLチェックが走るため、閉じタグを省略したような書き方だと弾かれます。
これをどうにかしないといつまでたっても画面自体が表示されません。今さら HTML を書き直すのはさすがに厳しいので以下の手順で回避しましょう。
1.Thymeleaf のパース(構文解析)設定をゆるく変える
Thymeleafの設定をクラスを使って変えることもできますが、今回は application.properties ファイルを作って設定を入れてみます。
以下のように src/main/resources 直下に、空の application.properties ファイルを作ってください。
その中に以下の設定を書いて保存します。
spring.thymeleaf.mode=LEGACYHTML5 spring.thymeleaf.cache=false spring.thymeleaf.encoding=UTF-8
テンプレートモードを「LEGACYHTML5」へ変更してやることで HTML 解析がゆるくなります。
ひきつづき次の手順2.に進んでください。
2.NekoHTML ライブラリを入れる
今回 Maven から NekoHTML を入れる方法をご紹介します。ちなみに NekoHTML は HTMLパーサーです。
ネコというネーミングが気になりますが・・・。
Maven の pom.xml に以下を追記
<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency>
ライブラリを入れるために一度プロジェクトをビルドしてください。
これで Thymeleaf のパーサーがゆるい設定に変わりますので、あとはいつもどおりプロジェクトを実行してください。パーサーチェックが通って画面が無事表示されるはずです。
おまけ
そういえば前にクラスから Thymeleaf の設定をしようとして書いたコードが残っていました。
実行しても設定が変わらなかったのでどなたか解決策をご存知でしたら教えてくださいw
@Configuration
public class ThymeleafConfig {
@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ServletContextTemplateResolver servletContextTemplateResolver = new ServletContextTemplateResolver();
// servletContextTemplateResolver.setPrefix("/webapp/templates/");
servletContextTemplateResolver.setSuffix(".html");
servletContextTemplateResolver.setTemplateMode("LEGACYHTML5");
servletContextTemplateResolver.setCharacterEncoding("UTF-8");
servletContextTemplateResolver.setCacheable(false);
SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
springTemplateEngine.setTemplateResolver(servletContextTemplateResolver);
ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
thymeleafViewResolver.setCharacterEncoding("utf-8");
thymeleafViewResolver.setTemplateEngine(springTemplateEngine);
return thymeleafViewResolver;
}
}
それでは今日はここまで。Thymeleaf使いの方の一助になれば幸いです。

