表達式語言(ExPRession Language,EL),EL表達式是用”${}”括起來的腳本,用來更方便的讀取對象!
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>在2.jsp中獲取Session設置的屬性 <%@ 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>效果:上面看起來,也沒有多復雜呀,那我們試試EL表達式的!
在2.jsp中讀取Session設置的屬性
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title></title> </head> <body> ${name} </body> </html>只用了簡簡單單的幾個字母就能輸出Session設置的屬性了!并且輸出在瀏覽器上!以前在JSP頁面獲取JavaBean的數據是這樣子的:
1.jsp頁面Session存進一個Person對象,設置age的屬性為22 <jsp:useBean id="person" 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()); %>效果如下現在我使用了EL表達式讀取數據又會非常方便了
//等同于person.getAge() ${person.age}集合操作在開發中被廣泛地采用,在EL表達式中也很好地支持了集合的操作!可以非常方便地讀取Collection和Map集合的內容
為了更好地看出EL表達式的強大之處,我們也來對比一下使用EL表達式和不使用EL表達式的區別
下面不使用EL表達式輸出集合的元素
在1.jsp頁面中設置session的屬性,session屬性的值是List集合,List集合裝載的又是Person對象 <% 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); %>在2.jsp中獲取到session的屬性,并輸出到頁面上 <% 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}同樣也可以有相同的效果:
我們再來使用一下Map集合
在1.jsp中session屬性存儲了Map集合,Map集合的關鍵字是字符串,值是Person對象
<% 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); %>看起來好像取出數據的時候是會有點復雜,但是有了EL表達式也是非常輕松的! ${map.aa.username} <br> ${map.bb.username}效果:EL表達式主要是來對內容的顯示,為了顯示的方便,EL表達式提供了11個內置對象。
pageContext 對應于JSP頁面中的pageContext對象(注意:取的是pageContext對象)pageScope 代表page域中用于保存屬性的Map對象requestScope 代表request域中用于保存屬性的Map對象sessionScope 代表session域中用于保存屬性的Map對象applicationScope 代表application域中用于保存屬性的Map對象param 表示一個保存了所有請求參數的Map對象paramValues表示一個保存了所有請求參數的Map對象,它對于某個請求參數,返回的是一個string[]header 表示一個保存了所有http請求頭字段的Map對象headerValues同上,返回string[]數組。cookie 表示一個保存了所有cookie的Map對象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內置對象一般都是別的頁面帶數據過來的(表單、地址欄)!
表單頁面
<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>處理表單頁面: ${param.username} <br> ${param.age} <br> //沒有學習jstl之前就一個一個寫吧。 ${paramValues.hobbies[0]} <br> ${paramValues.hobbies[1]} <br> ${paramValues.hobbies[2]} <br>效果:EL表達式最大的特點就是:如果獲取到的數據為null,輸出空白字符串”“!這個特點可以讓我們數據回顯
在1.jsp中模擬場景 <%--模擬數據回顯場景--%> <% 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':'' }>女效果:EL自定義函數用于擴展EL表達式的功能,可以讓EL表達式完成普通Java程序代碼所能完成的功能
開發HTML轉義的EL函數我們有時候想在JSP頁面中輸出JSP代碼,但是JSP引擎會自動把HTML代碼解析,輸出給瀏覽器。此時我們就要對HTML代碼轉義。步驟:
編寫一個包含靜態方法的類(EL表達式只能調用靜態方法),該方法很常用,Tomcat都有此方法,可在/webapps/examples/WEB-INF/classes/util中找到 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("<"); break; case '>': result.append(">"); break; case '&': result.append("&"); break; case '"': result.append("""); 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>/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>在JSP頁面中導入和使用自定義函數,EL自定義的函數一般前綴為”fn”,uri是”/WEB-INF/tld文件名稱” <%@ 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>效果:既然作為JSTL標簽庫中的一個庫,要使用fn方法庫就需要導入JSTL標簽!要想使用JSTL標簽庫就要導入jstl.jar和standard.jar包!
所以,要對fn方法庫做測試,首先導入開發包(jstl.jar、standard.jar)
fn方法庫全都是跟字符串有關的(可以把它想成是String的方法)
fn:toLowerCasefn:toUpperCase fn:trim fn:lengthfn:split fn:join 【接收字符數組,拼接字符串】fn:indexOffn:containsfn:startsWithfn:replacefn:substringfn:substringAfterfn:endsWithfn:escapeXml【忽略XML標記字符】fn:substringBefore測試代碼:
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>效果:
|
新聞熱點
疑難解答