最新バージョンの記事を掲載しました。
Struts2.5でThymeleaf3を使う に最新の記事を掲載しています。
Thymeleaf
Struts2の非公式ですが、Thymeleafプラグインがgithub:codework/struts2-thymeleaf-pluginにて公開されております。
このプラグインを導入すると、画面出力にThymeleafが扱え、Struts2のメッセージ出力やActionクラスのフィールド出力がカンタンです。
ThymeleafはHTMLをテンプレートに使えますので、HTMLのデザインや構成を崩さずに扱えます。
プラグインの導入方法
先ほど公開されているソースは、Struts2.3.16.3+Thymeleaf2.1.3を指定しております。
それも使うことができますが、Spring frameworkと組み合わせて使いたい場合などもある場合は、以下にForkしたものを公開しております。
github:A-pZ/struts2-thymeleaf3-plugin
これを取得してください。
Eclipse4.xであればgithubから入手後に、構成>mavenプロジェクトへ変換することで、すぐに使えます。
バージョン表記はStruts2にあわせています。
プラグインの設定
- Struts2-thymeleaf3プラグインを/WEB-INF/libに含めます。
- mavenであれば、先ほど導入したStruts2-thymeleaf3プラグインを指定します。
- Eclipse4.xのm2eプラグインであれば、Struts2-thymeleaf3プラグインのプロジェクトを、プロジェクト参照した後にプロジェクトアセンブリーに追加してください。
Thymeleafプラグインはレスポンスの形式を定義するResultを拡張したプラグインです。プラグインの標準では、継承元パッケージに struts-tymeleaf、result-typeにthymeleafを指定します。
Spring frameworkのbeanも使う場合は、result-typeにthymeleaf-springを指定してください。
以下にプラグインのstruts-plugin.xmlを示します。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<bean type="org.codework.struts.plugins.thymeleaf.spi.TemplateEngineProvider" name="default" class="org.codework.struts.plugins.thymeleaf.spi.DefaultTemplateEngineProvider" />
<package name="struts-thymeleaf" extends="struts-default">
<result-types>
<result-type name="thymeleaf" class="org.codework.struts.plugins.thymeleaf.ThymeleafResult"/>
</result-types>
</package>
</struts>
使い方
Actionの継承パッケージを result-typeにthymeleafを定義したものを指定します。標準では struts-thymeleaf で良いです。
その後、resultにthymeleafを指定します。
以下にActionクラスの例を示します。
@Namespace("/")
@ParentPackage("struts-thymeleaf")
@Results({
@Result(name = ActionSupport.SUCCESS, location = "form" , type="thymeleaf"),
})
@Slf4j
public class SampleSubscribeAction extends LumiActionSupport {
@Action("subscribe")
public String subscribe() throws Exception {
welcome = "おめでとう!Struts2-Thymeleafが実行できました。";
return SUCCESS;
}
@Getter @Setter
private String welcome;
}
このサンプルでは Struts2-conventionプラグイン ならびに project lombok のアノテーションを使っています。
HTMLテンプレートでActionクラスのフィールドを表示する
Actionクラスのフィールドを表示する方法は、action.(フィールド名)を指定するだけです。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" lang="ja">
<head>
</head>
<body>
<h2 th:text="${action.welcome}">ここはHTMLプロトタイプです</h2>
</body>
</html>
実行すると、h2タグのテキストが、Actionクラスのフィールドの値に置換されて表示されます。