您的位置:首页 > 编程语言 > Java开发

Struts2 使用OGNL表达式投影(过滤)

2016-11-03 17:16 671 查看
一.集合的投影(过滤)有以下三种方式: 

(1).“?#”:投影(过滤)所有符合条件的集合,如:students.{?#this.age >30 };

(2).“^#”:投影(过滤)第一个符合条件的元素,如:students.{^#this.age > 30}; 

(3).“$#”:投影(过滤)最后一个符合条件的元素,如:students.{$#this.age >30 } 。 
注意: .“this”表示集合中的元素; 
二.OGNL具体使用投影(过滤):
 1)创建实体类
public class Student {
private String uname;
private int age;
private boolean gender;
..........
}

2)创建Action类
public class StudentAction extends ActionSupport {

private List<Student> students;

public List<Student> getStudents() {
return students;
}

public void setStudents(List<Student> students) {
this.students = students;
}

@Override
public String execute() throws Exception {

students = new ArrayList<Student>();
students.add(new Student("zhang", 25,false));
students.add(new Student("liu", 35,true));
students.add(new Student("fei", 36,true));
students.add(new Student("kit", 45,false));
students.add(new Student("bear", 18,true));

return SUCCESS;
}
}

3)在struts.xml文件配置action

<action name="oo" class="com.hlx.action.StudentAction">
<result>/ognl.jsp</result>
</action>

4)JSP页面测试
投影查询:获取students中所有uname的列表:<s:property value="students.{uname}"/><p/>

选择查询:获取students中所有age>30的uname列表:<s:property value="students.{?#this.age>30}.{uname}"/><p/>

选择查询:获取students中所有age>30并且gender为true的uname列表:
<s:property value="students.{?#this.age>30 && #this.gender}.{uname}"/><p/>

选择查询:获取students中所有age>30并且gender为true的第一个元素的uname列表:
<s:property value="students.{^(#this.age>30 && #this.gender)}.{uname}"/><p/>

选择查询:获取students中所有age>30并且gender为true的最后一个元素的uname列表:
<s:property value="students.{$(#this.age>30 && #this.gender)}.{uname}"/><p/>



5)运行效果:





三 总结:
    投影:选出集合中每个元素的相同属性组成新的集合

    选择:过滤满足选择条件的集合元素
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: