码迷,mamicode.com
首页 > 其他好文 > 详细

EL表达式

时间:2014-05-14 08:53:17      阅读:421      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   c   

EL表达式

基本语法:${EL表达式}

1.获取数据

1)EL表达式只能获取四大域中的数据。

2)EL表达式获取的对象如果是null,页面不会显示数据。因此,EL表达式中永远不会出现空指针异常。

3).运算符和[]运算符

.运算符能做的,[]运算符也能做。[]运算符能做,.运算符不一定能做。

eg:

bubuko.com,布布扣
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="cn.lsl.domain.Person"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
  </head>
  
  <body>
    <jsp:useBean id="person" class="cn.lsl.domain.Person"></jsp:useBean>
    <jsp:setProperty property="name" name="person" value="lsl"/>
    ${person.name }
    <hr/>
    <%
        pageContext.setAttribute("pp","p1");
        pageContext.setAttribute("pp","p2",PageContext.SESSION_SCOPE);
        request.setAttribute("pp","p3");
        application.setAttribute("pp","p4");
     %>
     ${pp }
     <hr/>
     ${person.address.city }<br/>
     ${person.class }<br/>
     ${person[‘class‘] }  
     <hr/>
     <!-- 获取数组中指定的元素 -->   
     <%
         String str[] = {"a","b","c"};
         pageContext.setAttribute("str",str);
      %>
     ${str[1] }
     <hr/>
     <%
         List list = new ArrayList();
         list.add("aa");
         list.add("bb");
         list.add("cc");
         pageContext.setAttribute("list",list);
     %>
     ${list[2] }
     <hr/>
     <%
         Map map = new LinkedHashMap();
         map.put("a","aaa");
         map.put("b","bbb");
         map.put("c","ccc");
         pageContext.setAttribute("mm",map);
     %>
     ${mm.b }
     <hr/>
     <%
         Map map1 = new LinkedHashMap();
         map1.put("1","aaa");
         map1.put("2","bbb");
         map1.put("3","ccc");
         pageContext.setAttribute("mm1",map1);
     %>
     ${mm1["3"] }
     <hr/>
      <%
         Map map2 = new LinkedHashMap();
         map2.put("a",new Person("lsl","男",true));
         map2.put("b",new Person("zs","女",false));
         map2.put("c",new Person("ls","女",true));
         pageContext.setAttribute("mm2",map2);
     %>
     ${mm2["a"].name }<br/>
     ${mm2["b"].name }<br/>
     ${mm2.c.name }<br/>
     
  </body>
</html>
bubuko.com,布布扣

2.数学逻辑运算

empty运算符:如果判断的对象是null或者空字符串,都返回true。对于集合对象本身不是                       null,没有任何元素,也返回true。

EL表达式不支持字符串连接操作。

eg:

bubuko.com,布布扣
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
  </head>
  
  <body>
    <jsp:useBean id="person" class="cn.lsl.domain.Person"></jsp:useBean>
    ${empty p }
    <hr/>
    <%
        List list = new ArrayList();
        list.add("aaa");
        pageContext.setAttribute("list",list);
    %>
    ${empty list }
    <hr/>
    <%
        session.setAttribute("user","lsl");
     %>
    ${empty user?"请登录":"欢迎您:" }${user }<br/>
    <hr/>
    <%
        pageContext.setAttribute("gender","0");
     %>
     ${gender == "0"?"女":"男" }
    <hr/>
  </body>
</html>
bubuko.com,布布扣

3.获取JSP的内置对象(11大EL内置对象)

难点,不要与JSP的内置对象和范围名称搞混

11大EL隐式对象中,其中一个是表示自身对象外,其余都是表示的Map结构

                  

EL隐式对象名称                Java类型                                              备注

pageContext                     javax.servlet.jsp.PageContext                与JSP中的内置对象完全相同

剩余的都是代表的Map集合

pageScope                        java.util.Map                                        代表着PageContext页面范围域那个Map

