LoginSignup
1
0

More than 5 years have passed since last update.

global-forwardsとaction、どちらの子要素のfowardが優先されるのか調べてみた

Posted at

すべての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>&lt;%=request.getRequestURI()%&gt;</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>&lt;%=request.getRequestURI()%&gt;</h1>
<h3>actionの子要素forwardで定義されたCさんだけのページです。</h3>

</html:base></html:html>

用意したURLにアクセスしてみる

「A.do」、「B.do」にアクセス、A,Bさんに案内役を頼むと下記のページに案内されました。

struts_07_141007.jpg

ところが「C.do」、Cさんに案内してもらうと秘密のページを教えてくれます。

struts_08_141007.jpg

このことから、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>
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0