JSTL使用運算式來簡化頁面的代碼,這對一些標準的方法,例如bean的getter/setter方法,請求參數或者context以及session中的資料的訪問非常方便,但是我們在實際應用中經常需要在頁面調用對象的某些方法,例如我需要調用字串的length方法來擷取字串的長度時,在以往的開發過程中我們必須把對象先轉為String類,然後在調用其length方法,這樣的代碼繁瑣而且容易出錯。
因此JSTL內建了幾個用於字串操作的方法,可以直接在運算式中使用,大大的簡化了代碼,提供代碼的可讀性。在JSTL的表達是中要使用一個函數,其格式如下
${ns:methodName(args....)}
在使用這些函數之前必須在JSP中引入標準函數的聲明
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
下面是JSTL中內建的方法列表以及其描述
| 函數名 |
函數說明 |
使用舉例 |
| contains |
判斷字串是否包含另外一個字串 |
<c:if test="${fn:contains(name, searchString)}"> |
| containsIgnoreCase |
判斷字串是否包含另外一個字串(大小寫無關) |
<c:if test="${fn:containsIgnoreCase(name, searchString)}"> |
| endsWith |
判斷字串是否以另外字串結束 |
<c:if test="${fn:endsWith(filename, ".txt")}"> |
| escapeXml |
把一些字元轉成XML表示,例如<字元應該轉為< |
${fn:escapeXml(param:info)} |
| indexOf |
子字串在母字串中出現的位置 |
${fn:indexOf(name, "-")} |
| join |
將數組中的資料聯合成一個新字串,並使用指定字元格開 |
${fn:join(array, ";")} |
| length |
擷取字串的長度,或者數組的大小 |
${fn:length(shoppingCart.products)} |
| replace |
替換字串中指定的字元 |
${fn:replace(text, "-", "")} |
| split |
把字串按照指定字元切分 |
${fn:split(customerNames, ";")} |
| startsWith |
判斷字串是否以某個子串開始 |
<c:if test="${fn:startsWith(product.id, "100-")}"> |
| substring |
擷取子串 |
${fn:substring(zip, 6, -1)} |
| substringAfter |
擷取從某個字元所在位置開始的子串 |
${fn:substringAfter(zip, "-")} |
| substringBefore |
擷取從開始到某個字元所在位置的子串 |
${fn:substringBefore(zip, "-")} |
| toLowerCase |
轉為小寫 |
${fn.toLowerCase(product.name)} |
| toUpperCase |
轉為大寫字元 |
${fn.UpperCase(product.name)} |
| trim |
去除字串前後的空格 |
${fn.trim(name)} |