Wednesday, July 7, 2010

Struts2 Control Tag if elseif else Example


Struts2 If/ else if / else Tag Example


Aim:

            The Control Tags are used for flow control such as if/else if / else.

if, elseif and else tags only one tag evaluates at a time. Evaluation is based upon the conditions being processed. Evaluated conditions must be of Boolean type. This is illustrated in the following Jsp page.

If the condition in tag evaluates to 'true' then only this tag is evaluated and others are discarded.
If the condition in tag evaluates to 'false' and tag evaluates to 'true' then the body of the tag is processed.
If the condition in tag  and tags evaluates to 'false' then only the  tag is processed.

Procedure:

            Step 1:

                        Create Project name as ControlPro

            Step 2:

                        Create Action class ControlAction.java

                        Include following coding into ControlAction.java

                       
package example;
import com.opensymphony.xwork2.ActionSupport;
public class ControlAction extends ActionSupport
{
    private String name;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public ControlAction()
    {
    }

    public String execute() throws Exception
    {
        return "success";
    }

}

Step 3:

            Create jsp files

home.jsp

< %@taglib uri="/struts-tags" prefix="s" % >
< html >
< head >
< meta content="keyword" name="Struts2 if example" >
< title > Home jsp < /title >
< /head >
< body >
< s:form action="controlAction" >
< s:textfield name="name" label="Enter Name"/ >
< s:submit value="OK"/ >
< /s:form >
< /body >
< /html >


success.jsp

< %@taglib uri="/struts-tags" prefix="s" % >
< html >
< head >
< meta content="keyword" name="Struts2 if example" >
< title > Home jsp < /title >
< /head >
< body >

< s:if test="name=='suresh'" >
< div > If Statement < /div >
< /s:if >
< s:elseif test="name=='kumar'" >
< div > ElseIf Statement < /div >
< /s:elseif >
< s:else >
< div > Else Statement < /div >
< /s:else >

< /body >
< /html >


Step 4:

Made some changes in 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="example" namespace="/example" extends="struts-default" >

< action name="controlAction" class="example.ControlAction" >
< result name="INPUT" > /example/home.jsp < /result >
< result name="success" > /example/success.jsp < /result >
< /action >

< /package >
< /struts >


Step 5:

Run home.jsp

How it works

You enter suresh

If Statement will display

You enter kumar

Else If statement will display

You enter anything except suresh and kumar.

Else statement will display

Directory Structure of the project

No comments:

Post a Comment