通过源代码了解运行路径
1 解析请求路径得到path
path = request.getServletPath();
2 根据path得到一个ActionMapping
封装一个action节点所有信息,包括子节点信息,比如forward
3 得到formBean
a 在scope指向的范围内寻找,名字以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);
b 如果找到返回,没找到创建,为了效率
c 把fromBean放到scope所指向的范围
if ("request".equals(mapping.getScope())) {
request.setAttribute(mapping.getAttribute(), instance);
} else {
HttpSession session = request.getSession();
session.setAttribute(mapping.getAttribute(), instance);
}
d 调用formBean的reset方法(重置)因为此formBean有可能是从session或request的范围取出的,它还保留上次业务逻辑的数值
e 根据请求参数给formBean属性赋值
- Enumeration names = request.getParameterNames(); 得到客户端请求参数名的集合
- 循环得到每个名称,并求值parameterValue = request.getParameterValues(name);
- BeanUtils.populate(bean, properties)给fromBean赋值
f 根据action节点的Validate属性决定是否验证。
if (!mapping.getValidate()) {
return (true);
}
ActionMessages errors = form.validate(mapping, request);
if ((errors == null) || errors.isEmpty()) {
if (log.isTraceEnabled()) {
log.trace(" No errors detected, accepting input");
}
return (true);
}
如果返回的ActionMeessages(ActionErrors为ActionMeessages子类)为null或者长度为0,返回true继续运行。非空的话则跳转到input属性指向的界面。
4 得到ActionBean
Action instance = null;
synchronized (actions) {
// Return any existing Action instance of this class
instance = (Action) actions.get(className);
if (instance != null) {
if (log.isTraceEnabled()) {
log.trace(" Returning existing Action instance");
}
return (instance);
}
instance.setServlet(this.servlet);
actions.put(className, instance);
}
5 调用actionBean的execute方法,返回ActionForward对象
6 请求转发或者定向到新界面
if (forward.getRedirect()) { // only prepend context path for relative uri if (uri.startsWith("/")) { uri = request.getContextPath() + uri; } response.sendRedirect(response.encodeRedirectURL(uri)); } else { doForward(uri, request, response); // Unwrap the multipart request, if there is one. if (request instanceof MultipartRequestWrapper) { request = ((MultipartRequestWrapper) request).getRequest(); } RequestDispatcher rd = getServletContext().getRequestDispatcher(uri); if (rd == null) { response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, getInternal().getMessage("requestDispatcher", uri)); return; } rd.forward(request, response); }