Search code examples
javajspstruts2freemarker

How to pass multiple checkboxes to the Action


I am using Struts 2 and Freemarker. This is my action class:

package test;

import java.util.ArrayList;
import java.util.List;

public class WelcomeAction {
    
    private String userName;
    private String gender;
    private List<String> fruits;
    private String fruit;


    public String execute() {
//      if(!userName.equals("a"))
//      {
//          return "fail";
//      }
//      else {
//          return "SUCCESS";           
//      }
        return "SUCCESS";
    }   
    
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    
    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getFruitsPicked() {
        return fruit;
    }

    public void setFruitsPicked(String fruitsPicked) {
        this.fruit = fruitsPicked;
    }

    public List<String> getFruits() {
        return fruits;
    }

    public void setFruits(List<String> fruits) {
        this.fruits = fruits;
    }
    
    public WelcomeAction(){
        fruits = new ArrayList<String>();
        fruits.add("apples");
        fruits.add("oranges");
        fruits.add("pears");
        fruits.add("peaches");
    }
}

This is what I have in my .ftl:

<input type="checkbox" list="fruits" name="friut[]" value="apples" /> Apples<br /> 
<input type="checkbox" list="fruits" name="friut[]" value="oranges" /> Oranges<br /> 
<input type="checkbox" list="fruits" name="friut[]" value="pears" /> Pears<br /> 
<input type="checkbox" list="fruits" name="friut[]" value="peaches" /> Peaches<br />

This is how I tried printing:

<#list fruits as item>${item}</#list>

But above command prints all the items in my list that I added in my constructor. Of course, I only want the items that were checked when the form was submitted.


Solution

  • name="friut[]" should be name="fruits". The JavaBean property name is fruits, not fruit (nor friut... note the typo). I don't know about that [] is meaningful for Struts, better said, for OGNL/ValueStack.setValue that the ParametersIntercaptor uses. (It understands fruits[0] though, which is useful to set an element in an existing list.). So at the end Struts has ignored the parameters, so you end up with the original list. Where does list="fruits" come from?