Seven core practices of Jakarta Struts

Source: Internet
Author: User
Tags map class
Original article http://www.onjava.com/pub/a/onjava/2002/10/30/jakarta.html? Page = 1)
(Prepared by Chuck cavaness, compiled by Qiu Wenyu)

Editor's note: when the network company where the author Chuck cavaness (author of the book programming Jakarta Struts) decided to adopt the Struts framework, chuck spent several months studying how to use it to build a company's application system. This article describes some of the author's hard-earned experiences in using struts. If you are a Java programmer responsible for developing Web applications through JSP and Servlet, and you are also considering using the Struts-based construction method, then you will find a lot of insightful and valuable information here.

1. Expand the Struts framework only when necessary

A good framework has many advantages. First, it must be able to meet users' foreseeable needs. Therefore, Struts provides a general architecture for Web applications, so that developers can focus on how to solve practical business problems. Second, a good framework must be able to provide an extension interface where appropriate, so that applications can expand the framework to better adapt to the actual needs of users.

It would be great if Struts framework can meet the needs of any project on any occasions. But in fact, no framework claims to be able to do this. Some specific application requirements cannot be foreseen by the Framework developers. Therefore, the best way is to provide enough extension interfaces so that developers can adjust struts to better meet their special requirements.

There are many places in Struts Framework for extension and customization. Almost all configuration classes can be replaced with a customized version, which can be done simply by modifying the struts configuration file.

Other components, such as actionservlet and requestprocessor, can also be replaced by custom versions. Even New features in Struts 1.1 are designed according to the extended principle. For example, in the exception handling mechanism, you can customize the handle for exception handling to better respond to errors in the application system.

This adjustable feature, as a framework, is more suitable for your applications and affects the project development performance to a large extent. First, because your application is based on an existing mature and stable framework such as struts, the number of errors found during the test will be greatly reduced, it can also shorten development time and reduce resource investment. Because you no longer need to invest in development to write the code of the basic framework.

However, implementing more functions is costly. We must be careful to avoid unnecessary misuse of extension performance. Struts is composed of core packages and many toolkit, which have provided many implemented functions. Therefore, do not expand the Struts framework blindly. First, determine whether other methods can be used to implement the existing functions. Before deciding to write the extension code, make sure that struts does not implement the functions you need. Otherwise, duplicate features will lead to confusion and will require additional effort to clear it.

2. Exception Handling statement

To define the logical process of an application, mature experience is that we recommend that you use the configuration method outside the code, instead of writing it to the program code. In J2EE, such examples are everywhere. From the implementation of EJB security and transaction behavior to describing the relationship between JMS messages and destinations, many runtime processing flows can be defined outside the program.

The struts creator used this method from the very beginning to customize all aspects of the application system runtime by configuring the struts configuration file. This is a continuation of the new features of Version 1.1, including the new exception handling function. In earlier versions of Struts framework, developers have to handle errors in struts applications by themselves. In the latest version, the situation has greatly improved. Struts framework provides a built-in class called exceptionhandler, which is used by the system to handle errors generated during the running of Action classes by default. This is also one of the many extensible interfaces of the framework we mentioned in the previous tip.

Struts's default exceptionhandler class generates an actionerror object and stores it in a scope object. In this way, JSP pages are allowed to use error classes to remind users of problems. If you think this cannot meet your needs, you can easily implement your own excepionhandler class.

Customize exception handling methods and mechanisms

To customize your own exception handling mechanism, the first step is to inherit the org. Apache. Struts. Action. exceptionhandler class. This class has two methods to override, one is excute () and the other is storeexception (). In most cases, you only need to override the excute () method. The excute () method declaration of the exceptionhandler class is as follows:

As you can see, this method has several parameters, including the original exception. Method returns an actionforward object, which is used to take the Controller class to the place where the request must be forwarded after the Exception Processing is completed.

