Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Explain various Action classes used in struts framework

In this article we will discuss various action classes used in the Struts Framework and their implementation.

Introduction:

The struts framework is widely used in web applications and well established in the market place.

Apache Struts is an open source framework used to develop JSP or servlet based web application. Struts extend the Java servlet API and are based on the model view controller or MVC design pattern.

Action Class in Struts framework defines the business logic. An action class handles the client request and prepares the response. It also decides where the response should be forwarded. Basically an action class receives data from the presentation layer and forwards the data to the corresponding business layer. It also processes the data which comes from the business layer and forwards them back to the presentation layer. In short, an action class is described as:

  • Action class should extend org.apache.struts.action.Action class.
  • Should override the execute method of the Action class.
  • The Action Servlet selects the Action class for incoming http request defined under the action mapping tag in the struts config.xml file.
  • These classes are used to invoke the classes at the business layer or data access layer to get the data from the bean and store the processed data and return the result or error depending upon the situation.
  • These classes are multi threaded. Hence a developer has to be careful while handling the action variable as they are not thread safe.

Types of action class:

We have following types of action classes in struts:

  • Action - The basic action class in which we implement our business logic.
  • Include Action - Similar as include page directive in jsp.
  • Forward Action - Used in case we need to forward the request from one JSP to another. If we directly forward the request from one jsp it violates the MVC architecture. Hence an action class is used to do this job.
  • Dispatch Action - Handles multiple operations in multiple methods. It is better to have one method per operation instead of merging the entire business logic in a single execute method of an action class.
  • Look up Dispatch Action - Same as dispatch action but recommended not to use.
  • Switch Action - used to switch between different modules in struts application.

Most commonly used action classes are:

  • Action
  • Dispatch Action

Action Class:

This is the base action class in struts. Here the developer needs to override the execute method as under.

Listing 1: Sample displaying base action class

package com.home.upload.action ;

import java.io.IOException ;
import java.util.HashMap ;
import java.util.Map ;

import javax.servlet.ServletException ;
import javax.servlet.http.HttpServletRequest ;
import javax.servlet.http.HttpServletResponse ;

import org.apache.log4j.Logger ;
import org.apache.struts.action.Action ;
import org.apache.struts.action.ActionForm ;
import org.apache.struts.action.ActionForward ;
import org.apache.struts.action.ActionMapping ;
import org.apache.struts.upload.FormFile ;

import com.home.upload.action.forms.UploadForm ;
import com.home.upload.service.FileUploadService ;
import com.home.upload.service.impl.FileUploadServiceImpl ;
import com.home.upload.util.UploadConstants ;

public class FileUploadAction extends Action {
    
    private static Logger logger = Logger.getLogger(FileUploadAction.class);
    
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {
        
        if (form != null) {
            
            UploadForm uploadForm = (UploadForm) form;
            
            FormFile file1 = uploadForm.getFilePath1 ();
            FormFile file2 = uploadForm.getFilePath2 ();
            FormFile file3 = uploadForm.getFilePath3 ();
      
            Map< String, byte[] > fileMap = new HashMap< String, byte[] > ();
            fileMap.put(file1.getFileName(), file1.getFileData());
            fileMap.put(file2.getFileName(), file2.getFileData());
            fileMap.put(file3.getFileName(), file3.getFileData());
            
            FileUploadService uploadService = new FileUploadServiceImpl ();
            
            if (uploadService.doUpload (
                    getServlet().getServletContext().getRealPath("/").concat( UploadConstants.UPLOAD_FOLDER), fileMap )
                    .size() > 0) {
                logger.debug( "Upload is successfull" );
                uploadForm.setUploadFlag(UploadConstants.UPLOAD_SUCCESS);
            } else {
                logger.debug( " Upload failed " );
                uploadForm.setUploadFlag(UploadConstants.UPLOAD_FAILURE);
            }
          }
        return (mapping.findForward(UploadConstants.UPLOAD_SUCCESS));
    }
}

The struts config.xml file for this action class should be as under.

Listing 2: Sample displaying configuration file

