Editor's note: When the author Chuck Cavaness (with a "Programming Jakarta Struts" book) where the network after the company decided to use Struts framework, Chuck has spent several months studying how to use it to build the company's applications. This article is described the use of Struts in the course of a number of hard-earned experience and insights. If you are responsible for development through the jsp and servlet Web applications, Java programmers, and is also considering building Struts-based method, then here you will find many valuable insights as well as information.
1. Only when it is necessary to consider expanding Struts Framework
A good framework has many advantages, first of all, it must be able to meet the foreseeable needs of the users. This Struts application for the Web provides a common framework, so developers can focus on how to solve real business issues. Secondly, a good framework must also be able to provide expanded where appropriate interface for the application to extend the framework to better adapt to the user's actual needs.
If the Struts framework on any occasion, any project can well meet the demand, that is great. But in fact, not a framework that claim to do this. There must be some demand for a particular application framework developers can not be foreseen. Therefore, the best way is to provide sufficient expansion interface allows developers to adjust the struts to better meet their specific requirements.
In the Struts framework, there is a lot for expansion and customization. Almost all of the configuration class can be replaced with a customized version, this simple change it as long as the Struts configuration file can be done.
Other components such as the ActionServlet and RequestProcessor can also use a custom version of the place. Even in Struts 1.1 new features have also extended the principle in accordance with the design. For example, in the exception handling mechanism allows users to customize the exception handling on the handle to the application system to better respond to the error occurred.
Adjustable features such as a framework it is more suitable for your application to a large extent the same time also affected the project development results. First, as your application is based on an existing mature and stable framework such as Struts, discovered during testing will greatly reduce the number of errors, but also can shorten the development time and reduce resource inputs. Because you no longer need to invest in developing the basis of the power used to write framework code.
However, to achieve more functionality is to spend a greater price. We must be careful to avoid unnecessary abuse of scalability, Struts is the core package with a lot of kit form, and they have provided a lot of functionality has been achieved. So do not blindly expanding Struts framework, should determine if other means can use the existing functionality to achieve. Written decision must be confirmed before expanding Struts code does not achieve the function you want. Otherwise, chaos will lead to duplication of functions have to spend extra effort will remove it.
2. Use exception handling statement
To define the logic of the application process, mature experience is recommended in the code, the use of allocation methods to achieve, not coded in the program code. In J2EE, the examples abound. EJB from achieving the security and transaction behavior to describe the JMS message and the destination of the relationship between the number of run-time processes are defined in procedures outside.
Struts Creator from the beginning this approach, by configuring Struts configuration file to customize the application run-time aspects. This is a new feature in version 1.1 on continuity, including the new exception handling features. In the Struts framework previous versions, developers had to deal with their own Struts application error occurred in the situation. In the latest version, the situation had changed greatly, Struts Framework offers a built-called ExceptionHandler class, class action for system default handling errors generated by the operation. This is a technique in the framework we mention one of many scalable interfaces.
Struts default will generate a ActinError ExceptionHandler class object and stored in the appropriate range (scope) object. This allows JSP pages using the wrong class to remind the user any problems. If you think this does not meet your needs, you can easily implement your own ExcepionHandler class.
Specific custom exception handling methods and mechanisms
To customize your own exception handling mechanism, the first step is to inherit org.apache.struts.action.ExceptionHandler class. This class has two ways to cover, one excute () the other is storeException (). In most cases, only covers one of the excute () method. The following is ExceptionHandler class excute () method declaration:
public ActionForward execute (Exception ex,
ExceptionConfig exConfig,
ActionMapping mapping,
ActionForm formInstance,
HttpServletRequest request,
HttpServletResponse response
) Throws ServletException;
As you can see, this method has several parameters, including the original exception. Method returns an ActionForward object for exception handling end of the controller class will be taken to a place where the request must be forwarded.
Of course, you can achieve any treatment, but in general, we must examine the thrown exception, and for the type of exception for a particular treatment. By default, the system of exception handling function is to create an error message, and forwards the request to the configuration file specified place. Custom exception handling is a common example of nested exception handling. Assuming that the exception contains a nested exception, these nested exception but also contains other exceptions, so we have to override the original execute () method, write error messages for each exception.
Once you have created your own ExceptionHandler class, it should be in the Struts configuration file, part of the statement of the class to let Struts know to use your custom exception handling to replace the default exception handling.
You can configure your own class for Action Mapping ExceptionHandler specific part or all of the Action object. If it is used for a specific part of the Action Mapping in the element configuration. If you want this class for all the Action objects can be specified in the element. For example, suppose we create an exception handling class CustomizedExceptionHandler for all of the Action class, the element defined as follows:
handler = "com.cavaness.storefront.CustomizedExceptionHandler"
key = "global.error.message"
path = "/ error.jsp"
scope = "request"
type = "java.lang.Exception" />
The element can be set for many properties. In this article, the most important attribute than handler property, handler attribute is inherited from the definition of a subclass of ExceptionHandler full name. If the attribute is not defined, Struts will use their default values. Of course, other attributes are also important, but if you want to override the default exception handling, then, handler is undoubtedly the most important attribute.
Finally, it should point out is that you can have different exception handling class to handle different exceptions. In the above example, CustomizedExceptionHandler to deal with any subclass of java.lang.Exception. In fact, you can define multiple exception handling classes, each specializing in different exception tree. The following XML fragment to explain how to configure to achieve this.
handler = "com.cavaness.storefront.CustomizedExceptionHandler"
key = "global.error.message"
path = "/ error.jsp"
scope = "request"
type = "java.lang.Exception" />
handler = "com.cavaness.storefront.SecurityExceptionHandler"
key = "security.error.message"
path = "/ login.jsp"
scope = "request"
type = "com.cavaness.storefront.SecurityException" />
Here, if an exception is thrown, struts framework will attempt to find in the configuration file ExceptionHandler, if not found, then the struts will be along the exception of the parent chain until they found a layer up to find matches so far. Therefore, we can define a hierarchical relationship structure exception handling, in the configuration file has reflected this.
3. Use of application modules (Application Modules)
Struts 1.1, a new feature is the application module concept. Struts application module allows a single application is divided into several modules, each module has its own Struts configuration file, JSP page, Action and so on. This new feature is the large and medium sized development team to solve the most complained about a problem that in order to better support parallel development allows multiple configuration files, rather than a single configuration file.
Note: In the early beta versions, this feature is known as sub-applications (sub-applications), recently renamed the purpose is to reflect their more logical division of labor.
Obviously, when many developers together to participate in a project, a single Struts configuration file is easy to cause resource conflicts. Struts application module allows classification according to functional requirements, in many cases has proved so closer to reality. For example, suppose we want to develop a typical store applications. Component can be divided into modules such as catalog (Catalog), customer (customer), customer service (customer service), order (order), etc.. Each module can be distributed to a different directory, so each part is easy to locate resources to help develop and deploy. Figure 1 shows the application's directory structure.
Figure 1. A typical application's directory structure stores
Note: If you do not need to project into multiple modules, Struts framework supports a default application module. This makes the application can also be created under the 1.0 version, portable, because the application automatically as the default application module.
In order to use multi-application module functionality, you must perform the following preparation steps:
鈥?for each application module to create a separate Struts configuration file.
鈥?Web deployment descriptor Web.xml configuration file.
鈥?Use org.apache.struts.actions.SwitchAction to achieve the jump between the program modules.
Create separate Struts configuration file
Each Struts application module must have its own profile. Allowed to create their own independent of other modules, Action, ActionForm, exception handling and more.
Continue to store the application above example, we can create the following configuration files: a file named struts-config-catalog.xml, including catalog (Catalog), items (products list), and other related functions and inventory configuration information; another file called struts-config-order.xml, includes order (order) and order tracking (order tracking) setting. The third configuration file is struts-config.xml, which contains the default application module is a general feature.
Configuring Web deployment descriptor
In earlier versions of Struts, we Web.xml Struts configuration file to specify the path. Fortunately, this did not change, contribute to backward compatibility. But for many application modules, we need to increase the Web deployment descriptor in the new profile settings.
For the default application (including an earlier version of Struts), Struts framework document in Web.xml find the element with the config for load Action mapping applications and other settings. As an example, the following XML fragment shows a typical element:
config> / param-name>
/ WEB-INF/struts-config.xml
Note: If you can not find the elements in the existing "config" keyword, Struts framework will default to using the / WEB / struts-config.xml
In order to support multiple application modules (Struts 1.1 for new features), additional elements must be increased. And the default element is different, additional elements corresponding to each application module, you must config / xxx in the form of naming, in which the string xxx represents the name of the module only. For example, in store application example, the element can be defined as follows (note the bold part):
config
/ WEB-INF/struts-config.xml
config / catalog
/ WEB-INF/struts-config.xml
config / order
/ WEB-INF/struts-config.xml
The first element corresponds to the default application module. The second and third elements represent the non-default application module catalog and order.
When the Struts application is loaded, it first loads the default application module's configuration file. And then look with a string config / xxx form of additional initialization parameters. For each additional parsing configuration files and loaded into memory also. This step is complete, users can use it freely config / string back is to call the name of the corresponding application module.
Between multiple application module class called Action
For each application module to create a separate configuration file, we will likely need to call different modules Action. To do this you must use the Struts framework provides the SwitchAction class. Struts will automatically add the name of the module will be applied to the URL, just like Struts application is automatically added as the name added to the URL. Application module is a framework for a new expansion, contributed to a parallel team development. If your team is small then I need to use this feature, do not be modular. Of course, even if only one module, the system is still the same operation.
4. The WEB-INF JSP into JSP source code after the protection
To better protect your JSP to prevent unauthorized access and peep, a good way to store the page file in the Web application WEB-INF directory.
JSP developer will generally their page file stored in the Web application corresponding subdirectory. A typical store application directory structure shown in Figure 2. With the catalog (Catalog) related to JSP is saved in the catalog subdirectory. Customer associated with the JSP, JSP associated with orders and so on stored in accordance with this method.
Figure 2. JSP based on different functions are placed in different directory
Problem with this approach is the page file is easy to see the source code was stolen, or direct calls. Some situations this may not be a big problem, but in certain cases it may constitute a security risk. Users can direct calls to bypass the JSP Struts the controller is also a problem.
To reduce the risk, you can move the page file to the WEB-INF directory. Servlet-based statement, WEB-INF is not a public document as a Web application as part of the tree. Thus, WEB-INF directory of resources is not a direct service to customers. We can still use the WEB-INF directory of the JSP page to provide views to the customer, the customer can not directly request access to JSP.
Using the previous example, Figure 3 shows the JSP page will be moved to WEB-INF directory of the directory structure after
Figure 3. JSP stored in the WEB-INF directory of more secure
If the JSP page file moved to the WEB-INF directory, when the page is called to be the "WEB-INF" to the URL. For example, in a Struts configuration file for a logoff action to write a Action mapping. JSP path which must be "WEB-INF" at the beginning. As follows:
path = "/ logoff"
type = "org.apache.struts.webapp.example.LogoffAction">
This method Struts under any circumstances be regarded as a good way to practice. Is the only technique to note is that you must be a JSP and Struts action link. Even if the Action is only a very basic simple JSP, always to call a Action, then it calls the JSP.
Finally, a note that not all containers will support this feature. Early versions of WebLogic can not explain Servlet declarations and therefore can not provide support, it was reported in the new version has been improved. In summary, before you check your Servlet container.
5. Prebuilt Action class to use to enhance development efficiency
Struts framework with several prebuilt Action class, using them can greatly save development time. One of the most useful is org.apache.struts.actions.ForwardAction and org.apache.struts.actions.DispatchAction.
Use ForwardAction
In the application, may be often as long as the Action forwards to a JSP object situation. Mentioned in the previous point in Action called by the JSP is always a good habit. Action, if we do not have to perform any business logic, but would like to follow the words from the Action to access the page, you can use ForwardAction, it allows you to remove the Action class to create a number of empty. The advantage of using ForwardAction not create your own Action class, you need to do is in the Struts configuration file to configure a Action mapping.
For example, suppose you have a JSP file index.jsp, and can not directly invoke the page, to let the program through an Action class is called, then you can create the following Action mapping to achieve this:
As you see, when / home is called, will call ForwardAction and to forward the request to the index.jsp page.
Further discuss the adoption of an Action class is not directly forwarded to a page of the case, we must note that we still use elements of the forward attribute to achieve the objectives forward. Then elements are defined as follows:
path = "/ home"
forward = "/ index.jsp">
Of the above methods can save you time and help reduce the number of documents required for an application.
Use DispatchAction
DispatchAction is contained in another Struts can save a lot of development time of Action class. And the other provides only a single Action class execute () method to achieve a single business different, DispatchAction allows you to write more than a single Action class and business-related way. This reduces the number of Action classes, and the related business method together makes maintenance easier.
To use the function DispatchAction need to create a class of their own, through inheritance DispatchAction be abstract. To be provided for each business method must have a specific method signature. For example, we want to provide a method to realize the shopping cart to add the list of goods to create a class ShoppingCartDispatchAction provide the following methods:
public ActionForward addItem (ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception;
So, this class may also need a deleteItem () method from the customer's shopping cart to delete the list of goods, there clearCart () method to clear shopping cart, etc.. Then we can set these methods in a single Action class, no method is provided for each one Action class.
In a method called ShoppingCartDispatchAction inside, just in the URL provided in the method name as a parameter value. That is, call addItem () method of the URL might look like:
http://myhost/storefront/action/cart?method=addItem
Parameter specifies which method to call methods in ShoppingCartDispatchAction. The name parameter can be any configuration, where the use of "method" is just one example. The name parameter can be set on their own Struts configuration file.
6. Using dynamic ActionForm
In the Struts framework in, ActionForm object is used to packing HTML form data (including request), and returns back to dynamic display to the user's data. They must be fully JavaBean, and inheritance. Struts ActionForm class inside the same time, the user can selectively override the default method of the two.
This feature can save a lot of time, because it can help to automatically verify the performance of layers. ActionForm only drawback is that the HTML form must be generated for different number of ActionForm class to save the data. For example, if there is a page that contains the user's registration information, another page will contain the user agent's information, you need two different ActionForm class. This is in large application systems can lead to excessive ActionForm class. Struts 1.1 have made a good improvement, the introduction of the concept of dynamic ActionForm class
DynaActionForm through the Struts framework in the class and its subclasses can implement dynamic ActionForm, dynamic ActionForm allows you to complete the ActionForm Struts configuration file all the configuration; applications no longer need to create specific ActionForm class. Specific configuration is: in the Struts configuration file by adding an element, the type attribute set to DynaActionForm or a sub-class of its full name. The following example creates a dynamic ActionForm named logonForm, it contains two instance variables: username and password.
name = "logonForm"
type = "org.apache.struts.action.DynaActionForm">
Dynamic ActionForm can be used for Action classes and JSP, use the same ActionForm with the ordinary, and only a small difference. If you use ordinary ActionForm objects you need to get and set methods to provide access and set data. In the example above, we need to provide getUsername () and setUsername () method to obtain and set the username variable, and likewise a pair of methods used to obtain and set the password variable.
Here we use the DynaActionForm, it will be the variable stored in a Map class object, so you must use DynaActionForm class get (name) and set (name) method, the parameter name is the name to access the instance variables. For example, in the username to access DynaActionForm value, you can use a similar code:
String username = (String) form.get ("username");
As the value stored in a Map object, so remember the get () method returns the Object Type object to do the mandatory conversion.
DynaActionForm several useful subclasses. One of the most important thing is DynaValidatorForm, this dynamic with the use ActionForm and Validator Validator public to provide automatic verification package. This feature allows you to specify the validation rules outside the code. Combination of the two properties to developers who will be very attractive.
7. Using visual tools
Since Struts 1.0 distribution has appeared in a number of visualization tools to help create, modify and maintain the Struts configuration file. Configuration file itself is XML-based format, in medium and large development applications will be increased to become very awkward. In order to facilitate the management of these files, once the large file you can not clear the time recommendations try to use one tool to assist in the development of a GUI. Commercial and open source tools have many, Table 1 lists the available tools and their related links, from where you can get more information.
Table 1. Struts GUI Tools
The nature of the application site
Adalon Business Software http://www.synthis.com/products/adalon
Easy Struts open source http://easystruts.sourceforge.net/
Struts Console free http://www.jamesholmes.com/struts/console
JForms Business Software http://www.solanasoft.com/
Camino Business Software http://www.scioworks.com/scioworks_camino.html
Struts Builder Open Source http://sourceforge.net/projects/rivernorth/
StrutsGUI free http://www.alien-factory.co.uk/struts/struts-index.html
Related Resources
To obtain a more comprehensive list of Struts GUI tools (including free and commercial), please visit the Struts resource page.
相关链接:
MATROSKA video fileCOMMENT Genealogyconverter mp4 to 3gp free downloadHow to quick cash FLOW statement the two main formsThe Table Border Css Syntax OrderPowerBuilder menu creationThunder counter Sohu said it has infringed the right to reputation or counterclaimYUNJIE: Mr. Chen in the "correction"?E-Mail List Management evaluationhow to convert Flv to 3gpC + + compiler on the template of separate answers to QUESTIONSFlash5 ActionScript Advanced Programming Guide (6)Convert mkv to avi free