Struts LookupDispatchAction

LookupDispatchAction provides a mechanism for grouping a set of related functions into a single action, thus eliminating the need to create seperate actions for each functions.

A convenient way to select a dispatch method is by linking it with a button. This can be problematic in a localized application, since the label of the button may change according to the user’s locale. For one user, the button may read delete; for another, it may read aufteilen.

The LookupDispatchAction (org.apache.struts.actions.LookupDispatch-Action) solves this problem by mapping the labels back to their original message key. The key can then be mapped to the appropriate dispatch method. Since the message key may not be an appropriate name for a Java method, the developer provides a hash table that maps the message keys to the dispatch method names:

protected Map getKeyMethodMap(){
      Map map =  new HashMap();
      map.put("label.add", "add");
      map.put("label.subtract", "subtract");
      map.put("label.multiply", "multiply");
      map.put("label.divide", "divide");
      return map;
}

In a JSP, the buttons could be created like this:

<html:form action="LookupDispatchAction">
    <html:submit property="method">
        <bean:message key="label.add" />
    </html:submit>
</html:form>

The labels for the buttons may vary by user locale, but the same method will be selected regardless.

Difference between the DispatchAction and DispatchLookup- Action is that the latter does a reverse lookup to match the localized value submitted for the button back to the message key. The message key is then mapped to the name of the dispatch method.

First create a new Dynamic Web Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
    </dependency>
  
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts-core</artifactId>
      <version>1.3.10</version>
    </dependency>
  
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts-taglib</artifactId>
      <version>1.3.10</version>
    </dependency>
  
</dependencies>

1. Action Form

Create a Action Form class and name it CalculatorForm.java that contains the following code.

package com.kruders.form;
 
import org.apache.struts.action.ActionForm;
 
public class CalculatorForm extends ActionForm{
    private static final long serialVersionUID = 1L;
    private Integer numberA;
    private Integer numberB;
    public Integer getNumberA() {
        return numberA;
    }
    public void setNumberA(Integer numberA) {
        this.numberA = numberA;
    }
    public Integer getNumberB() {
        return numberB;
    }
    public void setNumberB(Integer numberB) {
        this.numberB = numberB;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }
}

2. Action Class (Controller)

Let us create an Action class that will handle the request.

CalculatorAction.java

package com.kruders.action;
 
 
import java.util.HashMap;
import java.util.Map;
 
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.LookupDispatchAction;
 
import com.kruders.form.CalculatorForm;
 
public class CalculatorAction extends LookupDispatchAction{
    protected Map getKeyMethodMap(){
          Map map =  new HashMap();
          map.put("label.add", "add");
          map.put("label.subtract", "subtract");
          map.put("label.multiply", "multiply");
          map.put("label.divide", "divide");
          return map;
    }
     
    public ActionForward add(ActionMapping mapping,ActionForm form,
            HttpServletRequest request,HttpServletResponse response) 
    throws Exception {
        CalculatorForm calculatorForm = (CalculatorForm) form;
 
        Integer numberA = Integer.parseInt(request.getParameter("numberA").toString());
        Integer numberB = Integer.parseInt(request.getParameter("numberB").toString());
        Integer result = calculatorForm.getNumberA() + calculatorForm.getNumberB();
        request.getSession().setAttribute("result", result.toString());
        return mapping.findForward("success");
    }
     
    public ActionForward subtract(ActionMapping mapping,ActionForm form,
            HttpServletRequest request,HttpServletResponse response) 
    throws Exception {
 
        Integer numberA = Integer.parseInt(request.getParameter("numberA").toString());
        Integer numberB = Integer.parseInt(request.getParameter("numberB").toString());
        Integer result = numberA - numberB;
        request.getSession().setAttribute("result", result.toString());
        return mapping.findForward("success");
    }
     
    public ActionForward multiply(ActionMapping mapping,ActionForm form,
            HttpServletRequest request,HttpServletResponse response) 
    throws Exception {
 
        Integer numberA = Integer.parseInt(request.getParameter("numberA").toString());
        Integer numberB = Integer.parseInt(request.getParameter("numberB").toString());
        Integer result = numberA * numberB;
        request.getSession().setAttribute("result", result.toString());
        return mapping.findForward("success");
    }
     
    public ActionForward divide(ActionMapping mapping,ActionForm form,
            HttpServletRequest request,HttpServletResponse response) 
    throws Exception {
 
        Integer numberA = Integer.parseInt(request.getParameter("numberA").toString());
        Integer numberB = Integer.parseInt(request.getParameter("numberB").toString());
        Integer result = numberA / numberB;
        request.getSession().setAttribute("result", result.toString());
        return mapping.findForward("success");
    }
}

The CalculatorAction class must provide an implementation of getKeyMethodMap() method. This method maps the methods in the action class to keys in the Struts resource bundle file.

3. Action Handler

The next step is to create an action mapping for this action handler. The request parameter name is specified using the parameter attribute. Here the request parameter name is method.


In struts-config.xml write the following code

<action path="/LookupDispatchAction" parameter="method" name="CalculatorForm" type="com.kruders.action.CalculatorAction">
    <forward name="success" path="/calculator.jsp" />
</action>

4. Create JSP

Now create calculator.jsp and write the following code.

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<html>
<head>
<title>LookupDispatchAction Page</title>
</head>
<body>
<html:form action="LookupDispatchAction">
    Number A <html:text name="CalculatorForm" property="numberA" /><br>
    Number B <html:text name="CalculatorForm" property="numberB" /><br>
    <html:submit property="method">
        <bean:message key="label.add" />
    </html:submit>  
    <html:submit property="method">
        <bean:message key="label.subtract" />
    </html:submit>  
    <html:submit property="method">
        <bean:message key="label.multiply" />
    </html:submit>  
    <html:submit property="method">
        <bean:message key="label.divide" />
    </html:submit>
</html:form>
<% String result = (String)session.getAttribute("result");   
   if(result!=null) out.println("<br>Result : " + result);%>   
</body>
</html>

5. Struts Config

struts-config.xml file contains the following code.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
 
<struts-config>
 
    <form-beans>
        <form-bean name="CalculatorForm" type="com.kruders.form.CalculatorForm" />
    </form-beans>
     
    <global-forwards>
        <forward name="calculator" path="/calculator.do"/>
    </global-forwards>
     
    <action-mappings>
     
        <action
            path="/calculator"
            type="org.apache.struts.actions.ForwardAction"
            parameter="/calculator.jsp"/>
         
        <action path="/LookupDispatchAction" parameter="method" name="CalculatorForm" type="com.kruders.action.CalculatorAction">
            <forward name="success" path="/calculator.jsp" />
        </action>
         
    </action-mappings>
 
    <message-resources parameter="ApplicationResource"/>
     
</struts-config>

6. Properties File

Create ApplicationResources.properties write the following text.

label.add = add
label.subtract = subtract
label.multiply = multiply
label.divide = divide

7. Run Project

Now when you run the project, following screen will be displayed as in Figure 10.1

Figure 10.1 Figure 10.1


Now enter numberA and numberB and click on Add button, following screen will be displayed as in Figure 10.2

Figure 10.2 Figure 10.2

The folder structure of the example is shown below in Figure 10.3

Figure 10.3 Figure 10.3

You can download the source code of this example here.

No comments yet.

Leave a Reply