EL表达式

表达式语言(Expression Language,EL),EL表达式是用“${}”括起来的脚本,用来更方便的读取对象。

EL表达式主要用来读取数据,进行内容的显示。

没有使用EL表达式读取对象数据

page.jsp(向session设置一个属性)

<%
session.setAttribute("name","jack.ma");
System.out.println("向session中设置了一个属性");
%>

head.jsp(获取session设置的属性)

<%
String value=(String)session.getAttribute("name");
out.write(value);
%>

其实使用EL表达式,很简单

${name}

使用EL表达式可以方便地读取对象中的属性、提交的参数、JavaBean、甚至集合。

EL表达式语法:

${标识符}

EL表达式如果找不到相应的对象属性,返回空白字符串"",而不是null,这是EL表达式最大的特点。

 

EL表达式的作用

获取各类数据

获取域对象的数据

获取ServletContext属性(也就是application)类似上面获取session的属性。

${name}

EL表达式语句在执行的时候会调用findAttribute(String name)方法,用标识符作为关键字分别从page、request、session、application四个域中查找相应的对象。这就介绍了EL表达式可以仅仅通过标识符就能获取到存进域对象的数据。

findAttribute()的查找顺序:从小到大,也就是page-->request-->session-->application

获取JavaBean的属性

page.jsp(Session存进一个Person对象,设置age的属性为23)

<jsp:useBean id="person" class="com.company.Person" scope="session"/>
<jsp:setProperty name="person" property="age" value="23"/>

head.jsp(获取Session的属性)

<%
    Person person=(Person) session.getAttribute("person");
    System.out.println(person.getAge());
%>

而使用EL表达式更简单

//等同于person.getAge()
${person.age}

获取集合的数据

EL表达式中也很好地支持了集合的操作,可以非常方便地读取Collection和Map集合的内容。

page.jsp  设置session的属性,session属性的值是List集合,List集合装载的又是Person对象

<%
    List<Person> list=new ArrayList<>();
    Person p1=new Person();
    p1.setName("tom");
    p1.setAge(20);
    Person p2=new Person();
    p2.setName("jerry");
    p2.setAge(21);
    list.add(p1);
    list.add(p2);
    session.setAttribute("list",list);
%>

head.jsp 获取session属性,并输出在页面上

<%
    List list = (List<Person>)session.getAttribute("list");
    out.write((list.get(0))+"<br>");
    out.write(list.get(1)+"<br>");
%>

而采用EL表达式,则更简单

<%--取出list集合的第一个元素---%>
${list[0]}
<br>
<%--取出list集合的第二个元素---%>
${list[1]}

输出同样的结果

page.jsp session属性存储了Map集合,Map集合的关键字是字符串,值是Person对象

<%
    Map<String,Person> map=new HashMap<>();
    Person p1=new Person();
    p1.setName("jack");
    p1.setAge(10);
    Person p2=new Person();
    p2.setName("john");
    p2.setAge(12);
    map.put("p1",p1);
    map.put("p2",p2);
    session.setAttribute("map",map);
%>

head.jsp EL表达式获取数据

${map.p1}
<br>
${map.p2}

输出结果:

如果Map集合存储的关键字是一个数字,就不能使用“.”号运算符,只能使用“[]”的形式读取Map集合的数据。

${map["1"]}
<br>
${map["2"].name}

 

EL运算符

EL表达式支持简单的运算符:加减乘除取模,逻辑运算符。empty运算符(判断是否为null),三目运算符。

empty运算符可以判断对象是否为null,用于流程控制。

三目运算符简化了if和else语句,简化了代码书写。

<%
List<Person> list=null;
%>
${list==null?"list集合为空":"list集合不为空"}

EL表达式11个内置对象

EL表达式主要是来对内容的显示,为了显示,EL表达式提供了11个内置对象。

  1. pageContext 对应于JSP页面中的pageContext对象(注意:取的是pageContext对象)
  2. pageScope 代表page域中用于保存属性的Map对象
  3. requestScope 代表request域中用于保存属性的Map对象
  4. sessionScope 代表session域中用于保存属性的Map对象
  5. applicationScope 代表application域中用于保存属性的Map对象
  6. param 表示一个保存了所有请求参数的Map对象
  7. paramValues表示一个保存了所有请求参数的Map对象,它对于某个请求参数,返回的是一个string[]
  8. header 表示一个保存了所有http请求头字段的Map对象
  9. headerValues同上,返回string[]数组。
  10. cookie 表示一个保存了所有cookie的Map对象
  11. initParam 表示一个保存了所有web应用初始化参数的map对象
<%--pageContext内置对象--%>
<%
    pageContext.setAttribute("pageContext1", "pageContext");
%>
pageContext内置对象:${pageContext.getAttribute("pageContext1")}
<br>

<%--pageScope内置对象--%>
<%
    pageContext.setAttribute("pageScope1","pageScope");
%>
pageScope内置对象:${pageScope.pageScope1}
<br>

<%--requestScope内置对象--%>
<%
    request.setAttribute("request1","reqeust");
%>
requestScope内置对象:${requestScope.request1}
<br>

<%--sessionScope内置对象--%>
<%
    session.setAttribute("session1", "session");
%>
sessionScope内置对象:${sessionScope.session1}
<br>

<%--applicationScope内置对象--%>
<%
    application.setAttribute("application1","application");
%>
applicationScopt内置对象:${applicationScope.application1}
<br>

<%--header内置对象--%>
header内置对象:${header.Host}
<br>

<%--headerValues内置对象,取出第一个Cookie--%>
headerValues内置对象:${headerValues.Cookie[0]}
<br>


<%--Cookie内置对象--%>
<%
    Cookie cookie = new Cookie("Cookie1", "cookie");
%>
Cookie内置对象:${cookie.JSESSIONID.value}
<br>

<%--initParam内置对象,需要为该Context配置参数才能看出效果【jsp配置的无效!亲测】--%>

initParam内置对象:${initParam.name}

<br>

输出的结果:

注意事项:

  • 测试headerValues时,如果头里面有“-” ,例Accept-Encoding,则要headerValues[“Accept-Encoding”]
  • 测试cookie时,例${cookie.key}取的是cookie对象,如访问cookie的名称和值,须${cookie.key.name}${cookie.key.value}
  • 测试initParam时,初始化参数要的web.xml中的配置Context的,仅仅是jsp的参数是获取不到的

上面已经测过了9个内置对象了,至于param和parmaValues内置对象一般都是别的页面带数据过来的(表单、地址栏)

index.jsp

  <form action="head.jsp" method="post">
    用户名:<input type="text" name="username"/> <br>
    年龄:<input type="text" name="age"/><br>
    <input type="checkbox" name="hobbies" value="football"/>足球
    <input type="checkbox" name="hobbies" value="basketball"/>篮球
    <input type="checkbox" name="hobbies" value="table tennis"/>乒乓球
    <br>
    <input type="submit" value="提交"/>
  </form>

head.jsp  获取数据

${param.username}
<br>
${param.age}
<br>
${paramValues.hobbies[0]}
<br>
${paramValues.hobbies[1]}
<br>
${paramValues.hobbies[2]}

显示结果:

EL表达式回显数据

EL表达式最大的特点就是:如果获取到的数据为null,输出空白字符串""。

<%
Person person=new Person();
person.setName("jerry");
request.setAttribute("user",person);
%>
<input type="radio" name="team" value="jack" ${user.name=="jack"?"checked":""}/>JACK
<br>
<input type="radio" name="team" value="jerry" ${user.name=="jerry"?"checked":""}/>JERRY

显示结果:

 

EL自定义函数

EL自定义函数用于扩展EL表达式的功能,可以让EL表达式完成普通Java程序代码所能完成的功能。

开发HTML转义的EL函数。

有时候想在JSP页面中输出JSP代码,但是JSP引擎会自动把HTML代码解析,输出给浏览器。此时就要对HTML代码转义。

步骤:

编写一个包含静态方法的类(EL表达式只能调用静态方法),该方法很常用,Tomcat都有该方法,在apache-tomcat-9.0.11\webapps\examples\WEB-INF\classes\util中找到HTMLFilter.java。

    public static String filter(String message) {

        if (message == null)
            return null;

        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuilder result = new StringBuilder(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
            case '<':
                result.append("&lt;");
                break;
            case '>':
                result.append("&gt;");
                break;
            case '&':
                result.append("&amp;");
                break;
            case '"':
                result.append("&quot;");
                break;
            default:
                result.append(content[i]);
            }
        }
        return result.toString();
    }

