struts.xml にはOGNL式が書ける。
例えばLocaleの設定によってResultで表示するファイル変えたりする事ができる。
<result>${ "/"+locale.getLanguage() +"/list.jsp" }</result>
しかし、全部のresultをこんな風に書くと見た目が汚いので、テンプレートの置き換えが可能な新しいresultを作った
TemlateResult.java
package jp.co.hershe.struts2.util; import org.apache.struts2.dispatcher.ServletDispatcherResult; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.Result; /** * Resut のLocation をKeyとして Template に従い置き換える * * OGNLのexpressionを何度も書きたくないので作成 * * @author mikuni * */ public class TemplateResult implements Result { // bodyコンテントを何に設定するかの hint public static final String DEFAULT_PARAM = "location"; // 通常の Result 処理 ServletDispatcherResult result; // 表示ページ String location; // 対象のテンプレート( 置き換え後 OGNL評価を行う ) String template; // 置き換えるキー文字列 String key; // コンストラクタ public TemplateResult() { super(); result = new ServletDispatcherResult(); } // コンストラクタ public TemplateResult(String location) { super(); this.location = location; result = new ServletDispatcherResult(); } public void setTemplate( String template ) { this.template = template; } public void setKey( String key ) { this.key = key; } public void setLocation( String location ) { this.location = location; } public void setParse( boolean arg0 ) { result.setParse(arg0); } public void setEncode( boolean arg0 ) { result.setEncode(arg0); } public void execute(ActionInvocation invocation) throws Exception { String loc = template.replace(key, location); result.setLocation(loc); result.execute(invocation); } }
<result-types> <result-type name="templ" class="jp.co.hershe.struts2.util.TemplateResult" default="true"> <param name="template">"/"+locale.getLanguage() +"#file#"</param> <param name="key">#file#</param> </result-type> </result-types>
とパッケージで宣言すると
<result>${ "/"+locale.getLanguage() +"/list.jsp"}</result>
は
<result result="templ">/list.jsp</result>
と書けてさらに default指定しているので、
<result>/list.jsp</result>
こう書ける。
で Locale がjaのときは /ja/list.jsp で en の時は /en/list.jsp を表示する。