`

Struts1.3.10深入源代码之核心类Action类

阅读更多
Action类是用户请求和业务处理逻辑之间的桥梁。每个Action类充当客户的一项业务代理。在RequestProcessor类预处理请求时,在创建Action的实例后,就调用自身的  processActionPerform()方法,该方法在调用Action类的execute()方法。
在Struts中所有的Action都继承org.apache.struts.action.Action类。
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;

public class Action {
    /**
     * <p>An instance of <code>TokenProcessor</code> to use for token
     * functionality.</p>
     */
    private static TokenProcessor token = TokenProcessor.getInstance();

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

    /**
     * <p>The servlet to which we are attached.</p>
     */
    protected transient ActionServlet servlet = null;

    // ------------------------------------------------------------- Properties

    /**
     * <p>Return the servlet instance to which we are attached.</p>
     *
     * @return The servlet instance to which we are attached.
     */
    public ActionServlet getServlet() {
        return (this.servlet);
    }

    /**
     * <p>Set the servlet instance to which we are attached (if
     * <code>servlet</code> is non-null), or release any allocated resources
     * (if <code>servlet</code> is null).</p>
     *
     * @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

    /**
     * <p>Process the specified non-HTTP request, and create the corresponding
     * non-HTTP response (or forward to another web component that will create
     * it), with provision for handling exceptions thrown by the business
     * logic. Return an {@link ActionForward} instance describing where and
     * how control should be forwarded, or <code>null</code> if the response
     * has already been completed.</p>
     *
     * <p>The default implementation attempts to forward to the HTTP version
     * of this method.</p>
     *
     * @param mapping  The ActionMapping used to select this instance
     * @param form     The optional ActionForm bean for this request (if any)
     * @param request  The non-HTTP request we are processing
     * @param response The non-HTTP response we are creating
     * @return The forward to which control should be transferred, or
     *         <code>null</code> if the response has been completed.
     * @throws Exception if the application business logic throws an
     *                   exception.
     * @since Struts 1.1
     */
    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;
        }
    }

    /**
     * <p>Process the specified HTTP request, and create the corresponding
     * HTTP response (or forward to another web component that will create
     * it), with provision for handling exceptions thrown by the business
     * logic. Return an {@link ActionForward} instance describing where and
     * how control should be forwarded, or <code>null</code> if the response
     * has already been completed.</p>
     *
     * @param mapping  The ActionMapping used to select this instance
     * @param form     The optional ActionForm bean for this request (if any)
     * @param request  The HTTP request we are processing
     * @param response The HTTP response we are creating
     * @return The forward to which control should be transferred, or
     *         <code>null</code> if the response has been completed.
     * @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

    /**
     * Adds 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. Initialize the attribute if it has not
     * already been. Otherwise, ensure that the request attribute is not set.
     *
     * @param request  The servlet request we are processing
     * @param messages Messages object
     * @since Struts 1.2.1
     */
    protected void addMessages(HttpServletRequest request,
        ActionMessages messages) {
        if (messages == null) {
            //  bad programmer! *slap*
            return;
        }

        // get any existing messages from the request, or make a new one
        ActionMessages requestMessages =
            (ActionMessages) request.getAttribute(Globals.MESSAGE_KEY);

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

        // add incoming messages
        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.
     *
     * @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>
     *
     * @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
     *
     * @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;
    }

    /**
     * <p>Return the user's currently selected Locale.</p>
     *
     * @param request The request we are processing
     * @return The user's currently selected Locale.
     */
    protected Locale getLocale(HttpServletRequest request) {
        return RequestUtils.getUserLocale(request, null);
    }

    /**
     * <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;
    }

    /**
     * <p>Return the default message resources for the current module.</p>
     *
     * @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>
     *
     * @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>
     *
     * <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);
    }

    /**
     * <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>
     *
     * <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
     * @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>
     *
     * <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>
     *
     * @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>
     *
     * @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>
     *
     * @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>
     *
     * @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>
     *
     * @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);
    }
}
分享到:
评论
1 楼 greatwqs 2011-06-12  

相关推荐

    struts1.3.10源代码

    深入研究Struts 1.3.10源代码,可以帮助我们掌握Web应用开发的基本架构,理解MVC模式在实践中的应用,以及学习如何通过配置和编程控制请求流程。同时,通过分析源码,还可以学习到如何处理HTTP请求,验证用户输入,...

    struts 1.3.10.chm api 中文版

    3. **配置文件**:包括`struts-config.xml`,这是Struts框架的主要配置文件,用于配置Action、ActionForm、ActionMapping以及数据源等。通过此文件,开发者可以声明Action类、定义请求路径以及指定视图。 4. **控制...

    struts-1.3.10

    在`src`目录下,可以找到Struts框架的源代码,包括Action类、Form Bean、Tiles、国际化等组件的实现。通过阅读源码,开发者能更深入地了解如何定制和扩展框架,以满足特定需求。 实例部分是学习和掌握Struts框架的...

    Struts 1.3.10+Spring3.0.5+Mybatis3.1.1框架整合全部jar包

    2. **Spring与Struts的集成**:使用Spring的Struts插件,将Action类的实例交给Spring容器管理,通过`&lt;bean&gt;`标签定义Action类并设置scope为prototype,保证每次请求都创建新的Action实例。 3. **Spring与Mybatis的...

    Struts-1.3.10-src.zip

    这里的"Struts-1.3.10-src.zip"是一个包含Struts 1.3.10版本的源代码压缩包,用于开发者深入理解Struts的工作原理和自定义功能。以下将详细介绍Struts 1.3.10中的关键知识点: 1. **MVC设计模式**:MVC是一种软件...

    struts1.3.0

    - **struts-1.3.10-src.zip**:包含了框架的源代码,可供开发者深入研究Struts的工作原理,也可以方便地进行二次开发和定制。 - **struts-1.3.10-lib.zip**:提供了运行Struts1.3.10所需的库文件,包括依赖的JAR包...

    struts-1.3.10文档

    前者定义Action类、Form Bean、数据源以及结果映射,后者则对Struts进行部署描述。 3. **Action类**:每个用户请求都会映射到一个特定的Action类,该类负责处理请求并调用业务逻辑。Action类通常会返回一个Forward...

    struts1框架源代码

    下面我们将深入探讨Struts1的源代码,了解其核心组件和工作原理。 1. **ActionServlet**:这是Struts1的核心控制器,它是Servlet的子类。ActionServlet负责拦截所有的HTTP请求,并根据配置文件(struts-config.xml...

    Struts1.3源代码

    Struts1.3源代码的分析可以帮助我们深入理解其内部工作机制,这对于开发者来说具有重要的学习价值。 在Struts1.3版本中,主要包含以下几个核心组件: 1. **ActionServlet**:这是Struts的核心控制器,负责处理HTTP...

    struts-1.3.8-all&1.3.10

    6. **开发包内容**:"struts-1.3.8"和"struts-1.3.10-lib"这两个文件可能分别代表了Struts框架的源代码和库文件。库文件夹通常包含运行Struts应用所需的各种JAR文件,如Struts核心库、第三方依赖库(如Commons ...

    struts1.3.jar

    2. **Action类**:在Struts 1.3中,Action类是控制器的核心,负责处理用户请求,执行业务逻辑,并将结果转发到相应的视图。每个Action类通常对应一个特定的用户操作。 3. **配置文件**:`struts-config.xml`是...

    web学习笔记.pdf

    - src:包含Struts1.3.10的全部源代码。 要在Java Web项目中使用Struts2,需要将Struts2核心库(如Struts-core-2.x.jar、xwork-2.x.jar、ognl-2.x.jar、freemarker-2.x.jar、commons-logging-1.0.4.jar)放入`WEB-...

    struts1.3源码

    在描述中提到,这个源代码版本的结构与官方提供的有所不同,但更便于导入,这意味着可能是经过优化或者重新组织过的目录结构。 Struts 1.3.x 系列是Struts 1的最后一个主要分支,引入了一些关键的改进和修复,比如...

    struts 1.3.0 all-in-one

    4. 动态Form Beans:开发者可以通过配置文件动态地创建和使用Form Beans,无需预先在源代码中定义。 5. 改进的ActionForward:ActionForward对象现在可以指向相对或绝对URL,使得应用的路由更加灵活。 标签库是...

Global site tag (gtag.js) - Google Analytics