Seven experiences of Struts application This article describes some of the experiences and experiences that the author is not easy to use in the Struts. If you are a JSP and Servlet development web application Java programmer, and is also considering using Struts-based build methods, then you will find a lot of information on the same time and valuable information.
1. Extend the Struts framework only when necessary
A good framework has a lot of advantages, first, it must meet the available needs of users. To this ends Struts provides a general architecture for web applications so that developers can concentrate on how to solve the actual business problem. Second, a good framework must also provide an extended interface in an appropriate place so that the application can expand the framework to better adapt to the actual needs of the user.
If Struts framework is in any occasion, it can meet the needs in any project, it's great. But in fact, there is no framework that claims to do this. There must be some specific application requirements to be the developers of the framework that cannot be foreseen. Therefore, the best way is to provide enough expansion interfaces that make developers to adjust Struts to better meet their special requirements.
There are many places available in Struts Framework for expansion and customization. Almost all configuration classes can be replaced with a user-customized version, as long as it is easy to modify the Struts profile.
Other components such as ActionServlet and RequestProcessor can also be replaced with custom versions. Even new features in Struts 1.1 are also designed according to the principles of extensions. For example, the user is allowed to customize the handle of an abnormality in an exception handling mechanism to better respond to an error occurring in an application system.
As a framework, this adjustable feature is also aware of the effect of project development while it is more suitable for your application. First, since your application is based on an existing mature, stable Framework such as Struts, the number of errors discovered during the test will be greatly reduced, and the development time and the reduction of resources can be reduced. Because you no longer need to put development power to write the code of the foundation framework.
However, achieving more features is costly. We must carefully avoid unnecessary abuse of extended performance, Struts is composed of a lot of tool packages by core packages, and they have provided a lot of functions that have been implemented. Therefore, don't blindly extend the Struts framework, you must first determine that you can use other methods to use existing features. Before deciding to write an extended code, you must confirm that Struts does not implement the features you want. Otherwise, repetition features will result in extra effort to clear it in the future.
2. Use an abnormal processing declaration
To define the logical flow of the application, mature experience is recommended in the code, with the configuration method, not written in the program code. In J2EE, such an example is all. From the security and transactional behavior of EJBs to describe the relationship between JMS messages and destination, many rules can be defined outside of the program.
The Struts creator uses this method from the beginning to customize all aspects of the application system run by configuring the configuration file of the Struts. This is continued on the new characteristics of version 1.1, including new exception handling functions. In the previous version of Struts Framework, developers have to handle errors that occur in Struts applications. In the latest versions, the situation is greatly changed, and the Struts Framework provides a built-in class that is called ExceptionHandler, which is used for the system default processing Action class running errors. This is also one of the Frameworks we mentioned in the last trick.
The Struts default ExceptionHandler class generates an ActionError object and saves in the appropriate range (Scope) object. This allows the JSP page to use the error class to remind users what problems. If you think this can't meet your needs, you can easily implement your own ExcePionHandler class. Method and mechanism for specific custom abnormal processing
To customize your own exception handling mechanism, the first step is to inherit the org.apache.struts.Action.exceptionHandler class. This class has 2 methods to overwrite, one is an excute () another is storeException (). In most cases, only the Excute () method is required. Below is an Excute () method of the ExceptionHandler class:
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 that takes the Controller class to the request that must be forwarded after the end of the abnormality processing.
Of course, you can implement any processing, but in general, we must check the throwing exception and perform specific processing for this type of exception. By default, the system's exception handling function is to create an error message while forwarding the request to the place specified in the configuration file. A common example of customized abnormal processing is to process nested exceptions. Assuming that the exception contains nested abnormalities, these nested exceptions include other exceptions, so we must overwrite the original Execute () method to write error information for each exception.
Once you have created your own ExceptionHandler class, you should declare this class in the Struts configuration file so that Struts knows the default exception handler for Struts.
You can configure your own ExceptionHandler class to be used for an action mapping specific part or all Action objects. If it is used for an action mapping specific part, it is configured in an element. If you want this class available for all Action objects, you can specify in the element. For example, suppose we created an exception handler CustomizedExceptionHandler for all Action classes, element definitions as follows:
Many properties can be set in the element. In this article, the most important attribute is not too Handler property, the value of the Handler property is the full name of the subclass of the ExceptionHandler class. If this property is not defined, Struts uses its own default. Of course, other properties are also important, but if you want to override the default exception handling, Handler is undoubtedly the most important properties.
Finally, it must be pointed out that you can have different exception handling classes to handle different exceptions. In the above example, CustomizedExceptionHandler is used to handle any subclasses of any java.lang.exception. In fact, you can also define multiple exception handling classes, each specially handles different exception trees. The following XML fragment explains how to configure this.
Here, once there is an abnormality, Struts framework will try to find ExceptionHandler in the configuration file. If you are not found, Struts will come up with a layer along the unusual parent class chain to find the match. Therefore, we can define a hierarchical exception handling relationship, which has embodied this in the configuration file. 3. A new feature using the application module (Application Modules) Struts 1.1 is the concept of the application module. The application module allows a single Struts application into several modules, each module has its own struts profile, JSP page, Action, and more. This new feature is to solve the largest problem of large and medium-sized development teams, that is, to better support parallel development to allow multiple configuration files instead of a single profile.
Note: In the early Beta version, this feature is called sub-application, and the most recent rename is to more reflect their logically division of labor.
Obviously, when many developers participate in a project together, a single Struts profile can easily cause resource conflicts. The application module allows Struts to be divided in accordance with the functional requirements, and many of the cases have proven to be more close to the actual. For example, suppose we have to develop a typical store app. Components can be divided into modules such as Catalog (Commodity Catalog), Customer (Customer), Customer Service, Order (Order), etc. Each module can be distributed to different directories, such that the resources of each part can be easily positioned, which helps to develop and deploy. Figure 1 shows the directory structure of the application.
Figure 1. Directory structure of a typical store app
Note: If you don't need to divide the project into multiple modules, the Struts framework supports a default application module. This allows applications to be created under version 1.0, which is portable because the application is automatically used as the default application module.
In order to use multiple application module functions, you must do the following preparation steps:
· Create a separate Struts profile for each application module.
• Configure the web deployment descriptor web.xml file.
· Use org.apache.struts.Actions.switch to implement the jump between the program between the module.
Create a standalone struts profile
Each Struts Application Module must have its own profile. Allows you to create your own Action, ActionForm, exception handling, or even more than other modules.
Continue to use the store app as an example, we can create the following configuration file: a file name is struts-config-catalog.xml, including the Catalog (Commodity Directory), Items (Product List), and other inventory-related features Configuration information; another file name is struts-config-order.xml, which contains settings to Order (orders) and Order Tracking. The third profile is Struts-Config.xml, which contains general features belonging to the default application module.
Configure web deployment descriptor
In the earlier versions of Struts, we specify the path to the Struts configuration file in Web.xml. It's good to change, help backward compatibility. But for multiple application modules, we need to add new configuration files to the Web Deployment Descriptor.
For default applications (including early versions of Struts), Struts Framework looks for elements with config files in the web.xml file to load Action Mapping and other application settings. As an example, the following XML fragments show a typical element: Note: If "config" keywords are found in the existing elements, Struts framework will use /Web/Struts-Config.xml by default
In order to support multiple application modules (new features of Struts 1.1), additional elements must be added. Unlike the default element, additional elements correspond to each application module, must be named in the form of config / xxx, where string XXX represents the unique name of the module. For example, in an example of a store application, the element can be defined as follows (note the bold part):
The first element corresponds to the default application module. The second and third elements represent non-default application modules Catalog and Order.
When Struts loads an application, it first loads the configuration file of the default application module. Then look for additional initialization parameters with string CONFIG / XXX. Each additional profile is also parsed and loaded into memory. After this step is completed, the user can use the CONFIG / back string to call the corresponding application module.
Call an Action class between multiple application modules
After you create a separate profile for each application module, we may need to call a different module Action. To this end, you must use the SwitchAction class provided by the Struts framework. Struts automatically adds the name of the application module to the URL, just like the name of the Struts automatically adds the application to the URL. The application module is a new expansion to the framework to help develop in parallel teams. If your team is small, there is no need to use this feature without having to make modularization. Of course, even if there is only one module, the system is still the same.
4. Put the JSP to WEB-INF to protect JSP source code
In order to better protect your JSP to avoid unauthorized access and peep, a good way is to store the page file in the web-inf directory of the web application.
Usually JSP developers will store their page files under the corresponding subdirectory of the web application. A typical list of store applications is shown in Figure 2. The JSP-related JSP-related JSP is saved in the catalog subdirectory. Store in this way with the JSP-related JSP related to the order.
Figure 2. Different function JSP is placed in different directories
The problem with this method is that these page files are easily peeable to see the source code, or is called directly. This may not be a big problem under certain situations, but may constitute a safety hazard in a particular situation. The user can bypass the struts of the Controller directly call JSP and also a problem. To reduce risks, these page files can be moved to the web-inferity. Based on servlet declaration, Web-INF is not part of a public document tree for web applications. Therefore, resources under the web-infers are not directly serving customers. We can still use the JSP page under the web-inf directory to provide views to customers, but customers cannot directly request access JSP.
Using the previous example, Figure 3 shows the directory structure that moves the JSP page to the web-INF directory.
Figure 3. JSP storage is more secure in the web-INF directory
If you move these JSP pages files to the web-inflicity, you must add "web-inf" to the URL when calling the page. For example, write an action mapping for a logoff action in a Struts profile. The JSP path must begin with "web-inf". As shown below: Please pay attention to the bold portion.
This method does not lose a good way to work with Struts under any circumstances. The only skill that you have to pay is that you must link JSP and a Struts Action. Even if the action is just a very basic simple JSP, it is always called an action, and then it calls JSP. Finally, it is not that all containers can support this feature. The early version of WebLogic cannot explain the servlet declaration, so support cannot be provided, which has been improved in the new version. Take your servlet container before using it.
5. Using the Prebuilt Action class to improve development efficiency
Struts Framework has several Prebuilt Action classes that use them to save development time. The most useful is org.apache.struts.Actions.ForwardAction and org.apache.struts.Actions.Dispatchaction.
Use ForwardAction
In the application, it may often appear as long as the Action object is forwarded to a JSP. In the previous point, it has been mentioned that it is always called JSP from Action. If we don't have to perform any business logic in the action, you can follow the access page from the Action, you can use ForwardAction, which allows you to create a number of empty Action classes. The advantage of using ForwardAction is not to create your own Action class, and you need to do just configure an action mapping in the Struts configuration file.
For example, assume you have a JSP file index.jsp, and you can't call this page directly, you must let the program call to call through an Action class, then you can build the following action mapping to achieve this:
As you can see, when the / home is called, the forwardaction will be called and forward the request to the index.jsp page. Discuss the situation that you don't transfer directly to a page via an Action class, you must pay attention to us still use the element. The Forward property in the Forward properties implement the forwarding target. At this time, the element is defined as follows:
The above two methods can save your time and help reduce the number of files needed to apply.
Use Dispatchaction
Dispatchaction is another Action class that Struts contains a large amount of saving time. Unlike other Action classes, only a single execute () method implements a single business, and DispatchAction allows you to write multiple methods related to your business in a single Action class. This reduces the number of Action classes and collects the relevant business methods to make maintenance easier.
To use Dispatchaction's features, you need to create a class yourself and get it by inheriting abstract dispatchaction. There must be a specific method Signature for each business method to provide. For example, we want to provide a method to implement a list of goods to the shopping cart, create a class ShoppingCartDispatchaction provides the following methods:
Then, this class is likely to need a deleteItem () method to remove a list of items from the customer's shopping cart, and the ClearCart () method clears the shopping cart and so on. At this time we can set these methods in a single Action class, without providing an Action class for each method.
When you call a method in the ShopPingCartDispatchaction, just provide the method name as the parameter value in the URL. That is, the URL calling the addItem () method can look similar to:
http: // myhost / storefront / action / cart? method = additem
The Method parameter specifies the method to be called in the ShoppingCartDispatchaction. The name of the parameter can be arbitrarily configured, "Method" used here is just an example. The name of the parameter can be set in the STRUTS configuration file. 6. Using Dynamic ActionForm
In Struts Framework, the ActionForm object is used to package the HTML table data (including request) and return to the data that is returned to the user. They must be complete JavaBean, inherited. The Actionform class in Struts, and the user can selectively override two default methods.
This feature can save a lot of time because it can assist automatic performance layers verification. The only disadvantage of ActionForm is that multiple ActionForm classes must be generated for different HTML tables to save data. For example, if there is a page containing the registration information of the user, another page contains information about the user's introducer, then there are two different Actionform classes. This will cause too much Actionform class in a large application system. Struts 1.1 made a good improvement in this, introduced dynamic Actionform class concept
The dynctionform class and its subclasses in Struts Framework can implement dynamic ActionForm, and dynamically ActionForm allows you to complete all configurations of ActionForm through the configuration file of Struts; no need to create specific Actionform classes in the application. The specific configuration method is: In the Struts configuration file, the TYPE attribute is set to a DynaActionform or a list of a subclass. The following example creates a dynamic Actionform named logonform, which contains two instance variables: username and password.
Dynamic ActionForm can be used for Action classes and JSPs, using methods with ordinary actionform, only one small difference. If you use a normal ActionForm object, you need to provide the GET and SET methods to get and set data. In the example above, we need to provide the getUserName () and setUsername () methods to get and set the username variable, and a pair of methods are used to obtain and set the Password variable.
Here we use DynaActionform, which saves the variables in an MAP class object, so you must use the Get (Name) and Set (Name) method in the DynaActionform class, where the parameter Name is the instance variable name to access. For example, to access the value of the username in DynaActionform, you can use similar code:
String username = (string) form.get ("username");
Since the value is placed in an MAP object, it is necessary to remember to make mandatory type conversion to the Object object returned by the get () method. DynaActionForm has several very useful subclasses. The most important of these is Dynavalidatorform, this dynamic ActionForm and Validator together provide automatic validation with public validator packages. This feature allows you to specify a verification rule outside the program code. Combining two features will be very attractive to developers.
7. Use visualization tools
Since Struts 1.0, there has been a lot of visualization tools to assist in creating, modifying, and maintaining Struts profiles. The configuration file itself is based on XML format, which will increase clumsy in large and medium-sized development applications. In order to more convenient management of these files, once the file is bigger, it is recommended to try to assist in the development of one of the GUI tools. There are many tools for commercial and open source, and Table 1 lists the available tools and their associated links, where you can get more information. Table 1. Struts GUI Tool Application Nature URL Adoreon 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 commercial software http://www.solanasoft.com/ Camino commercial open source software http://www.scioworks.com/scioworks_camino.html Struts Builder http://sourceforge.net/projects/rivernorth / Strutsgui Free http://www.alien-factory.co.uk/struts/struts-index.html