Strust Components-action Class detailed

Source: Internet
Author: User
Tags getmessage

The action class is a bridge between user requests and business logic, and each action acts as a business agent for the customer. When you requestprocessor a class preprocessing request, after you create an instance of the action, you call its own Processactionperform () method, which invokes execute () of the action class.
The Excute () method of the action invokes the business method of the model, completes the user request, and forwards the request to the other appropriate Web component based on the execution result.

One, action class caching

Struts Application Lifecycle Requestprocessor only one action instance is guaranteed, and all client requests share this instance. All requests can execute its Excute () method at the same time. The Requestprocessor class contains a hashmap as a cache that holds all action instances. The key that each action instance holds in the cache is the action class name. In the Processactioncreate () method of the Requestprocessor class, first check for the presence of an action instance in HashMap, or create a new one if it is used directly. The code that creates the action strength is in the synchronized code block to ensure that only one thread creates the action instance and then puts it in the HashMap. For use by other threads.
Code Code protected action processactioncreate (httpservletrequest request,                                              httpservletresponse response,                                             actionmapping mapping)           throws ioexception {             // Acquire the Action instance we will be  using  (if there is one)          String  Classname = mappIng.gettype ();          if  (log.isdebugenabled ())  {              log.debug (" looking for action instance  for class  " + classname);         &nbsp}             / / :todo: if there were a mapping property indicating whether          // an action were a singleton or  not  ([true]),          // could we just  Instantiate and return a new instance here?             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);             &NBSP}                  // 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);         &NBSP}             return  (instance);         }  

Two Create an action that supports multithreading
1. What is thread-safe code
Code that executes correctly in a multithreaded environment is thread-safe.
The meaning of security is to be able to execute correctly, otherwise the result is program execution error, may appear various unusual situation.

2. How to write thread-safe code
Many books explain how this is a problem, and they mainly explain how to synchronize the thread's use of shared resources. It is mainly about the various usages of the synchronized keyword, as well as the concept of lock.
Tool classes such as read and write locks are also available in the Java1.5. These require a high level of skill and are relatively difficult to debug.

However, thread synchronization is a method that is not possible, is more complex, and can result in a loss of performance. In the equivalent code, there is no need for synchronization to be much better at writing ease and performance.
What I'm emphasizing here is that the code is always thread-safe and does not need to be synchronized. As follows:
1 constants are always thread-safe because only read operations exist.
2 access to the constructor (new operation) is thread-safe because each time a new instance is created, the shared resource is not accessed.
3 The most important thing is that the local variable is thread safe. Because each method is executed, local variables are created in a separate space, which is not a shared resource. A local variable includes a parameter variable for the method.

The servlet is in a multithreaded environment. That is, multiple requests may be sent to a Servelt instance, and each request is a thread. The action under struts is similar, too, and you must write thread-safe action classes in a multithreaded environment.
The principle of thread safety is to use only local variables and use the instance variables carefully (instances of owning state, especially instances with business object state). If you use a stateful instance, the only and best approach is to use local variables in the action class only in the Execute () method of the action class, and for each thread that calls the Execute () method, the JVM creates local variables on the stack of each thread, Therefore, each thread has a separate local variable that is not shared by other threads. When the thread finishes executing the Execute () method, its local variables are destroyed.
If the instance variable of the action class is required, the Java Synchronization mechanism (synchronized) is required to synchronize the code blocks accessing the shared resource

Three, several action of struts
Struts provides some ready-made action classes that can be used to save time, as follows
Forwardaction
can be forwarded to other Web components, providing only one forwarding function without processing.
Includeaction
Contains other Web Components.
Diapatchaction
Usually one action completes only one operation, with this action to complete a set of related operations.
Lookupdispatchaction
He is a subclass of diapatchaction, and can define multiple methods, but it is mainly used in situations where there are multiple buttons in a form, and these buttons have a common name.
Switchaction
For switching between child modules.

Four Actionforward class
The Excute () method of the Action class returns a Actionforward object that represents a logical abstraction of the Web resource, where the Web resource can be a JSP page, a Java servlet, or an action.
There are two ways to return Actionforward from Excute.
1 dynamically create a Actionforward instance
return new Actionforward ("Failure", "login.jsp", true);
2) Findforward method to invoke Actionmappin instance
This approach starts with the action level, and then at the <global-forwards/> level, look for
Return Mapping.findforward ("failure");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.