⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 building_controller.html

📁 struts api,学习使用struts必备的文档
💻 HTML
📖 第 1 页 / 共 4 页
字号:
                     ActionForm form,
                     HttpServletRequest request,
                     HttpServletResponse response)
throws Exception;
</code>
</pre>

    <p>
    Since the majority of Struts projects are focused on building web 
    applications, most projects will only use the "HttpServletRequest" 
    version.
    A non-HTTP execute() method has been provided for applications that are 
    not specifically geared towards the HTTP protocol.  
    </p>

    <p>
    The goal of an <code>Action</code> class is to process a request, via
    its <code>execute</code> method, and return an <code>ActionForward</code> 
    object that identifies where control should be forwarded (e.g. a JSP, 
    Tile definition, Velocity template, or another Action) to provide the 
    appropriate response.  
    In the <em>MVC/Model 2</em> design pattern, a typical <code>Action</code> 
    class will often implement logic like the following in its 
    <code>execute</code> method:
    </p>
    
    <ul>
    
        <li>
        Validate the current state of the user's session (for example, 
        checking that the user has successfully logged on).
        If the <code>Action</code> class finds that no logon exists, the 
        request can be forwarded to the presentation page that displays the 
        username and password prompts for logging on.  
        This could occur because a user tried to enter an application "in the 
        middle" (say, from a bookmark), or because the session has timed out, 
        and the servlet container created a new one.
        </li>

        <li>
        If validation is not complete, validate the form bean properties as 
        needed. 
        If a problem is found, store the appropriate error message keys as a 
        request attribute, and forward control back to the input form so that 
        the errors can be corrected.
        </li>

        <li>
        Perform the processing required to deal with this request (such as
        saving a row into a database).  
        This <em>can</em> be done by logic code embedded within the 
        <code>Action</code> class itself, <strong>but</strong> should generally be 
        performed by calling an appropriate method of a business logic bean.
        </li>

        <li>
        Update the server-side objects that will be used to create the next
        page of the user interface (typically request scope or session scope
        beans, depending on how long you need to keep these items available).
        </li>

        <li>
        Return an appropriate <code>ActionForward</code> object that 
        identifies the presentation page to be used to generate this response, 
        based on the newly updated beans. 
        Typically, you will acquire a reference to such an object by calling 
        <code>findForward</code> on either the <code>ActionMapping</code> 
        object you received (if you are using a logical name local to this 
        mapping), or on the controller servlet itself (if you are using a 
        logical name global to the application).
        </li>
    
    </ul>

    <p>
    In Struts 1.0, Actions called a <code>perform</code> method instead of 
    the now-preferred <code>execute</code> method. 
    These methods use the same parameters and differ only in which exceptions 
    they throw. 
    The elder <code>perform</code> method throws <code>SerlvetException</code> 
    and <code>IOException</code>. 
    The new <code>execute</code> method simply throws <code>Exception</code>. 
    The change was to facilitate the Declarative Exception handling feature 
    introduced in Struts 1.1.
    </p>
    
    <p>
    The <code>perform</code> method may still be used in Struts 1.1 but is 
    deprecated.
    The Struts 1.1 method simply calls the new <code>execute</code> method 
    and wraps any <code>Exception</code> thrown as a 
    <code>ServletException</code>.
    </p>

   </div>
