JSP第四篇【EL表达式介绍、获取各类数据、11个内置对象、执行运算、回显数据、自定义函数、fn方法库】(修订版)...

 
 

前言

只有光头才能变强。

文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y

什么是EL表达式?

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

为什么要使用EL表达式?

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%><html><head>    <title>向session设置一个属性</title></head><body><%    //向session设置一个属性    session.setAttribute("name", "aaa");    System.out.println("向session设置了一个属性");%></body></html>"text/html" pageEncoding="UTF-8"%>
<html>
<head>
    <title>向session设置一个属性</title>
</head>
<body>

<%
    //向session设置一个属性
    session.setAttribute("name""aaa");
    System.out.println("向session设置了一个属性");
%>

</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title></title></head><body><%        String value = (String) session.getAttribute("name");        out.write(value);%></body></html>"java" %>
<html>
<head>
    <title></title>
</head>
<body>

<%
        String value = (String) session.getAttribute("name");
        out.write(value);
%>
</body>
</html>
640?wx_fmt=png
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title></title></head><body>${name}</body></html>"java" %>
<html>
<head>
    <title></title>
</head>
<body>

${name}

</body>
</html>
640?wx_fmt=png

EL表达式的作用

${标识符}

获取各类数据

获取域对象的数据

<%    //向ServletContext设置一个属性    application.setAttribute("name", "aaa");    System.out.println("向application设置了一个属性");%>//向ServletContext设置一个属性
    application.setAttribute("name""aaa");
    System.out.println("向application设置了一个属性");
%>
<%    ${name}%>

%>
640?wx_fmt=png

获取JavaBean的属性

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

在2.jsp中取出Session的属性

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

    System.out.println(person.getAge());
%>
640?wx_fmt=png
//等同于person.getAge()${person.age}
${person.age}
640?wx_fmt=png

获取集合的数据

<%    List<Person> list = new ArrayList();    Person person1 = new Person();    person1.setUsername("zhongfucheng");    Person person2 = new Person();    person2.setUsername("ouzicheng");    list.add(person1);    list.add(person2);    session.setAttribute("list",list);%>new ArrayList();

    Person person1 = new Person();
    person1.setUsername("zhongfucheng");

    Person person2 = new Person();
    person2.setUsername("ouzicheng");

    list.add(person1);
    list.add(person2);

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

    out.write(list.get(0).getUsername()+"<br>");

    out.write(list.get(1).getUsername());

%>

使用EL表达式又是怎么样的效果呢?我们来看看

<%--取出list集合的第1个元素(下标从0开始),获取username属性--%>${list[0].username}<br><%--取出list集合的第2个元素,获取username属性--%>${list[1].username}0开始),获取username属性--%>
${list[0].username}
<br>
<%--取出list集合的第2个元素,获取username属性--%>
${list[1].username}
640?wx_fmt=png
<%    Map<String, Person> map = new HashMap<>();    Person person1 = new Person();    person1.setUsername("zhongfucheng1");    Person person2 = new Person();    person2.setUsername("ouzicheng1");    map.put("aa",person1);    map.put("bb",person2);    session.setAttribute("map",map);%>
    Map<String, Person> map = new HashMap<>();

    Person person1 = new Person();
    person1.setUsername("zhongfucheng1");

    Person person2 = new Person();
    person2.setUsername("ouzicheng1");

    map.put("aa",person1);
    map.put("bb",person2);

    session.setAttribute("map",map);
%>
${map.aa.username}<br>${map.bb.username}
${map.bb.username}
640?wx_fmt=png
640?wx_fmt=png
${map["1"].username}<br>${map["2"].username}
<br>
${map["2"].username}

EL运算符

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

${list==null?"list集合为空":"list集合不为空"}
640?wx_fmt=png

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>
    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>
640?wx_fmt=png

注意事项:

<form action="/zhongfucheng/1.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="提交"><br></form>"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="提交"><br>
</form>
${param.username}<br>${param.age}<br>//没有学习jstl之前就一个一个写吧。${paramValues.hobbies[0]}<br>${paramValues.hobbies[1]}<br>${paramValues.hobbies[2]}<br>

${param.age}
<br>

//没有学习jstl之前就一个一个写吧。
${paramValues.hobbies[0]}
<br>

${paramValues.hobbies[1]}
<br>

${paramValues.hobbies[2]}
<br>
640?wx_fmt=png
640?wx_fmt=png

EL表达式回显数据

EL表达式最大的特点就是:如果获取到的数据为null,输出空白字符串""!这个特点可以让我们数据回显

<%--模拟数据回显场景--%><%    User user = new User();    user.setGender("male");    //数据回显    request.setAttribute("user",user);%><input type="radio" name="gender" value="male" ${user.gender=='male'?'checked':'' }>男<input type="radio" name="gender" value="female" ${user.gender=='female'?'checked':'' }>女
    User user = new User();
    user.setGender("male");

    //数据回显
    request.setAttribute("user",user);
%>


<input type="radio" name="gender" value="male" ${user.gender=='male'?'checked':'' }>男
<input type="radio" name="gender" value="female" ${user.gender=='female'?'checked':'' }>女
640?wx_fmt=png

