Saturday, March 1, 2008

Handling multiple checkboxes in Struts 2

Many a time in Web applications we implement a form with a table of records with checkboxes , allowing users to select some rows for performing operations on selected rows. In this post let us look at how it is implemented.

This example is based on Struts 2 framework, with StudentAction as the action class and student.jsp as JSP to display a list of students

The general requirement in these forms is to be able to get the list of selected rows in the "Action" class to perform the required operations and when the control is passed to render the jsp the previously selected rows should be still shown as selected. To achieve this we will add a special field to the StudentAction to hold the list of selected rows (normally identified with some primary key) , as shown in the below code snippet from StudentAction.java


public class StudentAction extends ActionSupport {
List students = new ArrayList();
List selected = new ArrayList();
public List getSelected() {
return selected;
}
public void setSelected(List selected) {

this.selected = selected;
}


.....



The corresponding JSP page to display the list of students with a checkbox will have to name that checkbox as "selected" as shown in below snippet

 















What this code does ? look at the line





if you find everything is straight forward except value="%{name in selected}" , it is a OGNL expression which returns "true" if the value returned by getName() (on the StudentAction instance) is contained in the list returned by getSelected() method, and because this list will be empty for the first time no checkbox will be selected (as the above expression returns false), on clickin Submit button after selecting some checkboxes Struts2 will automagically populates the selected List with the values of selected checkboxes (which happens to be name here), after the performing the business logic when the page is displayed again the above expresion will return true for the previously selected names resulting in those checkbox rendered selected.

Easy ?

4 comments:

Anonymous said...

Thank you! :o)

Jaydeep Virani said...

Thanks a lot...
It was very useful, I was not aware about how to select previously selected check boxes using 'in' keyword.

Harshagvs said...

glad it helped you.

Anonymous said...

Thanks. Your writeup helped me.