EL 表达式

介绍

EL :Expression Language,表达式语言。

作用

EL 表达式代替 jsp 中的表达式(<%= %>),用于显示数据,但功能更强大,代码更简洁

由于 技术更迭,jsp 使用的越来越少,这里只介绍 EL 表达式常用的功能

在一些java框架中,也会用到 EL 表达式,所以要会用 EL 表达式

语法

${x}

解释:

相当于调用 pageContext.getAttribute("x") 方法,并将 值 显示到jsp页面上

如果 pageContext.getAttribute("x") 取出的值为null,就继续执行 request.getAttribute("x")

如果 request.getAttribute("x") 取出的值为null,就继续执行 session.getAttribute("x")

如果 session.getAttribute("x") 取出的值为null,就继续执行 application.getAttribute("x")

如果 application.getAttribute("x") 取出的值为null,就什么都不显示

取值优先级:pageContext > request > session > application

例子

创建 jsp ,代码如下:

<%
    pageContext.setAttribute("name", "pageContext");
    request.setAttribute("name", "request");
    session.setAttribute("name", "session");
    application.setAttribute("name", "application");
%>

${name}

指定对象取值

pageScope.name:从 pageContext 对象中取 name 值
requestScope.name:从 requestScope 对象中取 name 值
sessionScope.name:从 sessionScope 对象中取 name 值
applicationScope.name:从 applicationScope 对象中取 name 值

运算

算数运算

  • +:加法,例子:${ 1 + 5 }

  • -:减法,例子:${ 1 - 5 }

  • *:乘法,例子:${ 2 * 5 }

  • /:除法,例子:${ 4 / 2 }

  • %:取模,例子:${ 1 / 2 }

关系运算

  • ==:等于,例子:${ 1 == 1 },结果 true

  • !=:不等于,例子: ${ 1 !=1 },结果 false

  • <:小于,例子: ${ 1 < 2 },结果 true

  • >:大于,例子: ${ 1 > 10 },结果 false

  • <=:小于等于,例子:${ 1 <= 10 },结果 true

  • >=:大于等于,例子:${ 1 >= 5 },结果 false

逻辑运算

  • &&:与运算,例子:${ 1 == 1 && 4 < 2 } 结果 false

  • ||:或运算,例子:${ 1 == 1 || 4 < 2 } 结果 true

  • !:取反,例子:${ !(1 == 1) }

. 运算符

取出 对象中的属性值,并显示到 jsp 页面上

例子

创建java类,如下:

public class Student{
    private String name;
    private int age;

    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;
    }
}

创建 jsp,内容如下:

<%
Student student=new Student();
student.setName("李雷");
student.setAge(20);

pageContext.setAttribute("std",student);
%>

姓名:${std.name} <br>
年龄:${std.age} <br>

[] 运算符

作用一

可以从 数组、List 中取出某个元素的值,显示到 jsp 页面上

<%
    List list=new ArrayList();
    list.add("李雷");
    list.add("韩梅梅");
    list.add("lucy");
    pageContext.setAttribute("list",list);
%>

${list[1]}

作用二:

从 Map 中 取值,显示到 jsp 页面上

<%
    Map map=new HashMap();
    map.put("name","李雷");
    map.put("age","20");
    pageContext.setAttribute("map",map);
%>

姓名:${map["name"]}
年龄:${map["age"]}

原文出处:/show_1IXsdC7mjkS.html