Of course, you can implement any processing, but in general, we must check the thrown exception and perform specific processing for this type of exception. By default, the system exception handling function is to create an error message and forward the request to the specified place in the configuration file. A common example of custom exception handling is to handle nested exceptions. Assume that this exception contains nested exceptions, which include other exceptions. Therefore, we must overwrite the original execute () method and write error information for each exception.

Once you have created your own exceptionhandler class, you should partially declare this class in the struts configuration file, so that struts knows to replace the default exception handling with your custom exception handling.

You can configure whether your own exceptionhandler class is used for Action mapping specific parts or all action objects. If it is a specific part used for Action mapping, it is configured in the <action> element. If you want this class to be used for all action objects, you can specify it in the <global-sections> element. For example, if we create an exception handling class customizedexceptionhandler for all action classes, the <global-exceptions> element is defined as follows:

You can set many attributes in the <exception/> element. In this article, the most important attribute is the handler attribute. The value of the handler attribute is the full name of the custom subclass that inherits the exceptionhandler class. If this attribute is not defined, Struts uses its own default value. Of course, other attributes are also important, but handler is undoubtedly the most important attribute if you want to overwrite the default exception handling.

It must be pointed out that you can have different exception handling classes to handle different exceptions. In the preceding example, customizedexceptionhandler is used to process any subclass of Java. Lang. exception. In fact, you can also define multiple exception handling classes, each of which specifically processes different exception trees. The following XML snippet explains how to configure to achieve this.

Once an exception is thrown, the Struts framework will try to find the exceptionhandler in the configuration file. If not, then struts will trace the parent category of the exception until matching is found. Therefore, we can define a hierarchical structure of the exception handling relationship, which is already reflected in the configuration file.

3. Use the application module)

A new feature of Struts 1.1 is the concept of an application module. The application module allows a single struts application to be divided into several modules. Each module has its own struts configuration file, JSP page, and action. This new feature is designed to solve one of the most complained problems for large and medium-sized development teams, that is, to better support parallel development, multiple configuration files are allowed instead of a single configuration file.

Note: In earlier beta versions, this feature was called a sub-application. Recently, it was renamed to reflect more of their logical division of labor.

Obviously, when many developers participate in a project, a single struts configuration file can easily cause resource conflicts. The application module allows struts to be divided according to functional requirements. In many cases, this has proved to be closer to reality. For example, suppose we want to develop a typical Store application. The components can be divided into modules, such as catalog, customer, customer service, and order. Each module can be distributed to different directories, so that the resources of each part are easy to locate and facilitate development and deployment. Figure 1 shows the directory structure of the application.

Figure 1. directory structure of a typical Store application
 

Note: If you do not need to divide the project into multiple modules, the Struts Framework supports a default application module. This allows the application to be created in version 1.0 with portability, because the application is automatically used as the default application module.

To use the multi-application module function, you must perform the following preparation steps:

• Create an independent struts configuration file for each application module.

• Configure the Web deployment descriptor web. xml file.

• Use org. Apache. Struts. Actions. switchaction to redirect programs between modules.

Create an independent struts configuration file

Each struts application module must have its own configuration file. You can create your own actions, actionform, exception handling, and more independent from other modules.