requestScope                    java.util.Map                                        代表着ServletRequest请求范围域那个Map

sessionScope                    java.util.Map                                        代表着HttpSession会话范围域那个Map

applicationScope                java.util.Map                                        代表着ServletContext应用范围域那个Map

param                               java.util.Map                                        代表着请求参数。key:请求参数的名称。value:请求参数的值,它是 一个字符串。

paramValues                      java.util.Map                                        代表着请求参数。key:请求参数的名称。value:请求参数的值,它是 一个字符串数组。             

header                              java.util.Map                                        代表着请求消息头。key:头名称。value:头值,它是一个字符串。

headerValues                     java.util.Map                                        代表着请求消息头。key:头名称。 value:头值,它是一个字符串数组。

cookie                               java.util.Map                                        代表客户端提交的Cookie的Map。key:cookie的name。value:cookie对象本身

initParam                           java.util.Map                                        代表着全局初始化参数(web.xml中context-param).key:参数名称。value:参数值

eg:

bubuko.com,布布扣
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="cn.lsl.domain.Person"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>EL的11大隐式对象</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
  </head>
  
  <body>
    <br/>-----------------pageContext内置对象-----------------<br/>
    ${pageContext }<br/>
    ${pageContext.request }<br/>
    <!-- EL表达式获取当前应用名称 -->
    ${pageContext.request.contextPath }<br/>
    <!-- EL表达式获取HttpServletResponse采用的编码 -->
    ${pageContext.response.characterEncoding }<br/>
    <br/>-----------------pageScope内置对象-----------------<br/>
    <%
        pageContext.setAttribute("pp","ppp");
        pageContext.setAttribute("p",new Person("lsl","男",false));
    %>
    ${pageScope.pp }<br/>
    ${pageScope.p.name }<br/>
    <hr/>
    <%
        pageContext.setAttribute("p1",new Person("lsl","男",false),PageContext.REQUEST_SCOPE);
    %>
    ${requestScope.p1.gender }
    <hr/>
    <%
        Person person = new Person("lsl","女",true);
        session.setAttribute("user",person);
    %>
    ${empty sessionScope.user?"请登录":"欢迎您:" }${sessionScope.user.name }
    <hr/>
    ${param.username }<br/>
    ${param.password }<br/>
    <hr/>
    <!-- http://localhost:8080/EL/3.jsp?username=abc&username=def&password=123 -->
    ${paramValues.username[0] }<br/>
    ${paramValues.username[1] }<br/>
    ${paramValues.password[0] }<br/>
    <hr/>
    ${header["accept-encoding"] }<br/>
    ${headerValues["accept-encoding"][0] }<br/>
    <hr/>
    <!-- 取JSESSIONID这个cookie的名字  -->
    ${cookie["JSESSIONID"].name }<br/>
    ${cookie.JSESSIONID.value}
    <hr/>
    ${initParam.encoding }
    <!-- 
        <context-param>
              <param-name>encoding</param-name>
              <param-value>UTF-8</param-value>
          </context-param>
     -->
  </body>
</html>
bubuko.com,布布扣

4.调用普通类的静态方法(EL函数)

编写步骤(自定义EL函数的编写步骤即自定义标签的编写步骤):

a、编写一个普通的java类,提供一个静态方法

bubuko.com,布布扣
public class FunctionDemo {
        public static String toUpperCase(String str){
            return str.toUpperCase();
        }
    }
bubuko.com,布布扣

b、在JavaWeb应用的WEB-INF目录下建立一个扩展名是tld(taglib definition)的XML文件(参考Tomcat中的示例)。内容如下:

bubuko.com,布布扣
<?xml version="1.0" encoding="UTF-8"?>
            <taglib 
                xmlns="http://java.sun.com/xml/ns/j2ee"                                               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee                                   http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
                version="2.0">
                    <tlib-version>1.0</tlib-version>
                    <short-name>myfn</short-name>
                    <uri>http://www.lsl.cn/myfn</uri>
                <function><!-- 定义函数 -->
                    <name>toUppercase</name>
                    <function-class>cn.lsl.el.FunctionDemo</function-class>
                    <function-signature>
                        java.lang.String toUpperCase( java.lang.String )
                    </function-signature>
                </function>
            </taglib>
