Struts - Exemple DispatchAction

Struts - Exemple DispatchAction

La classe Struts DispatchAction est utilisée pour regrouper des fonctionnalités similaires en une seule action et exécuter la fonction dépend de la valeur de paramètre donnée. Voici un exemple pour montrer l'utilisation de DispatchAction.

Téléchargez cet exemple -Struts-DispatchAction-Example.zip

1. Classe DispatchAction

Créez une classe DispatchAction personnalisée en étendant la classe DispatchAction et en déclarant deux méthodes -generateXML() etgenerateExcel().

MyCustomDispatchAction.java

package com.example.common.action;

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

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

public class MyCustomDispatchAction extends DispatchAction{

    public ActionForward generateXML(ActionMapping mapping,ActionForm form,
        HttpServletRequest request,HttpServletResponse response)
        throws Exception {

        request.setAttribute("method", "generateXML is called");

            return mapping.findForward("success");
    }

    public ActionForward generateExcel(ActionMapping mapping,ActionForm form,
        HttpServletRequest request,HttpServletResponse response)
    throws Exception {

        request.setAttribute("method", "generateExcel is called");

        return mapping.findForward("success");
    }
}

2. Configuration de Struts

Déclare un mappage d'action «CustomDispatchAction», avec l'attribut de paramètre et «action» comme valeur. La valeur du paramètre «action» est utilisée pour contrôler la méthode à appeler - generateXML () ou generateExcel ().

struts-config.xml





    

        

            

        

        
        

    

3. Voir page

Dans la page JSP, le paramètre fonctionne comme suit:

1. /CustomDispatchAction.do?action=generateXML exécutera la méthodegenerateXML().
2. /CustomDispatchAction.do?action=generateExcel exécutera la méthodegenerateExcel().

TestForm.jsp

Struts - DispatchAction Example

html:link


   |



a href


           Generate XML File

   |

           Generate Excel File

DispatchExample.jsp

Struts - DispatchAction Example

4. Essaye-le

Struts-DispatchAction-1-example

Si le lien «Generate XML File» est cliqué, il sera redirigé vershttp://localhost:8080/StrutsExample/CustomDispatchAction.do?action=generateXML

Struts-DispatchAction-2-xml-example

Si le lien «Generate Excel File» est cliqué, il sera redirigé vershttp://localhost:8080/StrutsExample/CustomDispatchAction.do?action=generateExcel

Struts-DispatchAction-3-excel-example