Struts DispatchAction类用于将相似的功能分组为单个动作,并根据给定的参数值执行该功能。 这是显示DispatchAction用法的示例。
1. DispatchAction类
通过扩展DispatchAction类,创建一个自定义DispatchAction类,并声明两个方法– generateXML()和generateExcel() 。
MyCustomDispatchAction.java
package com.mkyong.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”,其参数属性为“ action”。 参数值“ action”用于控制要调用的方法– generateXML()或generateExcel()。
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
<struts-config>
<action-mappings>
<action
path="/CustomDispatchAction"
type="com.mkyong.common.action.MyCustomDispatchAction"
parameter="action"
>
<forward name="success" path="/pages/DispatchExample.jsp"/>
</action>
<action
path="/Test"
type="org.apache.struts.actions.ForwardAction"
parameter="/pages/TestForm.jsp"
>
</action>
</action-mappings>
</struts-config>
3.查看页面
在JSP页面中,参数的工作方式如下:
1. /CustomDispatchAction.do?action=generateXML将执行generateXML()方法。
2. /CustomDispatchAction.do?action=generateExcel将执行generateExcel()方法。
TestForm.jsp
Struts - DispatchAction Example
html:link
action="/CustomDispatchAction.do?action=generateXML">
|
action="/CustomDispatchAction.do?action=generateExcel">
a href
DispatchExample.jsp
Struts - DispatchAction Example
4.测试
http:// localhost:8080 / StrutsExample / Test.do
如果单击“ 生成XML文件 ”链接,它将转发到http:// localhost:8080 / StrutsExample / CustomDispatchAction.do?action = generateXML
如果单击“ Generate Excel File ”链接,它将转发到http:// localhost:8080 / StrutsExample / CustomDispatchAction.do?action = generateExcel
翻译自: https://mkyong.com/struts/struts-dispatchaction-example-2/