bubuko.com,布布扣

 

c、(可选步骤)前提是把tld文件放到了WEB-INF目录下。 

告知应用,tld文件和tld中的uri的对应。修改web.xml,增加以下内容:

bubuko.com,布布扣
<jsp-config>
        <taglib>
            <taglib-uri>http://www.lsl.cn/myfn</taglib-uri>
            <taglib-location>/WEB-INF/myfn.tld</taglib-location>
        </taglib>
    </jsp-config>
bubuko.com,布布扣

d、在JSP中使用

用taglib指令,引入自定义的EL函数库

bubuko.com,布布扣
<%@ taglib uri="http://www.lsl.cn/myfn" prefix="myfn"%>
    ${myfn:toUppercase(p)}
bubuko.com,布布扣

eg:

FunctionDemo.java

bubuko.com,布布扣
package cn.lsl.el;
public class FunctionDemo {
    public static String toUpperCase(String str){
        return str.toUpperCase();
    }
}
bubuko.com,布布扣

myfn.tld

bubuko.com,布布扣
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
    <tlib-version>1.0</tlib-version>
    <short-name>myfn</short-name>
    <uri>http://www.lsl.cn/myfn</uri>
    <function><!-- 定义函数 -->
        <name>toUppercase</name>
        <function-class>cn.lsl.el.FunctionDemo</function-class>
        <function-signature>java.lang.String toUpperCase( java.lang.String )</function-signature>
    </function>
</taglib>
bubuko.com,布布扣

web.xml

bubuko.com,布布扣
<jsp-config>
        <taglib>
            <taglib-uri>http://www.lsl.cn/myfn</taglib-uri>
            <taglib-location>/WEB-INF/myfn.tld</taglib-location>
        </taglib>
</jsp-config>
bubuko.com,布布扣
bubuko.com,布布扣
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.lsl.cn/myfn" prefix="myfn"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
  </head>
  
  <body>
     <%
        pageContext.setAttribute("p","abcdefg");
     %>
    ${myfn:toUppercase(p)}
  </body>
</html>
bubuko.com,布布扣

5.SUN提供的标准EL函数库

JSTL标准标签

需要导入JSTL的jar包。standard.jar jstl.jar

eg:

bubuko.com,布布扣
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
  </head>
  
  <body>
      ${fn:contains("abc","bc") }<br/>
    ${fn:substring("shit",3,100) }<br/>  ${fn:split("www.lsl.cn",".")[0]}${fn:split("www.lsl.cn",".")[1]}
${fn:split("www.lsl.cn",".")[2]}<br/>
    ${fn:split("2013-04/26","-/")[0]}<br/>
    ${fn:split("2013-04/26","-/")[1]}<br/>
    ${fn:split("2013-04/26","-/")[2]}<br/>
    &lt;hr/&gt;<br/>
    <%
    pageContext.setAttribute("h","<h1>haha</h1>");
    %>
    ${fn:escapeXml(h)}
  </body>
</html>
bubuko.com,布布扣

拓展:

Functions标签库中常用的16个函数的用法

1)fn:contains函数用于判断在源字符串中是否包含目标字符串,其语法为:

fn:contains(String source,String target) -------boolean;

2)fn:containsIgnoreCase函数用于判断在源字符串中是否包含目标字符串,并且在判断时忽略大小写,其语法为:

fn: containsIgnoreCase (String source,String target) -------boolean;

3)fn:startsWith函数用于判断源字符串是否以指定的目标字符串开头,其语法为:

fn:startsWith(String source,String target) ----boolean

4)fn: endsWith函数用于判断源字符串是否以指定的目标字符串结尾,其语法为:

fn: endsWith (String source,String target) ----boolean

