Sunday, January 17, 2010

struts 2 tags demo : select tag

In this post we are going to see examples of how to use the struts 2 select tag in our jsp pages.

NOTE : The examples in this post are just bare bones examples and do not necessarily demonstrate the way that you should design the flow of your code.

To begin with, I would like to list down the prerequisites for these examples that are set up on my system.

Struts version : struts-2.1.8.1

jar files to include in your lib directory :

  • commons-fileupload-1.2.1.jar
  • commons-logging-1.0.4.jar
  • freemarker-2.3.15.jar
  • ognl-2.7.3.jar
  • struts2-core-2.1.8.1.jar
  • xwork-core-2.1.6.jar

Although the code that is written here does not mandate the need of an IDE and can be written using a simple text editor, however, during my experiments, I have been using Netbeans 6.8.

Server : Tomcat 6.0

That takes care of the runtime environment.

Now about our examples.

In the code sample below, i am going to create something of the sort of an ice cream parlor that gives the user an option to select the flavor of his choice by using the struts 2 select tag. The user can submit his choice to an action that prints the user's choice on the server logs using the omnipresent System.out.println().

First, our Flavor class :


public class Flavor {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

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





The Bean that handles the creation of a list of flavors that will be used in the select tag.

package sample;

import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author ryan
 */
public class IceCreamCorner extends ActionSupport{
    
    private List flavors;

    public List getFlavors() {
        return flavors;
    }

    @Override
    public String execute()
    {
        System.out.println("Inside IceCreamBean : Method : Execute.");
        /*
         * Please note that this way of initializing is just for demonstration purposes
         * In real applications, you will fetch this data using a DataAccessObject (DAO).
         * Or if you are using spring/hibernate/EJB, the Flavor class can be an entity.
         * The only objective in this example is to populate a list with Flavor objects.
         */
        Flavor f1=new Flavor();
        Flavor f2=new Flavor();
        Flavor f3=new Flavor();

        flavors=new ArrayList();

        f1.setName("Vanilla");
        f1.setId(1);

        f2.setName("Chocolate");
        f2.setId(2);

        f3.setName("Strawberry");
        f3.setId(3);

        flavors.add(f1);
        flavors.add(f2);
        flavors.add(f3);

        System.out.println("Flavor list size : "+flavors.size());
        return ActionSupport.SUCCESS;
    }
}




Following is the class that the user will submit his flavor choice for further processing.


package sample;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

/**
 *
 * @author ryan
 */
public class FormAnalyzer extends ActionSupport{

    @Override
    public String execute()
    {
        System.out.println("Inside FormAnalyzer : Method : execute");
        ActionContext ac = ActionContext.getContext();

        HttpServletRequest request=(HttpServletRequest)ac.get(ServletActionContext.HTTP_REQUEST);

        Enumeration paramNames= request.getParameterNames();

        while(paramNames.hasMoreElements())
        {
            String param=(String)paramNames.nextElement();
            System.out.println("\nParameter Name : "+param);
            System.out.println("Parameter Values : ");
            
            String[] paramValues=request.getParameterValues(param);
            
            for(String paramVal:paramValues)
            {
                System.out.println(paramVal);
            }
            
        }

        return ActionSupport.ERROR;
    }
}


The struts.xml configuration file.



 

        
            
             
                /success.jsp
            
            
                /failure.jsp
                /success.jsp
            

        



First let me demonstrate using the struts 2 select tag with a dynamically created list



            
            
            
        

In this example, the value that is sent to the FormAnalyzer class is the value of the text that is displayed in the drop down menu.

Before we use the list of flavors of ice creams in the select tag, first the list needs to be initialized. In our example here, we will achieve that by calling an action in the page that will do nothing but populate our list. We will store this action object as a variable on our page and later access this action object to retrieve the list of flavors.

The action object that will be used here is an object of class IceCreamCorner. Thw following line will have to be included before executing any select tag for the examples given in this post.




Now, you can use the given examples and see for yourself the effects of setting the different tag attributes of the struts 2 select tag.

Example 1 : Demonstrating the use of the s:select tag with the listKey and listVaue attributes


            
            
            
        



Example 2 : Demonstrating the use of the s:select tag without the listKey attribute In this case, the String representation of the list object,i.e. toString() value, itself is sent as the paramter value which is not a very useful thing to do. Hence, it makes more sense to use the listValue attribute with the listKey attribute.



            
            
            
        


Example 3 : Demonstrating the use of the s:select tag with a predefined selected value


            
            
            
        



Example 4 : Demonstrating the use of the s:select tag which can have multiple selections



            
            
            
        


I Hope that helps.

Signing Off
Ryan

2 comments:

IMP said...

Very good descriptive tutorial.

Anonymous said...

Thanks for the example, helped me a lot