<?xml version = "1.0" encoding = "ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC " -//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
	<form-beans>
		<form-bean name = "LoginForm" type = "com.home.upload.action.forms.LoginForm" />
		<form-bean name = "MenuForm" type = "com.home.upload.action.forms.MenuForm" />
		<form-bean name = "UploadForm" type = "com.home.upload.action.forms.UploadForm" />
	</form-beans>
	<global-forwards />
	<action-mappings>
		<action path = "/login" type = "com.home.upload.action.LoginAction" name = "LoginForm" input = "/login.jsp" >
			<forward name = "success" path = "/menu.jsp" />
			<forward name = "failure" path = "/loginFailure.jsp" />
		</action>
		<action path = "/menuAction" type = "com.home.upload.action.MenuAction" name = "MenuForm" input = "/menu.jsp" parameter = "method" >
			<forward name = "upload" path = "/fileUpload.jsp" />
			<forward name = "listFiles" path ="/listUploadedFiles.jsp" />
		</action>
		<action path = "/uploadAction" type = "com.home.upload.action.FileUploadAction" name ="UploadForm" input ="/fileUpload.jsp" >
			<forward name ="uploadSuccess" path ="/uploadSuccess.jsp" />
		</action>
	</action-mappings>
	<message-resources parameter = "ApplicationResources" />
	<plug-in className = "org.apache.struts.validator.ValidatorPlugIn" >
		<set-property property = "pathnames"
			value = "/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
	</plug-in>
</struts-config>
 

As we see in the above example that if the class extends the basic Action class it should override the execute method. Also the struts config file has only one forward path corresponding to the uploadAction.

Dispatch Action:

The dispatch action class also extends the basic action class. This class has an advantage over the action class that it does not has to explicitly override the execute method rather the developers are free to write their own methods. It enables the developers to use the same action class for multiple flows. A classic example of using the dispatch action class is in case of handling the menu operations as under.

Listing 3: Sample displaying dispatch action class

package com.home.upload.action ;

import java.io.File ;
import java.io.IOException ;
import java.util.List ;

import javax.servlet.ServletException ;
import javax.servlet.http.HttpServletRequest ;
import javax.servlet.http.HttpServletResponse ;

import org.apache.log4j.Logger ;
import org.apache.struts.action.ActionForm ;
import org.apache.struts.action.ActionForward ;
import org.apache.struts.action.ActionMapping ;
import org.apache.struts.actions.DispatchAction ;

import com.home.upload.action.forms.MenuForm ;
import com.home.upload.service.FileUploadService ;
import com.home.upload.service.impl.FileUploadServiceImpl ;
import com.home.upload.util.UploadConstants ;

public class MenuAction extends DispatchAction {
    
    private static Logger logger = Logger.getLogger( MenuAction.class );
    
    public ActionForward upload( ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response ) throws IOException, ServletException {
        return ( mapping.findForward ( UploadConstants.UPLOAD ) );
    }
    
    public ActionForward listFiles( ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response ) throws IOException, ServletException {
        FileUploadService uploadService = new FileUploadServiceImpl ();
        String stagingLocation = getServlet().getServletContext().getRealPath( "/" ). concat( UploadConstants.UPLOAD_FOLDER );
        MenuForm menuForm = (MenuForm) form;
        if ((new File( stagingLocation ) ).exists() ) {
            List<String> fileNames = uploadService.getFileNames( stagingLocation );
            if (fileNames.size() > 0 ) {
                menuForm.setFiles( fileNames );
                menuForm.setListFlag ( UploadConstants.TRUE );
            } else {
                menuForm.setListFlag ( UploadConstants.FALSE );
            }
        } else {
            menuForm.setListFlag( UploadConstants.FALSE );
        }
        logger.info( " returning LIST ");
        return (mapping.findForward(UploadConstants.LIST_UPLOADED_FILES));
    }
}

As we see here there are two methods which handle the request from the user. These two methods are defined in the struts config.xml as under.

<action path = "/menuAction" type = "com.home.upload.action.MenuAction" name = "MenuForm" input = "/menu.jsp" parameter = "method" >
			<forward name = "upload" path = "/fileUpload.jsp" />
			<forward name = "listFiles" path = "/listUploadedFiles.jsp" />
</action>

The two methods - upload and listfiles have two separate entries against the action class - MenuAction. Each of these methods have separate forward paths to which they would redirect the response to.

Conclusion:

To conclude the discussion we can keep the following points in mind.

  • Struts is an open source framework used in java based web application.
  • Struts is based on the model view controller - MVC design pattern.
  • Struts has five different action classes of which the most commonly used are:
    • Action
    • DispatchAction
  • The Action class is the base class to which all the action classes should extend to.
  • Classes extending the Action class should override the execute method.
  • Classes extending the dispatch action class have their own action forward methods.
  • Classes extending the dispatch action class can have multiple action forward methods thus becoming useful in case of multiple optional flows.


Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login