5)fn:indexOf函数用于在源字符串中查找目标字符串,并返回源字符串中最先与目标字符串匹配的第一个字符的索引,如果在源字符串中不包含目标字符串,就返回-1,源字符串中的第一个字符的索引为0。 fn:indexOf函数的语法为:

fn: indexOf (String source,String target) ----int

6)fn:replace函数用于把源字符串中的一部分替换为另外的字符串,并返回替换后的字符串。fn:replace函数的语法为:

fn: replace (String source,String before,String after) ----String

7)fn:substring函数用于获取源字符串中的特定子字符串,它的语法为:

fn:substring(String source,int beginIndex,int endIndex) ------String

8)fn:substringBefore函数用于获取源字符串中指定子字符串之前的子字符串,其语法为:

fn:substringBefore(String source,String target) ----String

9)fn: substringAfter函数用于获取源字符串中指定子字符串之后的子字符串,其语法为:

fn: substringAfter (String source,String target) ----String

10)fn:split函数用于将源字符串拆分为一个字符串数组,其语法为:

fn: split (String source,String delimiter) ----String[]

11)fn:join函数用于将源字符串数组中的所有字符串连接为一个字符串,其语法为:

fn:join(String source[],String separator) ----String

12)fn:toLowerCase函数用于将源字符串中的所有字符改为小写,其语法为:

fn:toLowerCase(String source)  -----String

13)fn: toUpperCase函数用于将源字符串中的所有字符改为大写,其语法为:

fn: toUpperCase (String source)  -----String

14)fn:trim函数用于将源字符串中的开头和末尾的空格删除,其语法为:

fn:trim(String source) ----String

15)fn:escapeXml函数用于将源字符串中的字符“<”、“>”、“””和“&”等转换为转义字符,本书第1章的1.2节(HTML简介)介绍了转义字符的概念。fn:escapeXml函数的行为与<c:out>标签的escapeXml属性为true时的转换行为相同,fn:escapeXml函数的语法为:

fn:escapeXml(String source) ----String

16)fn:length函数用于返回字符串中的字符的个数,或者集合和数组的元素的个数,其语法为:

fn:length(source) ---- int

6. c:if

作用:判断是否为true,如果为true,那么标签的主体内容就会显示。

属性:

         test:必须的。要求必须是boolean的。支持表达式(EL或Java表达式)

         var:保存test运算结果的变量

         scope: 保存的域范围。默认是page

eg:

bubuko.com,布布扣
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
  </head>
  
  <body>
      <% 
          pageContext.setAttribute("result",true); 
       %>
       <c:if test="${result}">
           真的
       </c:if>
       <hr/>
       <%
        session.setAttribute("user","lsl");
     %>
     <c:if test="${sessionScope.user==null}">
         对不起!请登录
     </c:if>
     <c:if test="${sessionScope.user!=null}">
         欢迎您:${sessionScope.user }
     </c:if>
     <hr/>
     <%
        List list = new ArrayList();
        list.add("书");
        session.setAttribute("cart",list);
     %>
     <c:if test="${empty sessionScope.cart}">
         对不起!您还未曾购物
     </c:if>
     <c:if test="${!empty sessionScope.cart}">
         您购买了如下东西
     </c:if>
     <hr/>
     <c:if test="${empty sessionScope.cart}" var="result" scope="page"></c:if>
     ${result }
     
  </body>
</html>
bubuko.com,布布扣

7.c:forEach

遍历:数组、List、Set、Map

属性:

         items:要遍历的目标对象。支持表达式

         var:变量名。指向当前遍历的集合中的一个元素

         begin:开始的索引(含)

         end:结束的索引(含)

         step:步长。默认是1

         varStatus:取一个名字,引用了一个对象。

                   该对象有以下方法:

                   int getIndex():当前记录的索引号。从0开始

                   int getCount():当前记录的顺序。从1开始

                   boolean isFirst():是否是第一条记录

                   boolean isLast():是否是最后一条记录

 

