すべてのURLでの共通のエラーページなど、デフォルトとして使用する遷移先を毎回指定するのは面倒ですよね。
<!-- struts-config.xml -->
<action-mappings>
<action path="/A" type="MapAction">
<forward name="common" path="/pages/Common.jsp"></forward>
</action>
<action path="/B" type="MapAction">
<forward name="common" path="/pages/Common.jsp"></forward>
</action>
<action path="/C" type="MapAction">
<forward name="common" path="/pages/Common.jsp"></forward>
</action>
</action-mappings>
そんなときは、全てのaction要素で使用可能な遷移先をglobal-forwards要素で定義します。
<!-- struts-config.xml -->
<?xml version="1.0" encoding="ISO-8859-1" ?>
<struts-config>
<global-forwards>
<forward name="common" path="/pages/Common.jsp">
</forward></global-forwards>
<action-mappings>
<action path="/A" type="MapAction">
<action path="/B" type="MapAction">
<action path="/C" type="MapAction">
<forward name="common" path="/pages/C.jsp"></forward>
</action>
</action></action></action-mappings>
</struts-config>
Strutsの流れをイメージする
今回はイメージとしてA,B,Cさんの案内役(action要素)がいるとします。この人達は共通の行動をします。(同じActionクラスを実行)
Actionクラスにはただ、Common.jspへ向かえと書いてあるだけです。
<%-- Common.jsp --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<html:html>
<html:base>
<h1><%=request.getRequestURI()%></h1>
<h3>global-forwardsで定義された、みんなのページです!</h3>
</html:base></html:html>
しかし、Cさんだけは呼び名は同じCommon.jspでも違う場所を知っています。
<%-- C.jsp --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<html:html>
<html:base>
<h1><%=request.getRequestURI()%></h1>
<h3>actionの子要素forwardで定義されたCさんだけのページです。</h3>
</html:base></html:html>
用意したURLにアクセスしてみる
「A.do」、「B.do」にアクセス、A,Bさんに案内役を頼むと下記のページに案内されました。
ところが「C.do」、Cさんに案内してもらうと秘密のページを教えてくれます。
このことから、global-forwardsよりactionの子要素で定義されたforwardが優先されることがわかりました。下記のソースで言うと、ハイライトされている部分です。
<!-- struts-config.xml -->
<struts-config>
<global-forwards>
<forward name="common" path="/pages/Common.jsp">
</forward></global-forwards>
<action-mappings>
<action path="/C" type="MapAction">
<forward name="common" path="/pages/C.jsp"></forward>
</action>
</action-mappings>
</struts-config>