DispatchAction会减少Action数量,并且可以对同类方法进行统一处理。一般情况下,Action是一个模块一个,ActionForm也是一个模块一个,如一个用户管理模块就只要一个Action和一个ActionForm。
DispatchAction的流程:
public abstract class DispatchAction extends Action {
public ActionForward execute(mapping, form, request, response) throws Exception {
// Get the parameter. This could be overridden in subclasses.
//得到parameter="command"
String parameter = getParameter(mapping, form, request, response);
// Get the method's name. This could be overridden in subclasses.
//得到如usermaintain.do?command=del中的"del"
String name = getMethodName(mapping, form, request, response, parameter);
// Prevent recursive calls
//如usermaintain.do?command=execute是不允许的,如允许会覆盖DispatchAction.execute(),造成安全问题。
if ("execute".equals(name) || "perform".equals(name)){
throw new ServletException(message);
}
// Invoke the named method, and return the result
return dispatchMethod(mapping, form, request, response, name);
}
protected ActionForward dispatchMethod(mapping, form, request, response, String name) throws Exception {
// Make sure we have a valid method name to call.
// This may be null if the user hacks the query string.
//name为空,即usermaintain.do。所以可以覆写unspecified()方法
if (name == null) {
return this.unspecified(mapping, form, request, response); //在这里抛出异常
}
// Identify the method object to be dispatched to
//name不为空,会拿到method,进行动态调用。
Method method = null;
try {
method = getMethod(name);
} catch(......) {......}
ActionForward forward = null;
try {//把相应的参数传递过去
Object args[] = {mapping, form, request, response};
//this 是当前的UserAction
forward = (ActionForward) method.invoke(this, args);
} catch(......) {......}
// Return the returned ActionForward instance
return (forward);
}
}