EL自定义函数

EL自定义函数用于扩展EL表达式的功能,可以让EL表达式完成普通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());}

    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());

}
<?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>/zhongfucheng</uri>    <!--函数的描述-->    <function>        <!--函数的名字-->        <name>filter</name>        <!--函数位置-->        <function-class>utils.HTMLFilter</function-class>        <!--函数的方法声明-->        <function-signature>java.lang.String filter(java.lang.String)</function-signature>    </function></taglib>

<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>/zhongfucheng</uri>

    <!--函数的描述-->
    <function>

        <!--函数的名字-->
        <name>filter</name>

        <!--函数位置-->
        <function-class>utils.HTMLFilter</function-class>

        <!--函数的方法声明-->
        <function-signature>java.lang.String filter(java.lang.String)</function-signature>
    </function>

</taglib>
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8" %><%@taglib prefix="fn" uri="/WEB-INF/zhongfucheng.tld" %><html><head>    <title></title></head><body>//完成了HTML转义的功能${fn:filter("<a href='#'>点我</a>")}</body></html>
<%@taglib prefix="fn" uri="/WEB-INF/zhongfucheng.tld" %>


<html>
<head>
    <title></title>
</head>
<body>

//完成了HTML转义的功能
${fn:filter("<a href='#'>点我</a>")}


</body>
</html>
640?wx_fmt=png

EL函数库(fn方法库)

640?wx_fmt=png
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>"fn" uri="http://java.sun.com/jsp/jstl/functions" %>
contains:${fn:contains("zhongfucheng",zhong )}<br>containsIgnoreCase:${fn:containsIgnoreCase("zhongfucheng",ZHONG )}<br>endsWith:${fn:endsWith("zhongfucheng","eng" )}<br>escapeXml:${fn:escapeXml("<zhongfucheng>你是谁呀</zhongfucheng>")}<br>indexOf:${fn:indexOf("zhongfucheng","g" )}<br>length:${fn:length("zhongfucheng")}<br>replace:${fn:replace("zhongfucheng","zhong" ,"ou" )}<br>split:${fn:split("zhong,fu,cheng","," )}<br>startsWith:${fn:startsWith("zhongfucheng","zho" )}<br>substring:${fn:substring("zhongfucheng","2" , fn:length("zhongfucheng"))}<br>substringAfter:${fn:substringAfter("zhongfucheng","zhong" )}<br>substringBefore:${fn:substringBefore("zhongfucheng","fu" )}<br>toLowerCase:${fn:toLowerCase("zhonGFUcheng")}<br>toUpperCase:${fn:toUpperCase("zhongFUcheng")}<br>trim:${fn:trim("              zhong    fucheng    ")}<br><%--将分割成的字符数组用"."拼接成一个字符串--%>join:${fn:join(fn:split("zhong,fu,cheng","," ),"." )}<br>

containsIgnoreCase:${fn:containsIgnoreCase("zhongfucheng",ZHONG )}<br>

endsWith:${fn:endsWith("zhongfucheng","eng" )}<br>

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

indexOf:${fn:indexOf("zhongfucheng","g" )}<br>

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

replace:${fn:replace("zhongfucheng","zhong" ,"ou" )}<br>

split:${fn:split("zhong,fu,cheng","," )}<br>

startsWith:${fn:startsWith("zhongfucheng","zho" )}<br>

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

substringAfter:${fn:substringAfter("zhongfucheng","zhong" )}<br>

substringBefore:${fn:substringBefore("zhongfucheng","fu" )}<br>

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

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

trim:${fn:trim("              zhong    fucheng    ")}<br>

<%--将分割成的字符数组用"."拼接成一个字符串--%>
join:${fn:join(fn:split("zhong,fu,cheng","," ),"." )}<br>
640?wx_fmt=png
<%    User user = new User();    String likes[] = {"sing"};    user.setLikes(likes);    //数据回显    request.setAttribute("user",user);%><%--java的字符数组以","号分割开,首先拼接成一个字符串,再判读该字符串有没有包含关键字,如果有就checked--%><input type="checkbox"${ fn:contains(fn:join(user.likes,","),"sing")?'checked':'' }>唱歌<input type="checkbox"${ fn:contains(fn:join(user.likes,","),"dance")?'checked':'' }>跳舞new User();
    String likes[] = {"sing"};
    user.setLikes(likes);

    //数据回显
    request.setAttribute("user",user);
%>


<%--java的字符数组以","号分割开,首先拼接成一个字符串,再判读该字符串有没有包含关键字,如果有就checked--%>
<input type="checkbox"${ fn:contains(fn:join(user.likes,","),"sing")?'checked':'' }>唱歌
<input type="checkbox"${ fn:contains(fn:join(user.likes,","),"dance")?'checked':'' }>跳舞
640?wx_fmt=png

最后

乐于输出干货的Java技术公众号:Java3y。公众号内有200多篇原创技术文章、海量视频资源、精美脑图,不妨来关注一下!

640?wx_fmt=jpeg

有帮助?好看!转发! 640


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值