Struts – DispatchActionの例
Struts DispatchActionクラスを使用して、同様の機能を1つのアクションにグループ化し、指定されたパラメーター値に応じて関数を実行します。 DispatchActionの使用方法を示す例を次に示します。
この例をダウンロード–Struts-DispatchAction-Example.zip
1. DispatchActionクラス
DispatchActionクラスを拡張してカスタムDispatchActionクラスを作成し、generateXML()とgenerateExcel()の2つのメソッドを宣言します。
MyCustomDispatchAction.java
package com.example.common.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
public class MyCustomDispatchAction extends DispatchAction{
public ActionForward generateXML(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
request.setAttribute("method", "generateXML is called");
return mapping.findForward("success");
}
public ActionForward generateExcel(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
request.setAttribute("method", "generateExcel is called");
return mapping.findForward("success");
}
}
2. Struts構成
値としてパラメーター属性と「アクション」を使用して、アクションマッピング「CustomDispatchAction」を宣言します。 パラメーター値「アクション」は、呼び出すメソッド– generateXML()またはgenerateExcel()を制御するために使用されます。
struts-config.xml
3. ページを見る
JSPページでは、パラメーターは次のように機能します。
1. /CustomDispatchAction.do?action=generateXMLはgenerateXML()メソッドを実行します。
2。 /CustomDispatchAction.do?action=generateExcelはgenerateExcel()メソッドを実行します。
TestForm.jsp
Struts - DispatchAction Example
html:link
|
a href
Generate XML File
|
Generate Excel File
DispatchExample.jsp
Struts - DispatchAction Example
4. 試して

「Generate XML File」リンクをクリックすると、http://localhost:8080/StrutsExample/CustomDispatchAction.do?action=generateXMLに転送されます

「Generate Excel File」リンクをクリックすると、http://localhost:8080/StrutsExample/CustomDispatchAction.do?action=generateExcelに転送されます
