虽然DispatchAction类是一个抽象类,但其中却没有一个抽象方法。因此,DisplatchAction的子类不用实现任何DisplatchAction类中的方法。但如果要处理Action代码,就必须根据相应的Action来编写Action方法。一个Action方法除了方法名和execute方法不一样外,其他的都和execute方法完全一样。但编写Action方法时要注意,Action方法名必须和用于指定动作的请求参数值一致(大小写也必须一致)。在下面的例子中演示了通过DispatchAction类实现方法和Action的对应。在这个例子中,有三个方法:fr、en和unspecificed。其中fr和en是两个Action方法,分别用于将当前页面转发到法文和英文页面,而当用于指定Action的请求参数不存在时,则调用unspecificed方法(在这个方法中将当前页面转发到中文页面)。在这个程序中使用的用于指定Action的请求参数为language(读者可以指定自己的请求参数)。
在<samples工程目录>\src\action目录建立一个MyDispatchAction.java文件,代码如下:
import javax.servlet.RequestDispatcher;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.actions.*;
public class MyDispatchAction extends DispatchAction
{
// forward到法文页面
public ActionForward fr(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{
try
{
RequestDispatcher rd = request.getRequestDispatcher("/newGlobal.jsp?language=fr");
rd.forward(request, response);
}
catch (Exception e)
{
}
return null;
}
// forward到英文页面
public ActionForward en(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{
try
{
RequestDispatcher rd = request.getRequestDispatcher("/newGlobal.jsp?language=en");
rd.forward(request, response);
}
catch (Exception e)
{
}
return null;
}
// 在未使用language=fr和language=en作为访问参数的情况时调用这个方法
protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
try
{
// forward到中文页面
RequestDispatcher rd = request.getRequestDispatcher("/newGlobal.jsp?language=zh");
rd.forward(request, response);
}
catch (Exception e)
{
}
return null;
}
}
显示英文页面:
http://localhost:8080/samples/locale.do
{
return this.unspecified(mapping, form, request, response);
}
ActionForm form, HttpServletRequest request,
HttpServletResponse response, String name) throws Exception
{
ActionForward af = null;
// 在language参数值为空串的情况下,将方法名赋为null
if (name != null) // name表示Action方法名,也是language的参数值
if (name.equals(""))
name = null;
try
{
af = super.dispatchMethod(mapping, form, request, response, name);
}
catch(NoSuchMethodException e) // 处理Action方法未找到的情况
{
// 在language的参数值没有对应的Action方法时,将方法名赋为null
name = null;
af = super.dispatchMethod(mapping, form, request, response, name);
}
return af;
}
// 当language的参数值为execute或perfore时,必须将方法名赋为null,否则会出现递归调用
protected String getMethodName(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response,
String parameter) throws Exception
{
String methodName = super.getMethodName(mapping, form, request, response, parameter);
if ("execute".equals(methodName) || "perform".equals(methodName))
return null; // 如果访问的是execute和perform,直接将方法名设为null
return methodName;
}
http://localhost:8080/samples/locale.do?language=
http://localhost:8080/samples/locale.do?language=unknown