As an example, we can create the following configuration file: A file named struts-config-catalog.xml, containing catalog (item Catalog), items (item list), and other configuration information for inventory-related functionality; another file name is Struts-config-order.xml, containing settings for Order (order) and order tracking (order tracking. The third configuration file is a struts-config.xml that contains general functionality in the default application module.

Configure the Web deployment descriptor

In earlier versions of struts, we specified the struts configuration file path in Web. xml. Fortunately, this is not changed, which helps backward compatibility. However, for multiple application modules, we need to add new configuration file settings in the Web deployment descriptor.

For default applications (including earlier versions of struts. search for the config element <init-param> in the XML file to load action ing and other application settings. As an example, the following XML snippet shows a typical <init-param> element:

Note: If the "Config" keyword is not found in the existing <init-param> element, Struts framework uses/web/struts-config.xml by default

To support multiple application modules (New in Struts 1.1), you must add the <init-param> element. Unlike the default <init-param> element, the attached <init-param> element corresponds to each application module and must be named in the form of config/xxx, the string XXX represents the unique name of the module. For example, in the example of a store application, the <init-param> element can be defined as follows (in bold ):

The first <init-param> element corresponds to the default application module. The second and third elements represent the non-default application module catalog and order, respectively.

When struts loads an application, it first loads the configuration file of the default application module. Search for the additional initialization parameters in the form of config/xxx. Each additional configuration file is also parsed and loaded into the memory. After this step is completed, the user can call the corresponding application module with the character string after config/, that is, the name.

Call the action class between multiple application modules

After creating an independent configuration file for each application module, we may need to call actions in different modules. Therefore, the switchaction class provided by the Struts framework must be used. Struts automatically adds the application module name to the URL, just as Struts automatically adds the application name to the URL. The application module is a new extension of the Framework, which facilitates parallel team development. If your team is small, you don't need to use this feature and you don't need to be modularized. Of course, even if there is only one module, the system still operates the same way.

4. Put JSP in the WEB-INF to protect the JSP source code

To better protect your JSP against unauthorized access and peeping, a good way is to store the page file under the WEB-INF directory of the Web application.

Generally, JSP developers store their page files in the corresponding subdirectories of the Web application. The directory structure 2 of a typical Store application is shown in. JSP related to catalog is saved in the catalog subdirectory. JSP related to customer and JSP related to order are stored in this way.

Figure 2. jsp is placed in different directories based on different functions

 

The problem with this method is that these page files are easily peeked at the source code or directly called. In some cases, this may not be a big problem, but it may constitute a security risk in specific circumstances. It is also a problem that users can bypass struts controller to directly call JSP.

To reduce risk, you can move these page files to the WEB-INF directory. Servlet-based declarations do not make WEB-INF part of the Common Document Tree for Web applications. Therefore, the resources under the WEB-INF directory are not serving the customer directly. We can still use the JSP page under the WEB-INF directory to provide the view to the customer, but the customer cannot directly request access to JSP.

Using the previous example, Figure 3 shows the directory structure after moving the JSP page to the WEB-INF directory

Figure 3. More secure JSP stored in the WEB-INF directory

 

If you move these JSP page files to the WEB-INF directory, 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 configuration file. The JSP path must start with "WEB-INF. Note the bold Section as follows.

This method is a good method in struts practice under any circumstances. The only trick to note is that you must associate JSP with a struts action. Even if this action is just a very basic JSP, it always calls an action and then calls JSP.

It should be noted that not all containers support this feature. WebLogic earlier versions do not support servlet declarations, so it is reported that they have been improved in the new version. Check your servlet container before using it.

5. Use the prebuilt action class to improve development efficiency

Struts framework has several prebuilt action classes, which can greatly save development time. Among them, org. Apache. Struts. Actions. forwardaction and org. Apache. Struts. Actions. dispatchaction.

Use forwardaction

In an application, the action object is often forwarded to a JSP. As mentioned above, it is a good habit to always call JSP by action. If you do not need to execute any business logic in the action, but want to access the page from the action, you can use forwardaction, which allows you to create many empty action classes. The advantage of using forwardaction is that you do not have to create your own action class. You only need to configure an action mapping in the struts configuration file.

For example, suppose you have a JSP file index. JSP, and the page cannot be called directly. The program must be called through an action class. Then, you can create the following action ing to achieve this:

As you can see, when/home is called, it will call forwardaction and forward the request to the index. jsp page.

We will discuss the situation that a page is not directly forwarded through an action class. We must note that we still use the forward attribute in the <action> element to achieve the forwarding goal. The <action> element is defined as follows:

Both of the above methods can save your time and help reduce the number of files required by an application.

Use dispatchaction

Dispatchaction is another action class in Struts that can save a lot of development time. Unlike other action classes that only provide a single execute () method to implement a single business, dispatchaction allows you to write multiple business-related methods in a single action class. In this way, the number of action classes can be reduced, and related business methods can be combined to make maintenance easier.

To use the dispatchaction function, you must create a class by inheriting the abstract dispatchaction. Each business method to be provided must have a specific method signature. For example, we want to provide a method to add a commodity list to the shopping cart, and create a class shoppingcartdispatchaction to provide the following methods:

Therefore, this class may also require a deleteitem () method to delete the item list from the customer's shopping cart, and the clearcart () method to clear the shopping cart. In this case, we can set these methods in a single action class without providing an action class for each method.

When calling a method in shoppingcartdispatchaction, you only need to provide the method name as the parameter value in the URL. That is to say, the URL that calls additem () may look like:

Http: // myhost/storefront/Action/cart? Method = additem

The method parameter specifies the method to be called in shoppingcartdispatchaction. The parameter name can be configured at will. The "method" here is just an example. You can set the parameter name in the struts configuration file.

6. Use Dynamic actionform

In Struts framework, the actionform object is used to wrap HTML table data (including requests) and return the data dynamically displayed to the user. They must be full an and inherit the actionform class in. Struts. At the same time, you can selectively override two default methods.

This feature saves a lot of time because it can assist in automatic performance Layer verification. The only drawback of actionform is that multiple actionform classes must be generated for different HTML tables to save data. For example, if one page contains User Registration Information and the other page contains information about the user's introducer, two different actionform classes are required. This leads to an excessive number of actionform classes in large application systems. Struts 1.1 has improved this and introduced the concept of dynamic actionform.

You can use the dynaactionform class in Struts framework and its subclass to implement dynamic actionform. The dynamic actionform allows you to complete all the configurations of actionform through the struts configuration file; there is no need to create a specific actionform class in the application. The specific configuration method is: Add a <form-bean> element in the struts configuration file to set the type attribute to the full name of dynaactionform or a subclass of dynaactionform. 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 JSP. It is used in the same way as ordinary actionform, with only one small difference. If you use a common actionform object, you must provide the get and set methods to obtain and set data. In the preceding example, we need to provide the GetUserName () and setusername () methods to obtain and set the username variable. Likewise, there is a method for getting and setting the password variable.

Here we use dynaactionform, which saves the variables in a map Class Object. Therefore, we must use the get (name) and set (name) methods in the dynaactionform class, the parameter name is the name of the instance variable to be accessed. For example, to access the username value in dynaactionform, you can use similar code:

String username = (string) form. Get ("username ");

Because the values are stored in a map object, remember to perform mandatory type conversion on the object objects returned by the get () method.

Dynaactionform has several useful subclasses. The most important among them is dynavalidatorform. This dynamic actionform and validator use the public validator package to provide automatic verification. This feature allows you to specify verification rules outside the program code. Combining the two features will be very attractive to developers.

7. Use visualization tools

Since the struts 1.0 distribution, many visualization tools have emerged to help create, modify, and maintain struts configuration files. The configuration file itself is based on the XML format and becomes clumsy in large and medium-sized development applications. To facilitate the management of these files, we recommend that you use a GUI tool to assist development once the files are large enough to be clearly visible. There are many commercial and open-source tools. Table 1 lists available tools and their related links, from which you can get more information.

Table 1. Struts GUI tool
Application website
Adalong commercial software http://www.synthis.com/products/adalon
Easy struts open source http://easystruts.sourceforge.net/
Struts console http://www.jamesholmes.com/struts/console free
Jforms commercial software http://www.solanasoft.com/
Camino commercial software http://www.scioworks.com/scioworks_camino.html
Struts builder open source http://sourceforge.net/projects/rivernorth/
Strutsgufree http://www.alien-factory.co.uk/struts/struts-index.html

Related Resources

For a more comprehensive list of struts GUI tools (including free and commercial tools), visit the struts resource page.

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.