Sunday 23 November 2014

action element


Action element represents an action. An action must have a name attribute. Class is optional. For example you can specify action like below.

<action name="numberCheck">
            <result>/success.jsp</result>
</action>

For the action named ‘numberCheck’ controller displays ‘success.jsp’ as result page.

You can specify the action class in action element.

<action name="numberCheck" class="NumberCheckAction">
            <result name="success">/success.jsp</result>
            <result name="failure">/failure.jsp</result>
</action>

action named ‘numberCheck’  is mapped to action class ‘NumberCheckAction’. Whenever a request comes for the action ‘numberCheck’, execute methods of the action class ‘NumberCheckAction’ is invoked. Depends on the result of execute method corresponding results are displayed on the browser. If execute method returns “success” then success.jsp is displayed to client,. If execute method returns “failure”, then failure.jsp is displayed to client.

It is not always necessary to invoke execute method of action class. You can specify other method to execute instead of execute method.

For example, I updated NumberCheckAction class by adding ‘processReq’ behavior to it.
public class NumberCheckAction {
    private int number;
    private static String SUCCESS = "success";
    private static String FAILURE = "failure";

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String execute(){
        if(getNumber() %2 == 0){
            return SUCCESS;
        }
        else{
            return FAILURE;
        }
    }

    public String processReq(){
        return FAILURE;
    }
}

struts.xml
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="numberCheck" class="NumberCheckAction" method="processReq">
            <result name="success">/success.jsp</result>
            <result name="failure">/failure.jsp</result>
        </action>
    </package>
</struts>


<action name="numberCheck" class="NumberCheckAction" method="processReq">
Above statement specifies, handle the request to action method ‘processReq’ of the class NumberCheckAction.

If class attribute present and method attribute is not present, then execute method of this action class will be called by default.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment