前两天有位哥们问起Struts的ActionForm,翻了翻源码。
RequestProcessor的202与203行,以struts1.2为准。
// Process any ActionForm bean related to this request
ActionForm form = processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
330-331行
// Create (if necessary) a form bean to use
ActionForm instance = RequestUtils.createActionForm
(request, mapping, moduleConfig, servlet);
RequestUtils的方法源码:
public static ActionForm createActionForm(
HttpServletRequest request,
ActionMapping mapping,
ModuleConfig moduleConfig,
ActionServlet servlet) {
// Is there a form bean associated with this mapping?
String attribute = mapping.getAttribute();
if (attribute == null) {
return (null);
}
// Look up the form bean configuration information to use
String name = mapping.getName();
FormBeanConfig config = moduleConfig.findFormBeanConfig(name);
if (config == null) {
log.warn("No FormBeanConfig found under '" + name + "'");
return (null);
}
ActionForm instance = lookupActionForm(request, attribute, mapping.getScope());
// Can we recycle the existing form bean instance (if there is one)?
try {
if (instance != null && canReuseActionForm(instance, config)) {
return (instance);
}
} catch(ClassNotFoundException e) {
log.error(servlet.getInternal().getMessage("formBean", config.getType()), e);
return (null);
}
return createActionForm(config, servlet);
}
RequestUtils另外一方法:
private static ActionForm lookupActionForm(HttpServletRequest request, String attribute, String scope)
{
// Look up any existing form bean instance
if (log.isDebugEnabled()) {
log.debug(
" Looking for ActionForm bean instance in scope '"
+ scope
+ "' under attribute key '"
+ attribute
+ "'");
}
ActionForm instance = null;
HttpSession session = null;
if ("request".equals(scope)) {
instance = (ActionForm) request.getAttribute(attribute);
} else {
session = request.getSession();
instance = (ActionForm) session.getAttribute(attribute);
}
return (instance);
}
从以上可以看出,Struts先是到struts-config.xml配置的request或session里去拿,拿不到则创建。
需要注意的是,对DynaActionForm有一些处理上差异。