问题
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.
回答1:
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?
回答2:
You can use
<s:checkboxlist name="fruit" list="fruits"/>
You don't need to preserve multiple checkbox'es values in the multiple <input>
fields, so there's not necessary many <input>
fields. Struts2 should render it appropriately. Multiple values will come to the action with comma separated values.
In your code you have to add getters and setters for the list
the same way as for fruit
that contains selected values. The params
interseptor will do its job populating your action called with the setter when the form is submitted.
来源:https://stackoverflow.com/questions/14407699/how-to-pass-multiple-checkboxes-to-the-action