Let’s revisit – Струтс Ацтион Класе

Struts Action Classes

Струтс Ацтион Класе

Увод

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 [код] apache.struts.action.Action [/код] класа.
  • Should override the [код] execute [/код] method of the [код] Action [/код] класа.
  • The Action Servlet selects the Action class for incoming http request defined under the action mapping tag in the [код] struts config.xml [/код] фајл.
  • 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 –

[код]

package com.home.upload.action ;

увоз java.io.IOException ;

увоз java.util.HashMap ;

увоз java.util.Map ;

увоз javax.servlet.ServletException ;

увоз javax.servlet.http.HttpServletRequest ;

увоз javax.servlet.http.HttpServletResponse ;

увоз org.apache.log4j.Logger ;

увоз org.apache.struts.action.Action ;

увоз org.apache.struts.action.ActionForm ;

увоз org.apache.struts.action.ActionForward ;

увоз org.apache.struts.action.ActionMapping ;

увоз org.apache.struts.upload.FormFile ;

увоз com.home.upload.action.forms.UploadForm ;

увоз com.home.upload.service.FileUploadService ;

увоз com.home.upload.service.impl.FileUploadServiceImpl ;

увоз com.home.upload.util.UploadConstants ;

/**

* @author ТецхАлпине

*/

јавност класа FileUploadAction протеже Action {

приватан статички Logger logger = Logger.getLogger(FileUploadAction.класа);

јавност ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,

HttpServletResponse response) throws IOException, ServletException {

ако (форма != нула) {

UploadForm uploadForm = (UploadForm) форма;

FormFile file1 = uploadForm.getFilePath1 ();

FormFile file2 = uploadForm.getFilePath2 ();

FormFile file3 = uploadForm.getFilePath3 ();

Map< Ниска, byte[] > fileMap = нови HashMap< Ниска, byte[] > ();

fileMap.put(file1.getFileName(), file1.getFileData());

fileMap.put(file2.getFileName(), file2.getFileData());

fileMap.put(file3.getFileName(), file3.getFileData());

FileUploadService uploadService = нови FileUploadServiceImpl ();

ако (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 –

[код]

<?xml version = “1.0” encoding = “ISO-8859-1” ?>

<!DOCTYPE struts-config PUBLIC ” -//Apache Software Foundation//DTD Struts Configuration 1.1//EN” “хттп://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 = “метод” >

<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 [/код] метод. 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 classes for multiple flows. A classic example to use the dispatch action class in case of handling the menu operations as under –

[код]

package com.home.upload.action ;

увоз java.io.File ;

увоз java.io.IOException ;

увоз java.util.List ;

увоз javax.servlet.ServletException ;

увоз javax.servlet.http.HttpServletRequest ;

увоз javax.servlet.http.HttpServletResponse ;

увоз org.apache.log4j.Logger ;

увоз org.apache.struts.action.ActionForm ;

увоз org.apache.struts.action.ActionForward ;

увоз org.apache.struts.action.ActionMapping ;

увоз org.apache.struts.actions.DispatchAction ;

увоз com.home.upload.action.forms.MenuForm ;

увоз com.home.upload.service.FileUploadService ;

увоз com.home.upload.service.impl.FileUploadServiceImpl ;

увоз com.home.upload.util.UploadConstants ;

/**

* @author ТецхАлпине

*/

јавност класа MenuAction протеже DispatchAction {

приватан статички Logger logger = Logger.getLogger( MenuAction.класа );

јавност ActionForward upload( ActionMapping mapping, ActionForm form, HttpServletRequest request,

HttpServletResponse response ) throws IOException, ServletException {

return ( mapping.findForward ( UploadConstants.UPLOAD ) );

}

јавност ActionForward listFiles( ActionMapping mapping, ActionForm form, HttpServletRequest request,

HttpServletResponse response ) throws IOException, ServletException {

FileUploadService uploadService = нови FileUploadServiceImpl ();

String stagingLocation = getServlet().getServletContext().getRealPath( “/” ). concat( UploadConstants.UPLOAD_FOLDER );

MenuForm menuForm = (MenuForm) форма;

ако ((нови File( stagingLocation ) ).exists() ) {

List<Ниска> fileNames = uploadService.getFileNames( stagingLocation );

ако (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 = “метод” >

<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 has separate forward paths to which they would redirect the response to.

Закључак

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

 

Таггед на:
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share