在WEB-INF目录下创建tld(taglib description)文件,在tld文件中描述自定义函数

<?xml version="1.0" encoding="ISO-8859-1"?>

<taglib xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
        version="2.1">

    <tlib-version>1.0</tlib-version>
    <short-name>myshortname</short-name>
    <uri>/filter</uri>

    <!--函数的描述-->
    <function>
        <!--函数的名字-->
        <name>filter</name>
        <!--函数位置-->
        <function-class>com.company.util.HTMLFilter</function-class>
        <!--函数的方法声明-->
        <function-signature>java.lang.String filter(java.lang.String)</function-signature>
    </function>
</taglib>

在JSP页面中导入和使用自定义函数,EL自定义的函数一般前缀为"fn",uri是"/WEB-INF/tld文件名称"

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="fn" uri="/WEB-INF/filter.tld" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>  
  ${fn:filter("<a href='#'>点我</a>")}
 <%
   out.println("<a href='#'>点我</a>");
 %>
  </body>
</html>

效果对比:

 

EL函数库(fn方法库)

  • 由于在JSP页面中显示数据时,经常需要对显示的字符串进行处理,SUN公司针对于一些常见处理定义了一套EL函数库供开发者使用。
  • 其实EL函数库就是fn方法库,是JSTL标签库中的一个库,也有人称之为fn标签库,也可以成为fn方法库。
  • 既然作为JSTL标签库中的一个库,要使用fn方法库就需要导入JSTL标签!要想使用JSTL标签库就要导入jstl.jar和stardard.jar

首先导入开发包(jstl.jar和standard.jar)

其次在JSP页面中指明使用标签库

<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

fn方法库全都是跟字符串有关的(可以把它想成是String的方法)

  • fn:toLowerCase
  • fn:toUpperCase
  • fn:trim
  • fn:length
  • fn:split
  • fn:join 【接收字符数组,拼接字符串】
  • fn:indexOf
  • fn:contains
  • fn:startsWith
  • fn:replace
  • fn:substring
  • fn:substringAfter
  • fn:endsWith
  • fn:escapeXml【忽略XML标记字符】
  • fn:substringBefore
contains:${fn:contains("jackjerry",jack )}<br>

containsIgnoreCase:${fn:containsIgnoreCase("jackjerry",JACK )}<br>

endsWith:${fn:endsWith("jackjerry","erry" )}<br>

escapeXml:${fn:escapeXml("<jack>你是谁呀</jack>")}<br>

indexOf:${fn:indexOf("jackjerry","j" )}<br>

length:${fn:length("jackjerry")}<br>

replace:${fn:replace("jackjerry","j" ,"ab" )}<br>

split:${fn:split("jack,tom,jerry","," )}<br>

startsWith:${fn:startsWith("jackjerry","jac" )}<br>

substring:${fn:substring("jackjerry","2" , fn:length("jackjerry"))}<br>

substringAfter:${fn:substringAfter("jackjerry","jack" )}<br>

substringBefore:${fn:substringBefore("jackjerry","jerry" )}<br>

toLowerCase:${fn:toLowerCase("JACkJerry")}<br>

toUpperCase:${fn:toUpperCase("JACkJerry")}<br>

trim:${fn:trim("              jack    jerry    ")}<br>

<%--将分割成的字符数组用"."拼接成一个字符串--%>
join:${fn:join(fn:split("jack,tom,jerry","," ),"." )}<br>

显示的结果:

使用fn方法库数据回显

<%
    Person person = new Person();
    person.setName("jack");

    request.setAttribute("person", person);
%>
<input type="checkbox" ${fn:contains(person.getName(),"jack")?"checked":""}>Jack
<input type="checkbox" ${fn:contains(person.getName(),"jerry")?"checked":""}>Jerry

 

 posted on 2019-06-19 23:11  会飞的金鱼  阅读(154)  评论(0)    收藏  举报