JAVA EL技術&JSTL技術

EL(Express Lanuage)表達式能夠嵌入在jsp頁面內部,減小jsp腳本的編寫,EL 出現的目的是要替代jsp頁面中腳本的編寫。java

jsp腳本:<%=request.getAttribute(name)%>apache

EL表達式替代上面的腳本:${requestScope.name}數組

EL最主要的做用是得到四大域中的數據,格式${EL表達式}session

EL得到pageContext域中的值:${pageScope.key};app

EL得到request域中的值:${requestScope.key};jsp

EL得到session域中的值:${sessionScope.key};網站

EL得到application域中的值:${applicationScope.key};spa

EL從四個域中得到某個值${key};code

---一樣是依次從pageContext域,request域,session域,application域中 獲取屬性,在某個域中獲取後將不在向後尋找對象

 

<!-- 模擬域中的數據 -->
<% pageContext.setAttribute("name", "pageContxt"); //存儲字符串
    request.setAttribute("name", "request"); //存儲一個對象
    Users user=new Users(); user.setId(1); user.setUsername("lisi"); user.setPwd("123"); session.setAttribute("user", user); //存儲一個集合
    List<Users> list=new ArrayList<Users>(); Users user1=new Users(); user1.setId(1); user1.setUsername("wangwu"); user1.setPwd("123"); list.add(user1); Users user2=new Users(); user2.setId(1); user2.setUsername("zhaoliu"); user2.setPwd("123"); list.add(user2); application.setAttribute("List", list); %>
<hr>
<!-- 使用腳本取出域中的值 -->
<%=request.getAttribute("name") %>
<%Users u=(Users)session.getAttribute("user"); out.write(u.getUsername()); %>
<hr>
<!-- 使用EL表達式取出域中的值 --> ${requestScope.name} ${sessionScope.user.username} ${applicationScope.List[0].pwd} <hr>
<!-- 使用el表達式 全域查找(會從最小的找,底層就是findAttribute()) --> ${name } ${user.username} ${List[0].pwd}

EL的執行表達式

${1+1}

${empty user} 判斷域中的對象是否爲空。

${user==null?true:false}

 

JSTL(JSP Standard Tag Library),JSP標準標籤庫,能夠嵌入在jsp頁面中使用標籤的形式完成業務邏輯等功能。jstl出現的目的同el同樣也是要代替jsp頁面中的腳本代碼。JSTL標準標準標籤庫有5個子庫,但隨着發展,目前常使用的是他的核心庫。

Core

http://java.sun.com/jsp/jstl/core

c

 

JSTL下載:

從Apache的網站下載JSTL的JAR包。進入          「http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/」網址下載    JSTL的安裝包。

 

1.JSTL核心庫的經常使用標籤

1)<c:if test=」」>標籤

其中test是返回boolean的條件

<%request.setAttribute("count", 10); %>
<!--jstl標籤常常會和el配合使用  -->
<!-- test表明的返回boolean的表達式 -->
<c:if test="${count==10 }"> xxxx </c:if>

 

<!-- 用戶沒有登錄 -->
<c:if test="${empty user }">
    <a href="login.jsp">登錄</a>
    <a href="register.jsp">註冊</a>
</c:if>
<!-- 用戶已經登錄 -->
<c:if test="${!empty user }">
    <span>${user.name }</span>
    <a href="#">退出</a>
</c:if>
<%
    //模擬用戶已經登陸成功
    User user=new User(); user.setId(100); user.setName("張三"); user.setPwd("123"); session.setAttribute("user", user); %>

2)<c:forEach>標籤

使用方式有兩種組合形式

<!-- 模擬加強for  productList---List<Product>
    for(Product product:productList){ System.out.print(product.getName()); } -->
<!-- items:一個集合或數組(從域中選)   var:表明集合中的某一個元素 -->
<c:forEach items="${productList }" var="pro"> ${pro.name } </c:forEach>
相關文章
相關標籤/搜索