少儿编程麻麻少儿编程麻麻10-06 18:43

forEach标签

1、forEach标签的简单使用:

(1)未设置步长属性时,默认步长为1:

var="number" begin="0" end="12">
    <>out value="${number}">out>

?(2)设置步长属性后,步长改变:

var="number" begin="0" end="12" step="2">
    <>out value="${number}">out>

?

?

?从0到12输出,需要运用到begin和end属性。

2、遍历ArrayList集合:

(1)forEach遍历集合(ArrayList集合存储字符串):


<%
    ArrayList string=new ArrayList();
    string.add("星期一");
    string.add("星期二");
    string.add("星期三");
    string.add("星期四");
    string.add("星期五");
    string.add("星期六");
    string.add("星期天");
    request.setAttribute("string",string);
%>
"${requestScope.string}" var="str">
    <>out value="${str}">out>

先向ArrayList集合中添加元素,再将ArrayList集合添加到request域,使用forEach指明要遍历的集合来自哪个域,并将每一个元素分别输出(str代表每一个数据)。

?

?(2)遍历存储了学生对象的集合:

建立javabean:

package pers.zhb.domain;

public class Student {
    private String name;
    private int age;
    private String sex;
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

遍历集合中的对象:


<%
   ArrayList students=new ArrayList();
   Student student1=new Student();
   student1.setSex("");
   student1.setAge(12);
   student1.setName("mill");
   students.add(student1);

    Student student2=new Student();
    student2.setSex("");
    student2.setAge(23);
    student2.setName("莉莉");
    students.add(student2);

    request.setAttribute("student",students);
%>
"${requestScope.student}" var="stu">
    <>out value="${stu}">out>

?

3、遍历Map集合:

?(1)键和值都为String类型:


<%
    Map map = new HashMap();
    map.put("河南", "郑州");
    map.put("北京", "北京");
    session.setAttribute("provincialCapital",map);
%>
"${sessionScope.provincialCapital}" var="province">
    <>out value="${province.key}:${province.value}">out>

?

?(2)遍历值为Student对象的Map集合:


<%
    ArrayList students=new ArrayList();
    Student student1=new Student();
    student1.setSex("");
    student1.setAge(12);
    student1.setName("mill");
    students.add(student1);

    Student student2=new Student();
    student2.setSex("");
    student2.setAge(23);
    student2.setName("莉莉");
    students.add(student2);

    Map map = new HashMap();
    map.put("student1", student1);
    map.put("student2", student2);
    session.setAttribute("studentsMap",map);
%>
"${sessionScope.studentsMap}" var="student">
    <>out value="${student.key}: ${student.value.getName()}${student.value.getSex()}${student.value.getAge()}}">out>

?

程序之家二维码

000
评论

为您推荐