程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 層層遞進Struts1(五)之處理流程

層層遞進Struts1(五)之處理流程

編輯:關於JAVA

這篇博客我們深入Struts框架執行部分源碼,從ActionServlet的process函數開始,看一下其內在的執行 過程。

流程圖

以下流程圖展示的是ActionServlet和RequestProcessor兩個類用到的函數,如RequestProcessor調用的 其它類的函數不再說明。

函數說明

我們選擇幾個重要的函數說明,其它函數則簡單說明一下即可。

ActionServlet

process

/** 
* <p>Perform the standard request processing for this request, and create
* the corresponding response.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception is thrown
*/ protected void process(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ModuleUtils.getInstance().selectModule(request, getServletContext());
ModuleConfig config = getModuleConfig(request);
RequestProcessor processor = getProcessorForModule(config);
if (processor == null) {
processor = getRequestProcessor(config);
}
processor.process(request, response);
}
}

在調試時首先進入這個函數(Tomcat啟動完畢,產生請求後),這個函數的作用是獲取加載階段產生的 Module對象,產生struts邏輯處理的主要對象RequestProcessor。

RequestProcessor

process

/** 
* <p>Process an <code>HttpServletRequest</code> and create the
* corresponding <code>HttpServletResponse</code> or dispatch
* to another resource.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a processing exception occurs
*/ public void process(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Wrap multipart requests with a special wrapper
request = processMultipart(request);
// Identify the path component we will use to select a mapping
String path = processPath(request, response);
if (path == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Processing a '" + request.getMethod() +
"' for path '" + path + "'");
}
// Select a Locale for the current user if requested processLocale(request, response);
// Set the content type and no-caching headers if requested
processContent(request, response);
processNoCache(request, response);
// General purpose preprocessing hook
if (!processPreprocess(request, response)) {
return;
}
this.processCachedMessages(request, response);
// Identify the mapping for this request
ActionMapping mapping = processMapping(request, response, path);
if (mapping == null) {
return;
}
// Check for any role required to perform this action
if (!processRoles(request, response, mapping)) {
return;
}
// Process any ActionForm bean related to this request
ActionForm form = processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
// Validate any fields of the ActionForm bean, if applicable
try {
if (!processValidate(request, response, form, mapping)) {
return;
}
} catch (InvalidCancelException e) {
ActionForward forward = processException(request, response, e, form, mapping);
processForwardConfig(request, response, forward);
return;
} catch (IOException e) {
throw e;
} catch (ServletException e) {
throw e;
}
// Process a forward or include specified by this mapping
if (!processForward(request, response, mapping)) {
return;
}
if (!processInclude(request, response, mapping)) {
return;
}
// Create or acquire the Action instance to process this request
Action action = processActionCreate(request, response, mapping);
if (action == null) {
return;
}
// Call the Action instance itself
ActionForward forward =
processActionPerform(request, response,
action, form, mapping);
// Process the returned ActionForward instance
processForwardConfig(request, response, forward);
}

process是RequestProcessor對象主要的邏輯處理函數,根據上面的流程圖可以看到,整個邏輯處理都是在 這個函數中完成,它所調用的函數實現的功能如下:

processMultipart

這個函數的作用是判斷是否是文件上傳請求,如果是則特殊處理。

/** 
* <p>If this is a multipart request, wrap it with a special wrapper.
* Otherwise, return the request unchanged.</p>
*
* @param request The HttpServletRequest we are processing
*/
protected HttpServletRequest processMultipart(HttpServletRequest request) {
if (!"POST".equalsIgnoreCase(request.getMethod())) {
return (request);
}
String contentType = request.getContentType();
if ((contentType != null) &&
contentType.startsWith("multipart/form- data")) {
return (new MultipartRequestWrapper(request));
} else {
return (request);
}
}

processPath

獲取並截取請求,處理後變為需要的字符串,例如請求:http://localhost:8080/struts_login/login.do ,處理後的字符串為/login.do。

/** 
* <p>Identify and return the path component (from the request URI) that
* we will use to select an <code>ActionMapping</code> with which to dispatch.
* If no such path can be identified, create an error response and return
* <code>null</code>.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
*/
protected String processPath(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String path = null;
// For prefix matching, match on the path info (if any)
path = (String) request.getAttribute(INCLUDE_PATH_INFO);
if (path == null) {
path = request.getPathInfo();
}
if ((path != null) && (path.length() > 0)) {
return (path);
}
// For extension matching, strip the module prefix and extension
path = (String) request.getAttribute(INCLUDE_SERVLET_PATH);
if (path == null) {
path = request.getServletPath();
}
String prefix = moduleConfig.getPrefix();
if (!path.startsWith(prefix)) {
String msg = getInternal().getMessage("processPath");

log.error(msg + " " + request.getRequestURI());
response.sendError (HttpServletResponse.SC_BAD_REQUEST, msg);
return null;
}
path = path.substring(prefix.length());
int slash = path.lastIndexOf("/");
int period = path.lastIndexOf(".");
if ((period >= 0) && (period > slash)) {
path = path.substring(0, period);
}
return (path);
}

