與LookupDispatchAction、DispatchAction不同,MappingDispatchAction類並不通過請求參數來指定動作,而是將一個Struts動作對應於一個Action方法。下面的例子演示了如何使用MappingDispatchAction類來將Struts動作和Action方法相對應。
Action類的實現代碼:
package action;
import org.apache.struts.actions.MappingDispatchAction;
……
public class MyMappingDispatchAction extends MappingDispatchAction
{
public ActionForward pdf(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// 生成pdf文件
}
public ActionForward html(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// 生成html文件
}
public ActionForward unspecified(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// 處理默認動作
}
}
上面的代碼有兩個Action方法:pdf和html,分別用來生成pdf和html文件。還有一個unspecified方法用來處理默認動作。
我們可以使用如下的代碼來配置MyMappingDispatchAction類:
<action path="/pdf" type = "action.MyMappingDispatchAction" parameter="pdf" />
<action path="/html" type = "action.MyMappingDispatchAction" parameter="html" />
可以通過如下的URL來訪問pdf和html動作,分別會調用MyMappingDispatchAction類的pdf和html方法:
http://localhost:8080/samples/pdf.do
http://localhost:8080/samples/html.do