表達式語言(Expression Language,EL),EL表達式是用」${}」括起來的腳本,用來更方便的讀取對象!php
爲何要使用EL表達式,咱們先來看一下沒有EL表達式是怎麼樣讀取對象數據的吧!css
在1.jsp中設置了Session屬性html
<%@ 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>
<%@ 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表達式的!java
在2.jsp中讀取Session設置的屬性web
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title></title> </head> <body> ${name} </body> </html>
${標識符}
<% //向ServletContext設置一個屬性 application.setAttribute("name", "aaa"); System.out.println("向application設置了一個屬性"); %>
<% ${name} %>
之前在JSP頁面獲取JavaBean的數據是這樣子的:數組
<jsp:useBean id="person" class="domain.Person" scope="session"/> <jsp:setProperty name="person" property="age" value="22"/>
<% Person person = (Person) session.getAttribute("person"); System.out.println(person.getAge()); %>
如今我使用了EL表達式讀取數據又會很是方便了瀏覽器
//等同於person.getAge() ${person.age}
集合操做在開發中被普遍地採用,在EL表達式中也很好地支持了集合的操做!能夠很是方便地讀取Collection和Map集合的內容ruby
爲了更好地看出EL表達式的強大之處,咱們也來對比一下使用EL表達式和不使用EL表達式的區別bash
下面不使用EL表達式輸出集合的元素markdown
<% 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); %>
<% 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); %>
${map.aa.username} <br> ${map.bb.username}
${map["1"].username} <br> ${map["2"].username}
<% List<Person> list = null; %> ${list==null?"list集合爲空":"list集合不爲空"}
EL表達式主要是來對內容的顯示,爲了顯示的方便,EL表達式提供了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>
注意事項:
${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,輸出空白字符串」「!這個特色可讓咱們數據回顯
<%--模擬數據回顯場景--%> <% 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程序代碼所能完成的功能
步驟:
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()); }
<?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>
<%@ 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)
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
fn方法庫全都是跟字符串有關的(能夠把它想成是String的方法)
測試代碼:
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>
<% 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':'' }>跳舞