設置相關函數

processLocale、processContent、processNoCache、processCachedMessages,這四個函數的作用分別是 :設置國際化文件、設置內容類型、設置取消緩存、設置清楚session中struts的錯誤信息。

processMapping

根據上面生成的path,實例化對應的ActionMapping對象,如果此對象不為空則加載到request中,對應名 稱為Globals.MAPPING_KEY,如果為空,發送異常並添加到response中。

// If a mapping is 

found, put it in the request and return it
if (mapping != null) {
request.setAttribute(Globals.MAPPING_KEY, mapping);
return (mapping);
}
// Locate the mapping for unknown paths (if any)
ActionConfig configs[] = moduleConfig.findActionConfigs();
for (int i = 0; i < configs.length; i++) {
if (configs[i].getUnknown()) {
mapping = (ActionMapping) configs[i];
request.setAttribute(Globals.MAPPING_KEY, mapping);
return (mapping);
}
}

processRoles

Action執行是否需要特定的角色權限,如果不需要,則繼續執行。

String roles[] = 

mapping.getRoleNames();
if ((roles == null) || (roles.length < 1)) {
return (true);
}

processActionForm

創建ActionForm並檢測此Action的作用域,如果是Request則添加到request中,如果是Session則添加到 session中。

// Create (if necessary) a form bean to use
ActionForm instance = RequestUtils.createActionForm
(request, mapping, moduleConfig, servlet);
if (instance == null) {
return (null);
}
// Store the new instance in the appropriate scope
if (log.isDebugEnabled()) {
log.debug(" Storing ActionForm bean instance in scope '" +
mapping.getScope() + "' under attribute key '" +
mapping.getAttribute() + "'");
}
if ("request".equals(mapping.getScope())) {
request.setAttribute (mapping.getAttribute(), instance);
} else {
HttpSession session = request.getSession();
session.setAttribute(mapping.getAttribute(), instance);
}

ActionForm相關

processPopulate這個函數的作用是:調用processPopulate()方法,如果存在為ActionMapping配置的 ActionForm,則封裝請求對象中的數據到ActionForm 中,在進行封裝之前,先調用ActionForm 的reset()方 法進行屬性值的默認化

processValidate:如果action元素的屬性validate被設置為true ,則進一步調用validate()方法進行規 則校驗。如果validate()方法校驗失敗,就會保存一個ActionErrors 對象到請求區域中,請求將會自動重定 向到action映射的input屬性所指定的頁面中;如果校驗通過或在action 映射中沒有配置ActionForm,則繼續 處理請求。

異常處理

process這個函數中,包含一個try...catch塊,如果出現InvalidCancelException則執行兩個函數。

processException,將異常寫入日志警告文件,並跑出異常;processForwardConfig,與下面最後執行的 一個函數相同,捕獲結束

跳轉路徑

processForward、processInclude:這個兩個函數的作用是,檢測struts-config下<action>元素的 forward和include屬性的值,如有配置,則把forward和include 請求放在配置的頁面內;processForward() 調用 RequestDispatcher.forward(),而processInclude()調用RequestDispatcher.include()。

如果同時配置了forward 和include 屬性,Struts會優先選擇forward。

processActionCreate

這個函數的作用是從struts-config下<action>的type屬性得到Action類名,創建並返回它的實例。

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);
}
// Create and return a new Action instance
if (log.isTraceEnabled()) {
log.trace(" Creating new Action instance");
}
try {
instance = (Action) RequestUtils.applicationInstance(className);
// :TODO: Maybe we should propagate this exception
// instead of returning null.
} catch (Exception e) {
log.error(
getInternal().getMessage("actionCreate", mapping.getPath()),
e);
response.sendError(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
getInternal().getMessage ("actionCreate", mapping.getPath()));

return (null);
}
instance.setServlet(this.servlet);
actions.put(className, instance);
}
return (instance);

processActionPerform

執行自己寫的Action中execute函數,當然包含跳轉邏輯:

try {
return (action.execute(mapping, form, request, response));
} catch (Exception e) {
return (processException(request, response,
e, form, mapping));
}

processForwardConfig

獲取即將跳轉的路徑:

String forwardPath = forward.getPath();
String uri = null;
// paths not starting with / should be passed through without any processing
// (ie. they're absolute)
if (forwardPath.startsWith("/")) {
uri = RequestUtils.forwardURL(request, forward, null); // get module relative uri
} else {
uri = forwardPath;
}

doForward

獲取RequestDispatcher,並執行跳轉。

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);

總結

如果我們忽略函數,只從宏觀上看,可以總結為:

讀取配置文件

獲取訪問地址

設置Struts

創建、賦值、驗證ActionForm

異常處理

創建Action

執行Action中的邏輯

頁面跳轉

至此,如果不追究到最底層的函數,struts的執行流程已經講解完畢,如果有問題,歡迎大家指出。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved