Struts extension (plugin, actionservlet, requestprocess)

Source: Internet
Author: User

Introduction:

In many projects, developers implement their own MVC framework, not because they want to do something fundamentally different from struts, but because they are not aware of how to expand struts. Developing Your Own MVC framework can gain full control, but it also requires a lot of resources to implement it (human and material resources). Sometimes this is impossible under a tight schedule.

Struts is not only a powerful framework, but also scalable. You can expand struts in three ways.

1. Plugin: If you want to do some business logic during application startup or shutdown, create your own plugin class.

2. requestprocessor: If you want to make some business logic at a certain time point in the request processing process, create your own requestprocessor class. For example, before each request is executed, you can extend requestprocessor to check whether the user has logged in and whether he has the permission to execute a specific action.

3. actionservlet: If you want to perform some business logic during application startup and shutdown and when the request is processed, you can also expand the actionservlet class. However, you should use actionservlet when plugin and requestprocessor cannot solve your needs.

In this article, we will use a struts application example to demonstrate how to use these three methods to expand struts. The sample code can be downloaded from http://www.onjava.com/onjava/2004/11/10/examples/sample1.zip. Two successful examples of struts extension are struts's validation and tiles framework.

Let's assume that you are familiar with the Struts framework and know how to use it to create a simple application. For more information about struts, see the official homepage.

First: plugin
Plugin is an interface. You can create a class to implement this interface and do something when application startup or shutdown.

For example, I have created a web application that uses hibernate as the persistent layer. I want to initialize hibernate when the application is started, so that when my web application receives the first request, hibernate is already configured and available. At the same time, we want to disable hibernate when the application is closed. We can use a hibernate plugin to implement this requirement. The following two steps are taken:

1. Create a class to implement the plugin interface:

Public class hibernateplugin implements plugin {
Private string configfile;
// This method will be called at application shutdown time
Public void destroy (){
System. Out. println ("entering hibernateplugin. Destroy ()");
// Put hibernate cleanup code here
System. Out. println ("exiting hibernateplugin. Destroy ()");
}
// This method will be called at application startup time
Public void Init (actionservlet, moduleconfig config)
Throws servletexception {
System. Out. println ("entering hibernateplugin. INIT ()");
System. Out. println ("value of init parameter" +
Getconfigfile ());
System. Out. println ("exiting hibernateplugin. INIT ()");
}
Public String getconfigfile (){
Return name;
}
Public void setconfigfile (string ){
Configfile = string;
}
}

The class that implements the plugin interface must complete two methods: Init () and destroy (). The init () method is called when the application is started, and the destroy () method is called when shutdown. Struts also allows you to pass initialization parameters to your plugin class. To pass parameters, you must create a setan setter method for each parameter in the plugin class. In our hibernateplugin class, I will pass the name of configfile as a parameter, rather than hardcoding it into the program.

2. Add the following code to the struts-config.xml to notify struts of a new Plugin:

<Struts-config>
...
<! -- Message Resources -->
<Message-resources parameter = "sample1.resources. applicationresources"/>

<! -- Declare your plugins -->
<Plug-in classname = "com. sample. util. hibernateplugin">
<Set-Property = "configfile" value = "/hibernate. cfg. xml"/>
</Plug-in>
</Struts-config>

The attribute classname is the fully qualified name of the class that implements the plugin interface. For each initialization parameter, you can use the <set-property> element to pass the parameter. In our example, I want to pass the config file name, so I used a <set-property> with the configuration file path.

Struts's tiles and validator frameworks both use plugin to read the configuration file for initialization. The other two plug-ins can help you do the following:

· If your application depends on some configuration files, you can check whether they are available in the plugin class. If they are unavailable, a servletexception will be thrown, which will make the actionservlet unavailable.

· The init () method of the plugin interface is the last opportunity for you to change moduleconfig. moduleconfig is a set of static configuration information to describe the Struts-based module. Struts releases moduleconfig after all plugins are processed.

Second, how the request is processed

Actionservlet is the only servlet in the Struts framework and is responsible for processing all requests. Whenever a request is received, it first tries to find a sub-Application for the current request. Once a sub-application is found, actionservlet creates a requestprocessor object for that sub-application, calls the process () method of this object, and passes in the httpservletrequest and httpservletresponse objects.

Requestprocessor. Process () is where most requests are processed. The process () method uses the template method mode. Many independent methods are used to execute each step of request processing. These methods are called in sequence in the process method. For example, there will be an independent method to find the actionform class corresponding to the current request, and a method to check whether the current user has the required permissions to execute action mapping. These give us great flexibility. A requestprocessor class in the published struts package provides the default implementation for each step of request processing. This means that you can simply rewrite the method you are interested in, and use the default implementation for others. For example, by default, Struts calls request. isuserinrole () to check whether the user has the permission to execute the current actionmapping. If you want to query the database, all you need to do is override the processroles () method, returns true or false if the queried user has the required permissions.

First, we will see how the process () method is implemented by default, and then I will explain in detail every method in the default requestprocessor class, in this way, you can decide which part you want to change.

Public void process (httpservletrequest request, httpservletresponse response)
Throws ioexception, servletexception {
// Wrap multipart requests with a special wrapper
Request = processmultipart (request );
// Identify the path component we will
// Use to select a mapping
String Path = processpath (request, response );
If (Path = NULL ){
Return;
}
If (log. isdebugenabled ()){
Log. debug ("processing a'" + request. getmethod () + "'For path'" + path + "'");
}
// Select a locale for the current user if requested
Processlocale (request, response );
// Set the content type and no-caching Headers
// If requested
Processcontent (request, response );
Processnocache (request, response );
// General purpose preprocessing hook
If (! Processpreprocess (request, response )){
Return;
}
// Identify the mapping for this request
Actionmapping mapping =
Processmapping (request, response, PATH );
If (mapping = NULL ){
Return;
}
// Check for any role required to perform this action
If (! Processroles (request, response, mapping )){
Return;
}
// Process any actionform bean related to this request
Actionform form = processactionform (request, response, Mapping );
Processpopulate (request, response, form, Mapping );
If (! Processvalidate (request, response, form, mapping )){
Return;
}
// Process a forward or include specified by this mapping
If (! Processforward (request, response, mapping )){
Return;
}
If (! Processinclude (request, response, mapping )){
Return;
}
// Create or acquire the action instance
// Process this request
Action action =
Processactioncreate (request, response, Mapping );
If (Action = NULL ){
Return;
}
// Call the action instance itself
Actionforward forward = processactionperform (request, response, action, form, Mapping );
// Process the returned actionforward instance
Processforwardconfig (request, response, forward );
}

1. processmutipart (): In this method, Struts will read the request to check whether the contenttype of the request is multipart/form-data. If yes, the request will be parsed and packaged into httpservletrequest. When you create an HTML form to submit data, the contenttype of the request is application/X-WWW-form-urlencoded by default. However, if your form uses the file-type input control to allow users to upload files, you must change contenttype to multipart/form-data. In this case, you cannot use getparameter () to obtain the data submitted by the user. You must read the request as an inputstream and parse it to obtain the parameter value.

2. processpath (): In this method, Struts will read the URI of the request to determine the path element. This element is used to obtain the actionmappint element.

3. processlocale (): In this method, Struts will obtain locale for the current request. If configured, it can also use this object as Org. apache. struts. action. save the value of the locale attribute. As a side effect of this method, httpsession will be created. If you don't want to create it, you can set the locale attribute to false in controllerconfig, as shown below in the struts-config.xml:

<Controller>
<Set-Property = "locale" value = "false"/>
</Controller>

4. processcontent (): Call response. setcontenttype () to set contenttype for response. This method first tries to get contenttype from the struts-config.xml configuration. Text/html is used by default. To overwrite it, you can do the following:

<Controller>
<Set-Property = "contenttype" value = "text/plain"/>
</Controller>

5. processnocache (): If no-cache is configured, Struts will set the following three headers for each response:

Requested in struts config. xml
Response. setheader ("Pragma", "No-Cache ");
Response. setheader ("cache-control", "No-Cache ");
Response. setdateheader ("expires", 1 );

If you want to set the no-Cache header, add the following information to the struts-config.xml:

<Controller>
<Set-Property = "nocache" value = "true"/>
</Controller>

6. processpreprocess (): This method provides a hook for preprocessing and can be overwritten in the subclass. Its default implementation always returns true if nothing is done. If false is returned, the processing of the current request will be terminated.

7. processmapping (): This method uses the path information to obtain an actionmapping object. That is, the <action> element in the struts-config.xml file:

<Action Path = "/newcontact" type = "com. sample. newcontactaction" name = "newcontactform" Scope = "request">
<Forward name = "sucess" Path = "/sucesspage. Do"/>
<Forward name = "failure" Path = "/failurepage. Do"/>
</Action>

The actionmapping element contains the name of the action class and the actionform used to process the request. It also contains the actionforwards information of the current actionmapping configuration.

8. processroles (): the struts web application provides an authorization solution. That is to say, once a user logs on to the container, the struts processroles () method will check whether a user has a required role to run a given actionmapping by calling request. isuserinrole.

<Action Path = "/adduser" roles = "Administrator"/>

Suppose you have an adduseraction and you only want the Administrator to add a new user. All you need to do is add a role attribute to your adduseraction element. The value of this attribute is administrator. In this way, before running adduseraction, this method ensures that the user has the role of administraotr.

9. processactionform (): Each actionmapping has an actionform class. When struts processes an actionmapping, it will find the corresponding actionform class name from the name attribute of the <action> element.

<Form-bean name = "newcontactform" type = "org. Apache. Struts. Action. dynaactionform">
<Form-property name = "firstname" type = "Java. Lang. String"/>
<Form-property name = "lastname" type = "Java. Lang. String"/>
</Form-bean>

In our example, it will first check whether there is an org. Apache. Struts. Action. dynaactionform class object in the request scope. If it exists, it will use this object. If it does not exist, it will create a new object and set it in the request scope.

10. processpopulate (): In this method, Struts will assemble the instance variables of actionform with the matching request parameters.

