Saturday 28 January 2012

SIMPLER EXAMPLE FOR DISPATCHACTION

DISPATCHACTION WITH SIMPLE DEMO


If you want to explain the purpose of DispatchAction to a beginner,
I think we should use a very simple example.

For this purpose I have thought of an calcbean having 4 methods
( add, subtract,multiply and divide).

So, I developed dispatch app with simple
arithmetic operations (addidtion, subtraction,
multiplication and division)This application
has five files ,

1. demoInput.jsp
2. demoAction.java
3. demoForm.java
4. calcbean.java
5. demoOutput.jsp

===============================================


demoAction.java

package demopack;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.struts.action.*;

import org.apache.struts.actions.DispatchAction;

public class demoAction extends DispatchAction
{
public ActionForward add(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
demoForm demoform=(demoForm)form;

String a=demoform.getA();
String b=demoform.getB();


if(a.length()!=0)
{
calcbean bean1=new calcbean();
String r =bean1.add(a,b);

String r1 = "sum is ......"+r;



request.setAttribute("result",r1);
}


return(mapping.findForward("success"));
}
…//provided code for subtract , multiply and divide as above
}



calcbean.java

package demopack;

import java.util.*;
import java.sql.*;

public class calcbean
{

public String add(String n1,String n2)
{

int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
int c=a+b;

return ""+c;
}

//--------------


…//provided code for subtract , multiply and divide as above


//======================
}
since the calcapp has various functions. One important thing
is action mapping.When we make use of DispatchAction we have to
define the 'parameter' property of tag. For this calcapp
I have provided action mapping as shown below.












========================================================================
We can altogether avoid using DispatchAction, however, even if we have many methods! How?
The simple solution is to add 'operation' also as a parameter to the method in the helperbean.
For examople, we can write our calcbean to have a single method
like calculate(String s1, String s2, String operation)
This will make things very easy.


I have implemented this task in next essay.