Let’s revisit – Struts Action Classes

Struts Action Classes

Struts Action Classes

Introduction

Apache Struts is an open source framework used to develop JSP or servlet based web application. Struts extend the Java servlet API and 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 those back to the presentation layer. In short, an action class is described as –

  • Action class should extend [code] apache.struts.action.Action [/code] class.
  • Should override the [code] execute [/code] method of the [code] Action [/code] class.
  • The Action Servlet selects the Action class for incoming http request defined under the action mapping tag in the [code] struts config.xml [/code] 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 classes

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 –

[code]

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 ;

/**

* @author TechAlpine

*/

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));

}

}

[/code]

The [code] struts config.xml [/code] file for this action class should be as under –

[code]

<?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>

[/code]

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

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 classes for multiple flows. A classic example to use the dispatch action class in case of handling the menu operations as under –

[code]

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 ;

/**

* @author TechAlpine

*/

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));

}

}

[/code]

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

[code]

<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>

[/code]

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

Conclusion

  • 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.

 

Tagged on:
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share