Struts2でVolocityを使う

提供: Astarisk Works Wiki


目次

ライブラリの追加

descApache Velocity Site - The Apache Velocity Projectから Verocity本体とVelocityToolsをダウンロードしてWEB-INF/libのしたに配置する。

設定ファイルの置き場所を設定する

下の2行をstruts.xmlに設定することにより設定できる。

<constant name="struts.velocity.toolboxlocation" value="WEB-INF/velocity/toolbox.xml" />
<constant name="struts.velocity.configfile" value="WEB-INF/velocity/velocity.properties" />
パラメータ 説明
struts.velocity.toolboxlocation

VelocityToolsの設定ファイルの場所を指定する。

toolbox.xmlに記述したユーティリティークラスがVelocityのContextに追加される。

struts.velocity.configfile Velocityの設定ファイルの場所を指定する。

Struts1ではweb.xmlにVelocityServletを定義したが、Struts2ではVelocityManagerクラスが、resultタイプvelocityを設定したアクションで処理してくれるので不要となった。


toolbox.xmlの例

次の例はVelocityToolsで提供されているユーティリティを設定した例。自作のクラスを定義することもできる。

<?xml version="1.0" encoding="UTF-8"?>
<toolbox>
 <tool>
  <key>date</key>
  <scope>application</scope>
  <class>org.apache.velocity.tools.generic.DateTool</class>
 </tool>
 <tool>
  <key>params</key>
  <scope>request</scope>
  <class>org.apache.velocity.tools.view.tools.ParameterParser</class>
 </tool>
 <tool>
   <key>alternator</key>
<class>org.apache.velocity.tools.generic.AlternatorTool</class>    
<scope>application</scope> 
 </tool>
 <tool>
<key>list</key> <class>org.apache.velocity.tools.generic.ListTool</class> 
<scope>application</scope> 
 </tool>
</toolbox>

Velocity向けのStrutsTag

#s**tag **(...) ... #endという形式でVelocityのテンプレートで呼び出せる。

たとえば、urlタグの場合次のように使う。

#surl("value=/lib/default.js")

この例は次と等価

<s:url value="/lib/default.js"/>
個人用ツール