JSP中的EL表达式入门

一.EL是什么

EL(Expression Language) 是为了使JSP写起来更加简单。表达式语言的灵感来自于 ECMAScript 和 XPath 表达式语言,它提供了在 JSP 中简化表达式的方法,让Jsp的代码更加简化。

二.EL中的域对象

el有11个内置对象,其中4个是最重要的域对象

  1. pageScope
  2. requestScope
  3. sessionScope
  4. applicationScope
    还有以下7个域对象:
  5. pageContext
  6. param
  7. paramValues
  8. header
  9. headerValues
  10. cookie
  11. initParam

三.用法

1.写法:

${}

2.功能:

简单的运算
取出域对象中的参数并在页面展示

3.EL开关:

默认情况下el表达式是开启的
page指令中定义 isElIgnored=“true” 或者/${表达式}可以关闭el表达式

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="true" %>

\${3+2}

jsp页面不会输出5,而会输出${3+2}

4.取域对象中简单的值

  • 之前我们取域对象的方式:xxx.getAttribute(“键值”));
    例如:request.getAttribute("name"));
  • 用el表达式取域对象值:${键}
    例如:${name}这种方式是从最小的域范围到最大的域范围查找,如果找到符合的键,就取出其值,之后就算更大范围的域对象中有该同名键,也不会被取出来。
  • 也可以精确取出对象值:${xxxScope.键}
    例如:
<%--取出pageContext中的参数--%>
${pageScope.name}
<%--取出request中的参数--%>
${requestScope.name}
<%--取出session中的参数--%>
${sessionScope.name}
<%--取出application中的参数--%>
${applicationScope.name}

5.取域对象中复杂的值

<%--####################把new出来的对象存入域对象#################--%>
<%
    Hero hero = new Hero();
    hero.setId(001);
    hero.setName("李白");
    hero.setAge(18);
    pageContext.setAttribute("hero",hero);
%>
<%--取出--%>
${pageScope.hero}
${pageScope.hero.id}<br>


<%--#############################把数组存入域对象中######################--%>
<%
    String []s = {"李白","韩信","孙尚香"};
    pageContext.setAttribute("string",s);
%>
<%--取出--%>
${Arrays.toString(pageScope.string)}
${pageScope.string[0]}<br>


<%--#########################把list集合存入域对象中#########################--%>
<%
    ArrayList<Hero> list = new ArrayList<>();
    list.add(hero);
    pageContext.setAttribute("list",list);
%>
<%--取出--%>
${pageScope.list[0]}
${pageScope.list.get(0)}
${pageScope.list[0].name}<br>


<%--############################把map集合存入域对象中#############################--%>
<%
    HashMap<String, Hero> map = new HashMap<>();
    map.put("key",hero);
    pageContext.setAttribute("map",map);
%>
<%--取出--%>
${pageScope.map.key}
${pageScope.map["key"]}
${pageScope.map.key.age}

猜你喜欢

转载自blog.csdn.net/MrYushiwen/article/details/107593678