11. processvalidate (): struts will call the validate method of your actionform class. If you return actionerrors from validate (), It redirects the user to the page specified by the INPUT attribute of the <action> element.

12. processforward () and processinclude (): In these methods, Struts checks the forward or include attribute of the <action> element, the forward or include requests are placed on the configuration page.

<Action forward = "/login. jsp" Path = "/logininput"/>
<Action include = "/login. jsp" Path = "/logininput"/>

You can guess their differences from the names of these methods: processforward () finally calls requestdispatcher. Forward (), while processinclude () calls requestdispatcher. Include (). If both the forward and include attributes are configured, forward is always called because forward is processed first.

13. processactioncreate (): This method obtains the name of the action class from the type attribute of the <action> element and creates an instance that returns it. In our example, it will create an instance of the COM. sample. newcontactaction class.

14. processactionperform (): This method calls the excute () method of your action class, and your business logic is in the excute method.

15. processforwardconfig (): The excute () method of your action class will return an actionforward object, which will indicate which page is displayed to the user. Therefore, Struts will create a requestdispatcher for that page and call requestdispatcher. Forward ().

The list above illustrates the work and execution sequence of the default requestprocessor in each step of request processing. As you can see, requestprocessor is very flexible, allowing you to configure it by setting the attribute of the <controller> element. For example, if your application is preparing to generate xml content instead of HTML, you can set the attributes of the controller element to notify struts of such situations.

Third: Create your own requestprocessor

Through the above, we learned how the default Implementation of requestprocessor works. Now we will demonstrate an example to illustrate how to customize your own requestprocessor. To demonstrate how to create a custom requestprocessor, we will let our example implement the following two business needs:

· We want to create a contactimageaction class that will generate images instead of common HTML pages.

· Before processing each request, we want to check the username attribute in the session to determine whether the user has logged on. If the property is not found, we will redirect the user to the login page.

We will implement these business needs in two steps.

1. Create Your customrequestprocessor class, which will inherit from the requestprocessor class, as shown below:

Public class customrequestprocessor
Extends requestprocessor {
Protected Boolean processpreprocess (
Httpservletrequest request, httpservletresponse response ){
Httpsession session = request. getsession (false );
// If User is trying to access login page
// Then don't check
If (request. getservletpath (). Equals ("/logininput. Do ")
| Request. getservletpath (). Equals ("/login. Do "))
Return true;
// Check if username attribute is there is session.
// If so, it means user has allready logged in
If (session! = NULL & session. getattribute ("username ")! = NULL)
Return true;
Else {
Try {
// If No redirect user to login page
Request. getrequestdispatcher ("/login. jsp"). Forward (request, response );
} Catch (exception ex ){
}
}
Return false;
}

Protected void processcontent (httpservletrequest request,
Httpservletresponse response ){
// Check if user is requesting contactimageaction
// If yes then set image/GIF as content type
If (request. getservletpath (). Equals ("/contactimage. Do ")){
Response. setcontenttype ("image/GIF ");
Return;
}
Super. processcontent (request, response );
}
}

In the processpreprocess method of the customrequestprocessor class, we check the username attribute of the session. If not found, the user will be redirected to the login page.

To generate an image as an output, we must overwrite the processcontent method. First, check whether the request is a/contactimage path. If yes, we will set contenttype to image/GIF; otherwise, it will be set to text/html.

2. Add the following text after the <action-mappint> element of your struts-config.xml file to tell struts customrequestprocessor to be used as the requestprocessor class:

<Controller>
<Set-Property = "processorclass" value = "com. sample. util. customrequestprocessor"/>
</Controller>

Note that when only a few action classes need to generate non-text/html output, the processcontent () method is OK. If this is not the case, you should create a struts sub-application to process the request to generate the image action, and set contenttype to image/GIF for them.

Struts's tiles framework uses its own requestprocessor to describe struts output.

Fourth: actionservlet

If you view the Web. xml of your struts web application, you will see the following text:

<Web-app>
<Servlet>
<Servlet-Name> action = </servlet-Name>
<Servlet-class> org. Apache. Struts. Action. actionservlet </servlet-class>
<! -- All your init-Params go here -->
</Servlet>
<Servlet-mapping>
<Servlet-Name> action </servlet-Name>
<URL-pattern> *. DO </url-pattern>
</Servlet-mapping>
</Web-app>

This means that actionservlet is responsible for processing all your struts requests. You can create an actionservlet subclass. When an application is started or closed, specific tasks are performed for each request. However, before inheriting the actionservlet class, you should try to create a plugin or requestprocessor to solve your problem. Before servlet1.1, the tiles framework modifies the generated response based on actionservlet. However, since 1.1, it began to use the tilesrequestprocessor class.

Summary

Deciding to develop your own MVC Framework is a big decision. You must consider the time and resources required to develop and maintain the Framework Code. Struts is a very powerful and stable framework. You can modify it to meet most of your business needs.

On the other hand, do not rashly make the decision to expand struts. If you write some low-performance code in requestprocessor, it will execute each request, thus reducing the efficiency of your entire application. In some cases, developing Your Own MVC framework is better than extending struts.

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.