本文研究的主要是Struts框架中复选框的相关内容。复选框在web开发中用的非常广泛,具体介绍如下。
如下图,当前为用户选中的水果为"香蕉",点击按钮,跳转到修改界面进行修改。
跳转到修改界面后要回显用户的选择(香蕉),然后由用户再次进行勾选,如图:
前台界面:
后台ChecBoxAction.java代码:
public class ChecBoxAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String fruits;
public String getFruits() {
return fruits;
}
public void setFruits(String fruits) {
this.fruits = fruits;
}
public String test(){
System.out.println(this.getFruits());
//String fruitStr = this.getFruits().trim();
String fruitStr = this.getFruits().replaceAll(" ", "");
System.out.println("去除空格之后的字符串:" + fruitStr);
String[] fruit = fruitStr.split(",");
List myFruits = new ArrayList();
for (int i=0; i list = new ArrayList();
list.add("香蕉");
list.add("雪梨");
list.add("西瓜");
ActionContext.getContext().put("list", list);
return this.SUCCESS;
}
}
注:复选框向后台传值,传过去的是一个字符串,且带有空格,所以必须去除空格,但是用trim()方法是去除不了的,使用trim()方法之后的效果。如下:
如图,毫无效果!但是,我们可以使用replaceAll()方法,去替代空格,效果如下:
另外为了在修改界面展示所有的复选框(水果),我们在Action中模拟从数据库中取出所有的值,然后和用户选择的复选框一起传到修改界面。
修改界面:
注:修改界面比较复杂,首先是遍历所有复选框(水果),在每个浮选中又使用一个forEach循环,去遍历用户选择的所有复选框(水果),然后通过三目运算符去判断当前复选框是否被用户选中,如果匹配,就勾选。
总结以上就是本文关于复选框和Struts2后台交互代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!