eg:

bubuko.com,布布扣
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="cn.lsl.domain.Person"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
  </head>
  
  <body>
      <%
        String str[] = {"a","b","c"};
        pageContext.setAttribute("str",str);
    %>
    <c:forEach items="${str}" var="s">
        ${s }<br/>
    </c:forEach>
    <hr/>
    <%
        List list = new ArrayList();
        list.add("aa");
        list.add("bb");
        list.add("cc");
        pageContext.setAttribute("list",list);
    %>
    <c:forEach items="${list}" var="s">
        ${s }<br/>
    </c:forEach>
    <hr/>
   
   <%
        Set set = new HashSet();
        set.add("aaa");
        set.add("bbb");
        set.add("ccc");
        pageContext.setAttribute("set",set);
    %>
    <c:forEach items="${set}" var="s">
        ${s }<br/>
    </c:forEach>
    <hr/>
    <%
        Map map = new LinkedHashMap();
        map.put("a","aaaa");
        map.put("b","bbbb");
        map.put("c","cccc");
        pageContext.setAttribute("map",map);
    %>
    <c:forEach items="${map}" var="me">
        ${me.key }==${me.value }<br/>
    </c:forEach>
    <hr/>
    <%
        String s1[] = {"a","b","c","d","e","f"};
        pageContext.setAttribute("s1",s1);
    %>
    <c:forEach items="${s1}" var="s" begin="1" end="4" step="2">
        ${s }<br/>
    </c:forEach>
    <hr/>
    <c:forEach items="${s1}" var="s"  step="2">
        ${s }<br/>
    </c:forEach>
    <hr/>
    <c:forEach begin="1" end="100" var="s">
        ${s }
    </c:forEach>
    <hr/>
    <%
    List<Person> ps = new ArrayList<Person>();
    ps.add(new Person("zs","1",true));
    ps.add(new Person("ls","1",false));
    ps.add(new Person("ww","0",false));
    ps.add(new Person("xl","0",false));
    ps.add(new Person("xq","1",true));
    ps.add(new Person("xb","1",false));
    ps.add(new Person("xj","1",false));
    pageContext.setAttribute("ps",ps);
    %>
    <c:forEach items="${ps}" var="p">
        ${p.name}:${p.gender=="1"?"男":"女"}:${p.married?"已婚":"未婚"}<br/>
    </c:forEach>
    <hr/>
    <table border="1" width="60%">
        <tr>
            <th>索引</th>
            <th>顺序</th>
            <th>第一个</th>
            <th>最后一个</th>
            <th>姓名</th>
            <th>性别</th>
            <th>婚姻</th>
        </tr>
        <c:forEach items="${ps}" var="p" varStatus="vs">
            <tr>
                <td>${vs.index }</td>
                <td>${vs.count }</td>
                <td>${vs.first }</td>
                <td>${vs.last }</td>
                <td>${p.name }</td>
                <td>${p.gender=="1"?"男":"女"}</td>
                <td>${p.married?"已婚":"未婚"}</td>
            </tr>
        </c:forEach>
    </table>
    <hr/>
    <table border="1" width="60%">
        <tr>
            <th>顺序</th>
            <th>姓名</th>
            <th>性别</th>
            <th>婚姻</th>
        </tr>
        <c:forEach items="${ps}" var="p" varStatus="vs">
            <tr bgcolor="${vs.index%2==0?‘#CFCFCF‘:‘#4D88AB‘ }">
                <td>${vs.count }</td>
                <td>${p.name }</td>
                <td>${p.gender=="1"?"男":"女"}</td>
                <td>${p.married?"已婚":"未婚"}</td>
            </tr>
        </c:forEach>
    </table>
    
  </body>
</html>
bubuko.com,布布扣

 

EL表达式,布布扣,bubuko.com

EL表达式

标签:style   blog   class   code   java   c   

原文地址:http://www.cnblogs.com/EvanLiu/p/3725736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!