<h2 id="action_design_guide">4.4.1 Action Class Design Guidelines</h2>
<div class="indent">

    <p>
    Remember the following design guidelines when coding <code>Action</code> 
    classes:
    </p>

    <ul>
    
        <li>
        <strong>Write code for a multi-threaded environment</strong> -
        The controller servlet creates <strong>only one instance of your
        <code>Action</code> class</strong>, and uses this one instance to service
        all requests.  
        Thus, you need to write thread-safe <code>Action</code> classes.
        Follow the same guidelines you would use to write thread-safe 
        Servlets.  
        Here are two general guidelines that will help you write scalable, 
        thread-safe Action classes:
        
        <ul>
        
            <li>
            <strong>Only Use Local Variables</strong> - The most important principle 
            that aids in thread-safe coding is to use only local variables, 
            <strong>not instance variables</strong>, in your <code>Action</code> class.  
            Local variables are created on a stack that is assigned (by your 
            JVM) to each request thread, so there is no need to worry about 
            sharing them.  
            An <code>Action</code> can be factored into several local methods, 
            so  long as all variables needed are passed as method parameters. 
            This assures thread safety, as the JVM handles such variables 
            internally using the call stack which is associated with a single 
            Thread.
            </li>
            
            <li>
            <strong>Conserve Resources</strong> - As a general rule, allocating scarce 
            resources and keeping them across requests from the same user 
            (in the user's session) can cause scalability problems.  
            For example, if your application uses JDBC and you  allocate a 
            separate JDBC connection for every user, you are probably going
            to run in some scalability issues when your site suddenly shows 
            up on Slashdot.  
            You should strive to use pools and release resources (such as 
            database connections) prior to forwarding control to the 
            appropriate View component -- even if a bean method you have 
            called throws an exception.
            </li>
            
        </ul>
    
        </li>

        <li>
        <strong>Don't throw it, catch it!</strong> - Ever used a commercial website only to 
        have a stack trace or exception thrown in your face after you've already 
        typed in your credit card number and clicked the purchase button?  
        Let's just say it doesn't inspire confidence.  
        Now is your chance to deal with these application errors - in the 
        <code>Action</code> class.  
        If your application specific code throws expections you should catch these 
        exceptions  in your Action class, log them in your application's log 
        (<code>servlet.log("Error message", exception)</code>) and return the 
        appropriate ActionForward.
        </li>
    
    </ul>

    <p>
    It is wise to avoid creating lengthy and complex Action classes.
    If you start to embed too much logic in the <code>Action</code> class 
    itself, you will begin to find the <code>Action</code> class hard to 
    understand, maintain, and impossible to reuse.  
    Rather than creating overly complex Action classes, it is generally a 
    good practice to move most of the persistence, and "business logic" to a 
    separate application layer.  
    When an Action class becomes lengthy and procedural, it may be a good time 
    to refactor your application architecture and move some of this logic
    to another conceptual layer; 
    otherwise, you may be left with an inflexible application which can only 
    be accessed in a web-application environment.
    Struts should be viewed as simply the <strong>foundation</strong> for implementing 
    MVC in your applications. 
    Struts provides you with a useful control layer, but it is not a fully 
    featured platform for building MVC applications, soup to nuts.
    </p>

    <p>
    The MailReader example application included with Struts stretches this design
    principle somewhat, because the business logic itself is embedded in the
    <code>Action</code> classes. 
    This should be considered something of a bug in the design of the example,
    rather than an intrinsic feature of the Struts architecture, or an 
    approach to be emulated.
    In order to demonstrate, in simple terms, the different ways Struts can be
    used, the MailReader application does not always follow best practices.
    </p>
      
</div>
<h2 id="exception_handler">4.5 Exception Handler</h2>
<div class="indent">

    <p>
    You can define an ExceptionHandler to execute when an Action's 
    <code>execute</code> method throws an Exception.  
    First, you need to subclass 
    <code>org.apache.struts.action.ExceptionHandler</code> and override the 
    <code>execute</code> method.
    Your <code>execute</code> method should process the Exception and return 
    an ActionForward object to tell Struts where to forward to next.  
    Then you configure your handler in struts-config.xml like this:
    </p>
    
<pre>
<code>&lt;global-exceptions&gt;
    &lt;exception 
      key="some.key" 
      type="java.io.IOException" 
      handler="com.yourcorp.ExceptionHandler"/&gt;
&lt;/global-exceptions&gt;
</code>
</pre>
    
    <p>
    This configuration element says that 
    <code>com.yourcorp.ExceptionHandler.execute</code> will be called when 
    any IOException is thrown by an Action.  
    The <code>key</code> is a key into your message resources properties file 
    that can be used to retrieve an error message.
    </p>
    
    <p>
    You can override global exception handlers by defining a handler inside an 
    action definition.
    </p>
    
    <p>
    A common use of ExceptionHandlers is to configure one for 
    <code>java.lang.Exception</code> so it's called for any exception and log 
    the exception to some data store.
    </p>
    
</div>
<h2 id="plugin_classes">4.6 PlugIn Classes</h2>
<div class="indent">

    <p>
    The <em>PlugIn</em> interface extends Action and so that applications can
    easily hook into the ActionServlet lifecycle. 
    This interface defines two methods, <code>init()</code> and 
    <code>destroy()</code>, which are called at application startup and 
    shutdown, respectively. 
    A common use of a Plugin Action is to configure or load 
    application-specific data as the web application is starting up.
    </p>
    
    <p>
    At runtime, any resource setup by <code>init</code> would be accessed by 
    Actions or business tier classes. 
    The PlugIn interface allows you to setup resources, but does not provide 
    any special way to access them. 
    Most often, the resource would be stored in application context, under
    a known key, where other components can find it.
    </p>
    
    <p>
    PlugIns are configured using &lt;plug-in&gt; elements within the
    Struts configuration file. 
    See <a href="configuration.html#plugin_config"> PlugIn Configuration</a> 
    for details.
    </p>

</div>
<h2 id="actionmapping">4.7 The ActionMapping Implementation</h2>
<div class="indent">

    <p>
    In order to operate successfully, the Struts controller servlet needs
    to know several things about how each request URI should be mapped to an
    appropriate <code>Action</code> class.  
    The required knowledge has been encapsulated in a Java class named 
    <em>ActionMapping</em>, the most important properties are as follows:
    </p>

    <ul>
    
        <li>
        <code>type</code> - Fully qualified Java class name of the Action 
        implementation class used by this mapping.
        </li>

        <li>
        <code>name</code> - The name of the form bean defined in the config file
        that this action will use.
        </li>

        <li>
        <code>path</code> - The request URI path that is matched to select this
        mapping.  
        See below for examples of how matching works and how to use wildcards 
        to match multiple request URIs.
        </li>

        <li>
        <code>unknown</code> - Set to <code>true</code> if this action
        should be configured as the default for this application, to handle
        all requests not handled by another action.  
        Only one action can be defined as a default within a single application.
        </li>

        <li>
        <code>validate</code> - Set to <code>true</code> if the 
        <code>validate</code> method of the action associated with this mapping 
        should be called.
        </li>

        <li>
        <code>forward</code> - The request URI path to which control is passed
        when this mapping is invoked. 
        This is an alternative to declaring a <code>type</code> property. 
        </li>

    </ul>

</div>
<h2 id="config">4.8 Writing Action Mappings</h2>
<div class="indent">

    <p>
    How does the controller servlet learn about the mappings you want?
    It would be possible (but tedious) to write a small Java class that simply
    instantiated new <code>ActionMapping</code> instances, and called all of
    the appropriate setter methods.  
    To make this process easier, Struts uses the Jakarta Commons Digester component
    to parse an XML-based description of the desired mappings and create the 
    appropriate objects initialized to the appropriate default values.
    See the <a href="http://jakarta.apache.org/commons">Jakarta Commons 
    website</a> for more information about the Digester.
    </p>

    <p>
    The developer's responsibility is to create an XML file named
    <code>struts-config.xml</code> and place it in the WEB-INF directory of 
    your application. 
    This format of this document is described by the Document Type Definition
    (DTD) maintained at
    <a href="http://struts.apache.org/dtds/struts-config_1_2.dtd">
    http://struts.apache.org/dtds/struts-config_1_2.dtd</a>.
    This chapter covers the configuration elements that you will typically 
    write as part of developing your application.
    There are several other elements that can be placed in the 
    struts-config file to customize your application. 
    See "<a href="configuration.html">Configuring Applications</a>" for more 
    about the other elements in the Struts configuration file. 
    </p>

    <p>
    The controller uses an internal copy of this document to parse the 
    configuration; an Internet connection is not required for operation.
    </p>

    <p>
    The outermost XML element must be <code>&lt;struts-config&gt;</code>. 
    Inside of the &lt;struts-config&gt; element, there are three important 
    elements that are used to describe your actions:
    </p>
    
    <ul>
    
        <li>
        <code>&lt;form-beans&gt;</code>
        </li>
    
        <li>
        <code>&lt;global-forwards&gt;</code>
        </li>
    
        <li>
        <code>&lt;action-mappings&gt;</code>
        </li>

    </ul>
    
    <p>
    <code>
<strong>&lt;form-beans&gt;</strong>
</code>
<br />
    This section contains your form bean definitions.  
    Form beans are descriptors that are used to create ActionForm instances 
    at runtime. 
    You use a &lt;form-bean&gt; element for each form bean, which has the 
    following important attributes:
    </p>
    
    <ul>
    
        <li>
        <code>name</code>: A unique identifier for this bean, which will be 
        used to reference it in corresponding action mappings. 
        Usually, this is also the name of the request or session attribute 
        under which this form bean will be stored.
        </li>

        <li>
        <code>type</code>: The fully-qualified Java classname of the 
        ActionForm subclass to use with this form bean.
        </li>

    </ul>

    <p>
    <strong>&lt;global-forwards&gt;</strong>
<br />
    This section contains your global forward definitions.  
    Forwards are instances of the ActionForward class returned from an 
    ActionForm's <code>execute</code> method. 
    These map logical names to specific resources (typically JSPs), allowing 
    you to change the resource without changing references to it throughout 
    your application.
    You use a <code>&lt;forward&gt;</code> element for each forward 
    definition, which has the following important attributes:
    </p>
    
    <ul>
    
        <li>
        <code>name</code>: The logical name for this forward.  
        This is used in your ActionForm's <code>execute</code> method to 
        forward to the next appropriate resource. 
        Example: homepage
        </li>

        <li>
        <code>path</code>: The context relative path to the resource.
        Example: /index.jsp or /index.do
        </li>

        <li>
        <code>redirect</code>: <code>True</code> or <code>false</code> 
        (default).  

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -