struts1源碼研究: org.apache.struts.action.Action

代碼中註釋及翻譯全爲個人見解,若有錯誤之處請指正。
actoin中的方法 大多是針對 Messages,Errors,token的一些操作。

package org.apache.struts.action;

import org.apache.struts.Globals;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.ModuleUtils;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.TokenProcessor;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Locale;

/**
 *  Action必須以線程安全的方式編寫,
 * 因爲controller會爲同時存在的多個request共享一個實例。
 * 所以編寫時要注意:
 *
 * 實例和static變量不能存儲與具體request相關的信息。
 *
 *  存取受保護的JavaBeans, session 變量等資源時,必須使用同步(synchronized)。
 * 
 *
 *  當一個Action實例被第一次創建時,controller會用一個非空參數
 *(標識這個servlet實例和附屬他的Action)調用 setServlet 。
 *   當實例被關閉時,setServlet會被再次調用,用一個null
 *   參數來清空這個Action的信息
 *          
 
*/
public class Action {
    
/**
     * org.apache.struts.util.TokenProcessor類:令牌產生器,用於防止事務重複提交 
     
*/
    
private static TokenProcessor token = TokenProcessor.getInstance();

    
// NOTE: We can make the token  variable protected and remove Action's
    
// token methods or leave it private and allow the token methods to
    
// delegate(委託) their calls.
    
// ----------------------------------------------------- Instance Variables

    
/**
     * Action附屬的servlet。
     
*/
    
protected transient ActionServlet servlet = null;

    
// ------------------------------------------------------------- Properties
    public ActionServlet getServlet() {
        
return (this.servlet);
    }

    
/**
     * 設置Action附屬的servlet,或釋放所有資源(servlet=null)       
     * 
@param servlet The new controller servlet, if any
     
*/
    
public void setServlet(ActionServlet servlet) {
        
this.servlet = servlet;

        
// :FIXME: Is this suppose to release resources?
    }

    
// --------------------------------------------------------- Public Methods

    
/**
     *      非HTTP的execute方法,一般不用。
     * /
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        ServletRequest request, ServletResponse response)
        throws Exception {
        try {
            return execute(mapping, form, (HttpServletRequest) request,
                (HttpServletResponse) response);
        } catch (ClassCastException e) {
            return null;
        }
    }

    /**
     * 處理 HTTP request, 創建相應的(corresponding)
     * HTTP response (或定向到其他創建response 的組件
     * ), 返回 { ActionForward} 實例 來通知control如何跳轉。
     * 或當處理完成時返回null
     * 注:當請求發送到Action時就會自動執行這個execute方法,所以一般簡單的Action就重寫這個方法即可//by wzl.
     * 
@param mapping  The ActionMapping used to select this instance (用來選擇這個實例??)
     * 
@param form     可選的 ActionForm bean 
     * 
@param request  The HTTP request 
     * 
@param response The HTTP response 
     * 
@return forward  通知 control 應該跳轉的頁面, 或null (當業務完成時)
     * 
@throws Exception if the application business logic throws an
     *                   exception
     * 
@since Struts 1.1
     
*/
    
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        
throws Exception {
        
return null;
    }

    
// ---------------------------------------------------- Protected Methods

    
/**
     * 爲request添加 messages 
     * 在JSP用用 < html:messages> 標籤使用 (if messages="true" is set),
     *  參數message 必須被初始化                                                          //org.apache.struts.action.ActionMessages 
     *  Otherwise, ensure that the request attribute is not set.???
     *
     * 
@param request  被添加message的request請求
     * 
@param messages ActionMessages 需要添加的message
     * 
@since Struts 1.2.1
     
*/
    
protected void addMessages(HttpServletRequest request,
        ActionMessages messages) {
        
if (messages == null) {
            
//  bad programmer! *slap*
            return;
        }

        
// 取得request中的requestMessages, 沒有就創建一個
        ActionMessages requestMessages =
            (ActionMessages) request.getAttribute(Globals.MESSAGE_KEY);   
//"org.apache.struts.action.ACTION_MESSAGE";

        
if (requestMessages == null) {
            requestMessages 
= new ActionMessages();
        }

        
// messages加入到requestMessages
        requestMessages.add(messages);

        
// if still empty, just wipe it out from the request
        if (requestMessages.isEmpty()) {
            request.removeAttribute(Globals.MESSAGE_KEY);

            
return;
        }

        
// Save the messages
        request.setAttribute(Globals.MESSAGE_KEY, requestMessages);
    }

    
/**
     * Adds the specified errors keys into the appropriate request attribute
     * for use by the &lt;html:errors&gt; tag, if any messages are required.
     * Initialize the attribute if it has not already been. Otherwise, ensure
     * that the request attribute is not set.
     *  注:基本與addMessages相同,只是這裏的ActionMessages含的是錯誤信息,在頁面用 <html:errors>使用。/by wzl
     * 
@param request The servlet request we are processing
     * 
@param errors  Errors object
     * 
@since Struts 1.2.1
     
*/
    
protected void addErrors(HttpServletRequest request, ActionMessages errors) {
        
if (errors == null) {
            
//  bad programmer! *slap*
            return;
        }

        
// get any existing errors from the request, or make a new one
        ActionMessages requestErrors =
            (ActionMessages) request.getAttribute(Globals.ERROR_KEY);

        
if (requestErrors == null) {
            requestErrors 
= new ActionMessages();
        }

        
// add incoming errors
        requestErrors.add(errors);

        
// if still empty, just wipe it out from the request
        if (requestErrors.isEmpty()) {
            request.removeAttribute(Globals.ERROR_KEY);

            
return;
        }

        
// Save the errors
        request.setAttribute(Globals.ERROR_KEY, requestErrors);
    }

    
/**
     * <p>Generate a new transaction token, to be used for enforcing a single
     * request for a particular transaction.</p>
     * 爲需要處理特殊事務的request生成一個 事務token
     * 
@param request The request we are processing
     * 
@return The new transaction token.
     
*/
    
protected String generateToken(HttpServletRequest request) {
        
return token.generateToken(request);
    }

    
/**
     * Retrieves any existing errors placed in the request by previous
     * actions. This method could be called instead of creating a <code>new
     * ActionMessages()</code> at the beginning of an <code>Action</code>.
     * This will prevent saveErrors() from wiping out any existing Errors
     *
     * 獲得被上一個Action設置的error信息,這個方法可用來
     *初始化一個ActionMessages。可以用來防止saveErrors()清空已存在的Errors。
     *
     * 
@param request The servlet request we are processing
     * 
@return the Errors that already exist in the request, or a new
     *         ActionMessages object if empty.
     * 
@since Struts 1.2.1
     
*/
    
protected ActionMessages getErrors(HttpServletRequest request) {
        ActionMessages errors 
=
            (ActionMessages) request.getAttribute(Globals.ERROR_KEY);

        
if (errors == null) {
            errors 
= new ActionMessages();
        }

        
return errors;
    }

    
/**
     * 返回用戶當前選擇的 Locale。  //java.util.Locale 對象表示了特定的地理、政治和文化地區。
     *
     * 
@param request The request we are processing
     * 
@return The user's currently selected Locale.
     
*/
    
protected Locale getLocale(HttpServletRequest request) {
        
return RequestUtils.getUserLocale(request, null);
    }

    
/**
     * 大體同getError(request)
     * <p> Retrieves any existing messages placed in the request by previous
     * actions. This method could be called instead of creating a <code>new
     * ActionMessages()</code> at the beginning of an <code>Action</code> This
     * will prevent saveMessages() from wiping out any existing Messages </p>
     * 
     * 
@param request The servlet request we are processing
     * 
@return the Messages that already exist in the request, or a new
     *         ActionMessages object if empty.
     * 
@since Struts 1.2.1
     
*/
    
protected ActionMessages getMessages(HttpServletRequest request) {
        ActionMessages messages 
=
            (ActionMessages) request.getAttribute(Globals.MESSAGE_KEY);

        
if (messages == null) {
            messages 
= new ActionMessages();
        }

        
return messages;
    }

    
/**
     * 爲當前模型返回默認的MessageResources         ?? //org.apache.struts.util.MessageResources 
     *
     * 
@param request The servlet request we are processing
     * 
@return The default message resources for the current module.
     * 
@since Struts 1.1
     
*/
    
protected MessageResources getResources(HttpServletRequest request) {
        
return ((MessageResources) request.getAttribute(Globals.MESSAGES_KEY));
    }

    
/**
     * <p>Return the specified message resources for the current module.</p>
     * 根據key爲當前module返回特定的MessageResources
     * 看不懂
     * 
@param request The servlet request we are processing
     * 
@param key     The key specified in the message-resources element for
     *                the requested bundle.
     * 
@return The specified message resource for the current module.
     * 
@since Struts 1.1
     
*/
    
protected MessageResources getResources(HttpServletRequest request,
        String key) {
        
// Identify the current module
        ServletContext context = getServlet().getServletContext();
        ModuleConfig moduleConfig 
=
            ModuleUtils.getInstance().getModuleConfig(request, context);

        
// Return the requested message resources instance
        return (MessageResources) context.getAttribute(key
            
+ moduleConfig.getPrefix());
    }

    
/**
     * <p>Returns <code>true</code> if the current form's cancel button was
     * pressed. This method will check if the <code>Globals.CANCEL_KEY</code>
     * request attribute has been set, which normally occurs if the cancel
     * button generated by <strong>CancelTag</strong> was pressed by the user
     * in the current request. If <code>true</code>, validation performed by
     * an <strong>ActionForm</strong>'s <code>validate()</code> method will
     * have been skipped by the controller servlet.</p>
     *
     * 當form的cancel按鍵?被按下時返回true。該方法會檢查 request的
     *  Globals.CANCEL_KEY屬性。若爲true,ActionForm中的validate()將被跳過。
     *
     * <p> Since Action 1.3.0, the mapping for a cancellable Action must also have
     * the new "cancellable" property set to true. If "cancellable" is not set, and
     * the magic Cancel token is found in the request, the standard Composable
     * Request Processor will throw an InvalidCancelException. </p>
     *
     * 
@param request The servlet request we are processing
     * 
@return <code>true</code> if the cancel button was pressed;
     *         <code>false</code> otherwise.
     
*/
    
protected boolean isCancelled(HttpServletRequest request) {
        
return (request.getAttribute(Globals.CANCEL_KEY) != null);
    }

    
/**
     * 在當前session中存有事務token時 返回true。當存在以下情況時返回false:
     * <ul>
     *
     *  request中無session
     * 
     * session中無事務token
     * <li>No transaction token included as a request parameter</li>
     * request中沒有事務token屬性。
     *
     * 存在是事務token屬性與session中的不匹配。
     * </ul>
     *
     * 
@param request The servlet request we are processing
     * 
@return <code>true</code> if there is a transaction token and it is
     *         valid; <code>false</code> otherwise.
     
*/
    
protected boolean isTokenValid(HttpServletRequest request) {
        
return token.isTokenValid(request, false);
    }

    
/**
     * <p>Return <code>true</code> if there is a transaction token stored in
     * the user's current session, and the value submitted as a request
     * parameter with this action matches it. Returns <code>false</code> under
     * any of the following circumstances:</p>
     * 重寫上一個方法,添加參數 reset 決定是否在確認後重置token
     * <ul>
     *
     * <li>No session associated with this request</li> <li>No transaction
     * token saved in the session</li>
     *
     * <li>No transaction token included as a request parameter</li>
     *
     * <li>The included transaction token value does not match the transaction
     * token in the user's session</li>
     * 
     * </ul>
     *
     * 
@param request The servlet request we are processing
     * 
@param reset   Should we reset the token after checking it?
     * 
@return <code>true</code> if there is a transaction token and it is
     *         valid; <code>false</code> otherwise.
     
*/
    
protected boolean isTokenValid(HttpServletRequest request, boolean reset) {
        
return token.isTokenValid(request, reset);
    }

    
/**
     * <p>Reset the saved transaction token in the user's session. This
     * indicates that transactional token checking will not be needed on the
     * next request that is submitted.</p>
     * 重置token
     * 
@param request The servlet request we are processing
     
*/
    
protected void resetToken(HttpServletRequest request) {
        token.resetToken(request);
    }

    
/**
     * <p>Save the specified error messages keys into the appropriate request
     * attribute for use by the &lt;html:errors&gt; tag, if any messages are
     * required. Otherwise, ensure that the request attribute is not
     * created.</p>
     * 重置並設置Errors。
     * 
@param request The servlet request we are processing
     * 
@param errors  Error messages object
     * 
@since Struts 1.2
     
*/
    
protected void saveErrors(HttpServletRequest request, ActionMessages errors) {
        
// Remove any error messages attribute if none are required
        if ((errors == null|| errors.isEmpty()) {
            request.removeAttribute(Globals.ERROR_KEY);

            
return;
        }

        
// Save the error messages we need
        request.setAttribute(Globals.ERROR_KEY, errors);
    }

    
/**
     * <p>Save the specified messages keys into the appropriate request
     * attribute for use by the &lt;html:messages&gt; tag (if messages="true"
     * is set), if any messages are required. Otherwise, ensure that the
     * request attribute is not created.</p>
     * 重置並設置request中的Messages
     * 
@param request  The servlet request we are processing.
     * 
@param messages The messages to save. <code>null</code> or empty
     *                 messages removes any existing ActionMessages in the
     *                 request.
     * 
@since Struts 1.1
     
*/
    
protected void saveMessages(HttpServletRequest request,
        ActionMessages messages) {
        
// Remove any messages attribute if none are required
        if ((messages == null|| messages.isEmpty()) {
            request.removeAttribute(Globals.MESSAGE_KEY);

            
return;
        }

        
// Save the messages we need
        request.setAttribute(Globals.MESSAGE_KEY, messages);
    }

    
/**
     * <p>Save the specified messages keys into the appropriate session
     * attribute for use by the &lt;html:messages&gt; tag (if messages="true"
     * is set), if any messages are required. Otherwise, ensure that the
     * session attribute is not created.</p>
     *  重置並設置session中的Messages
     * 
@param session  The session to save the messages in.
     * 
@param messages The messages to save. <code>null</code> or empty
     *                 messages removes any existing ActionMessages in the
     *                 session.
     * 
@since Struts 1.2
     
*/
    
protected void saveMessages(HttpSession session, ActionMessages messages) {
        
// Remove any messages attribute if none are required
        if ((messages == null|| messages.isEmpty()) {
            session.removeAttribute(Globals.MESSAGE_KEY);

            
return;
        }

        
// Save the messages we need
        session.setAttribute(Globals.MESSAGE_KEY, messages);
    }

    
/**
     * <p>Save the specified error messages keys into the appropriate session
     * attribute for use by the &lt;html:messages&gt; tag (if
     * messages="false") or &lt;html:errors&gt;, if any error messages are
     * required. Otherwise, ensure that the session attribute is empty.</p>
     * 重置並設置session中的Errors
     * 
@param session The session to save the error messages in.
     * 
@param errors  The error messages to save. <code>null</code> or empty
     *                messages removes any existing error ActionMessages in
     *                the session.
     * 
@since Struts 1.3
     
*/
    
protected void saveErrors(HttpSession session, ActionMessages errors) {
        
// Remove the error attribute if none are required
        if ((errors == null|| errors.isEmpty()) {
            session.removeAttribute(Globals.ERROR_KEY);

            
return;
        }

        
// Save the errors we need
        session.setAttribute(Globals.ERROR_KEY, errors);
    }

    
/**
     * <p>Save a new transaction token in the user's current session, creating
     * a new session if necessary.</p>
     * 
     * 
@param request The servlet request we are processing
     
*/
    
protected void saveToken(HttpServletRequest request) {
        token.saveToken(request);
    }

    
/**
     * <p>Set the user's currently selected <code>Locale</code> into their
     * <code>HttpSession</code>.</p>
     *
     * 
@param request The request we are processing
     * 
@param locale  The user's selected Locale to be set, or null to select
     *                the server's default Locale
     
*/
    
protected void setLocale(HttpServletRequest request, Locale locale) {
        HttpSession session 
= request.getSession();

        
if (locale == null) {
            locale 
= Locale.getDefault();
        }

        session.setAttribute(Globals.LOCALE_KEY, locale);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章