EL表达式的使用

来源:互联网 发布:传统软件强调系统性 编辑:程序博客网 时间:2024/06/15 02:16

简介

EL表达式替代jsp表达式。因为开发jsp页面的时候遵守原则:在jsp页面中尽量少些甚至不写java代码。

EL表达式作用:向浏览器输出域对象中的变量或表达式计算的结果

基本语法: ${变量或表达式}    代替<%=变量或表达式%>


EL获取不同类型的数据


普通的对象 
 <%--demo1 普通对象 --%> <% String str = "普通字符串"; pageContext.setAttribute("key", str); Student s = new Student("01","小明");//参数为id 和 name pageContext.setAttribute("s1", s); %> <p> ${key} </p> <p> ${s1.id} --- ${s1.name} </p>//其实走的是getId()和getName()方法


数组或List集合

<%--demo2 数组或List集合 --%><%int arr[] = new int [3];arr[0] = 1; arr[1] = 2; arr[2] = 3;pageContext.setAttribute("array", arr);ArrayList <Integer> al = new ArrayList<Integer>();al.add(1);al.add(2);al.add(3);pageContext.setAttribute("list", al);%><p>${array[0] } ${array[1]} ${array[2]}</p><p>${list[0]} ${list[1]} ${list[2]}</p>

Map集合

<%--demo3 Map集合 --%><% Map<String,Student> m = new HashMap<>(); m.put("m1", new Student("001","小明"));m.put("m2", new Student("002","中明"));m.put("m3", new Student("003","大明"));pageContext.setAttribute("map", m);%><p>${map['m1'].id }--${map['m1'].name }</p><p>${map['m2'].id }--${map['m2'].name }</p><p>${map['m3'].id }--${map['m3'].name }</p>



EL执行的表达式:

算术表达式

比较表达式

逻辑表达式

判空表达式

<%String empty = "";pageContext.setAttribute("emptys",empty);%><p> ${empty emptys}</p> //其实是判断 empty == null || empty.equals("");

说明:

  el表达式一般不直接用==  != > < >= <=之类的表示相等不等于 大于 小于 大于等于 小于等于,而是使用字母表示的表达式。

他们的表示如下:
== eq 等于
!= ne 不等于
> gt 大于
< lt 小于
>= ge 大于等于
<= le 小于等于
not empty 不等于空 包括 null和""
empty  空 包括 null和""



EL的11个内置对象

  1. pageContext
  2. pageScope
            <% String str = "普通字符串";pageContext.setAttribute("key", str);%><p> ${pageScope.key} </p> //不写默认是pageScope域

  3. requestScope
    <% String str = "普通字符串";pageContext.setAttribute("key", str,pageContext.REQUEST_SCOPE);%><p> ${requestScope.key}----- </p>

  4. sessionScope
    <% String str = "普通字符串";pageContext.setAttribute("key", str,pageContext.SESSION_SCOPE);%><p> ${sessionScope.key}----- </p>

  5. applicationScope
    <% String str = "普通字符串";pageContext.setAttribute("key", str,pageContext.APPLICATION_SCOPE);%><p> ${applicationScope.key}----- </p>

  6. param
    <p>${param['id']}</p> <!-- 相当于request.getParameter("id")-->

  7. paramValues
    <p>${param['id']}</p> <!-- 相当于request.getParameter("id")-->

  8. header
    <p>${header['host'] }</p>

  9. headerValues
    <%=request.getHeaders("host").nextElement() %><p>${headerValues['host'][0] }</p>

  10. cookie 
       <% Cookie cook = new Cookie("cook","test"); response.addCookie(cook);%><p>${cookie['cook'].name }---${cookie['cook'].value }</p>

  11. initParam
    <p>${initParam['key'] }}</p>





使用总结:EL表达式可以替换jsp表达式,但是EL表达式局限: 不能条件判断,不能赋值,不能迭代。jsp标签替代jsp脚本,完成条件判断,赋值,迭代等等功能。