EL表達式+jstl核心庫+測試JSTL格式庫+自定義 JSTL 函數標籤庫

EL表達式:

1、 普通字符串
<%=request.getAttribute(“hello”)%>
結果:直接輸出hello world

2、 採用“ . ”進行導航,也稱存取器
姓名:$ {user.username }
年齡:$ {user.age }
所屬組:${user.group.name }
結果:輸出屬性名對應的屬性值(EL表達式特性)

3、 輸出map
${mapvalue.key1 }
結果:從map中拿到key爲key1的屬性值

4、 輸出數組
${str[1] }
結果:取出屬性名爲str,數組下標爲1的數組元素

5、 輸出對象數組,採用[]和下標
${usersArray[2].username }
結果:輸出數組中第二個元素的username屬性值

6、 輸出list,採用[]和下標
${userlist[4].username }
結果:輸出集合中第四個username的屬性值

7、 el表達式對運算符的支持
${1+2 }
${10/0 }<! – 發現異常,轉換成實型運算 -->
${10 div 5 }
${10 % 3 }
${10 mod 3 }
${abcd+ 3 }
結果:輸出結果與正常四則運算無異,而且EL表達式會自動處理異常

8、 測試empty
${empty value1 }
${empty value2 }
${empty value3 }
${empty value4 }
${!empty value4 }
結果:從scop中取出屬性名爲value1的值,如果爲空輸出true。不爲空,則爲false

測試類:

public class JstlElAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 普通字符串
		request.setAttribute("hello", "hello world");

		// 結構
		Group group = new Group();
		group.setName("zte");

		User user = new User();
		user.setUsername("張三");
		user.setAge(18);
		user.setGroup(group);

		request.setAttribute("user", user);

		// map
		Map mapValue = new HashMap();
		mapValue.put("key1", "value1");
		mapValue.put("key2", "value2");

		request.setAttribute("mapvalue", mapValue);

		// 字符串數組
		String[] strArray = null;

		strArray = new String[] { "a", "b", "c" };
		request.setAttribute("str", strArray);

		User[] users = new User[10];
		for (int i = 0; i < 10; i++) {
			User u = new User();
			u.setUsername("U_" + i);
			users[i] = u;
		}
		request.setAttribute("usersArray", users);

		List userList = new ArrayList();
		for (int i = 0; i < 10; i++) {
			User uu = new User();
			uu.setUsername("UU_" + i);
			userList.add(uu);
		}
		request.setAttribute("userlist", userList);

		// empty
		request.setAttribute("abcd", 6);
		request.setAttribute("value1", null);
		request.setAttribute("value2", "");
		request.setAttribute("value3", new ArrayList());
		request.setAttribute("value4", "123456");
		return mapping.findForward("success");
	}
}

**

• JSTL_ 標籤庫

**
一、 配置
將jstl.jar和standard.jar拷貝到WEB-INF/lib下
二、 導入
在jsp頁面中採用taglib指令引入標籤
例:
庫核心標籤庫指令引入: <%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core”%>
格式化標籤庫指令引入: <%@ taglib prefix=“fmt” uri=“http://java.sun.com/jsp/jstl/fmt”%>

**

測試jstl核心庫(見代碼註釋)

**
1、 直接輸出(測試c:out)

	hello(default):<c:out value="hello"/><br><!-- 直接輸出hello -->
	hello(default):<c:out value="${hello}"/><br><!-- jstl標籤一定要接EL表達式 -->
	hello(el表達式):${hello }<br>	
    hello(default="123"):<c:out value="${abcd}" default="123" /><br><!-- 如果沒有找到abcd的值,用默認值替代 -->
	hello(default="123"):<c:out value="${abcd}">123</c:out><br><!-- 輸出了123 -->
	bj(defalut):<c:out value="${bj}"/><br><!-- 不解析html標籤 -->
	bj(escapeXml="true"):<c:out value="${bj}" escapeXml="true"/><br><!-- 控制瀏覽器解析 -->
	bj(escapeXml="false"):<c:out value="${bj}" escapeXml="false"/><br><!-- 控制瀏覽器不解析 -->
	bj(el表達式):${bj }<br><!-- EL表達式會解析html標籤 -->

2、 改變內置對象屬性值(測試c:set和c:remove)

<c:set value="123" var="temp"/><!-- 直接往內置對象設值(這裏默認page,可以換成scop=request) -->
	temp:${temp }<br>
	<c:remove var="temp"/><!-- 從內置對象中移除屬性名爲temp的值 -->
	temp:${temp }<br>

3、 條件判斷標籤(測試條件控制標籤c:if)

 <c:if test="$ {v1 lt v2}" var="v"><! -- 從scop中取出v1,v2。比較V1<V2。(這裏爲true)-->
		v1小於v2<br>v=$ {v }<br>
	</c:if>
	<c:if test="$ {empty v3}"var="v"><! -- 判斷屬性名爲V3的值是否爲空 -->
		v3爲空<br>v=$ {v }<br>
	</c:if>
	<c:if test="$ {empty v4}">
		v4爲空<br>
	</c:if>
	<c:if test="$ {empty v5}">
		v5爲空<br>
	</c:if>

(將結果賦給var,結果爲真則執行其後語句,否則不執行)

4、 條件控制標籤(測試條件控制標籤c:choose,c:when,c:otherwise)

<c:choose>
		<c:when test="${v1 lt v2}"><!-- 如果V1<v2 -->
			v1小於v2<br>
		</c:when>
		<c:otherwise>
			v1大於v2<br>
		</c:otherwise>
	</c:choose>
	<c:choose>
		<c:when test="${empty v4}">
			v4爲空<br>
		</c:when>
		<c:otherwise>
			v4不爲空<br>
		</c:otherwise>
	</c:choose>

注意:c:when,c:otherwise必須定義在choose中。
結果:根據結果選擇輸出when語句或者otherwise語句

5、循環控制標籤c:forEach

<table border="1">
		<tr>
			<td>姓名</td>
			<td>年齡</td>
			<td>所屬組</td>
		</tr>
		<c:choose>
			<c:when test="${empty userlist}">
				<tr>
					<td colspan="3">沒有符合條件的數據!</td>
				</tr>
			</c:when>
			<c:otherwise>
				<c:forEach items="${userlist}" var="u">
					<tr>
						<td>${u.username }</td>
						<td>${u.age }</td>
						<td>${u.group.name }</td>
					</tr>
				</c:forEach>
			</c:otherwise>
		</c:choose>
	</table>	

注:這裏先判斷集合是否爲空,不爲空則用標籤遍歷所有屬性到var對象“u”,之後用EL表達式輸出“u”中屬性名對應屬性。

6、 循環控制標籤c:forEach,varstatus

<table border="1">
		<tr>
			<td>姓名</td>
			<td>年齡</td>
			<td>所屬組</td>
		</tr>
		<c:choose>
			<c:when test="${empty userlist}">
				<tr>
					<td colspan="3">沒有符合條件的數據!</td>
			</tr>
			</c:when>
			<c:otherwise>
				<c:forEach items="${userlist}" var="user" varStatus="vs">
					<c:choose>
						<c:when test="${vs.count % 2 == 0}">
							<tr bgcolor="red">
						</c:when>
						<c:otherwise>
							<tr>
						</c:otherwise>
		            </c:choose>
								<td>
									<c:out value="${user.username}"/>
								</td>
								<td>
									<c:out value="${user.age}"/>
								</td>
								<td>
									<c:out value="${user.group.name}"/>
								</td>
   </tr>		   
			</c:forEach>
			</c:otherwise>
		</c:choose>
	</table>

Varstatus:可以對特定的值進行輸出控制,例子表明偶數用紅色顯示

7、 循環控制標籤c:forEach,begin,end,step

<table border="1">
		<tr>
			<td>姓名</td>
			<td>年齡</td>
			<td>所屬組</td>
		</tr>
		<c:choose>
			<c:when test="${empty userlist}">
				<tr>
					<td colspan="3">沒有符合條件的數據!</td>
				</tr>
			</c:when>
			<c:otherwise>
				<c:forEach items="${userlist}" var="user" begin="2" end="8" step="2">
					<tr>
						<td>${user.username}</td>
						<td>${user.age}</td>
						<td>${user.group.name }</td>
					</tr>
				</c:forEach>
			</c:otherwise>
		</c:choose>
	</table>	

注:設定循環的起點begin,終點end,以及每次循環的間隔step(不設定默認爲1)

8、循環控制標籤c:forEach

<c:forEach begin="1" end="10">
		  ${hello} <br>
	</c:forEach>

結果:輸出10個值

9、 循環控制標籤c:forEach,輸出map

     <c:forEach  items="$ {mapvalue}" var="v">
    		$ {v.key }=$ {v.value }<br>
    	</c:forEach>

注:將map對象賦給var,拿到map集合的entry,輸出指定key的value

測試JSTL格式庫

1、測試日期的格式化

	${today}<br><!-- 輸出日期 -->
	today(default):<fmt:formatDate value="${today}"/><br>
	today(type="date"):<fmt:formatDate value="${today}" type="date"/><br>
	today(type="time"):<fmt:formatDate value="${today}" type="time"/><br>
	today(type="both"):<fmt:formatDate value="${today}" type="both"/><br>
	today(dateStyle="short"):<fmt:formatDate value="${today}" dateStyle="short"/><br>
	today(dateStyle="medium"):<fmt:formatDate value="${today}" dateStyle="medium"/><br>
	today(dateStyle="long"):<fmt:formatDate value="${today}" dateStyle="long"/><br>
	today(dateStyle="full"):<fmt:formatDate value="${today}" dateStyle="full"/><br>
	today(pattern="yyyy/MM/dd HH:mm:ss"):<fmt:formatDate value="${today}" pattern="yyyy/MM/dd HH:mm:ss"/><br><!-- 直接定義格式 -->
	today(pattern="yyyy/MM/dd HH:mm:ss"):<fmt:formatDate value="${today}" pattern="yyyy/MM/dd HH:mm:ss" var="d"/><br>
	.......${d }<br格式化value的值必><!-- 加了var則輸出var才輸出值 -->

2、測試數字的格式化

	${n}<br><!-- 123456.123 -->
	n(default):<fmt:formatNumber value="${n}"/><br><!-- 默認分位 -->
	n(pattern="###,###.##"):<fmt:formatNumber value="${n}" pattern="###,###.##"/><br><!-- 定義格式 -->
	n(pattern="###,###.0000"):<fmt:formatNumber value="${n}" pattern="###,###.0000"/><br><!-- 小鼠不足部分用0補齊 -->
	n(groupingUsed="false"):<fmt:formatNumber value="${n}" groupingUsed="false"/><br> <!-- 默認不分位 -->
	n(minIntegerDigits="10"):<fmt:formatNumber value="${n}" minIntegerDigits="10"/><br><!-- 最小整數爲10位 -->
	n(type="currency"):<fmt:formatNumber value="${n}" type="currency"/><br><!-- 以美元開頭輸出 -->
	n(type="currency"):<fmt:formatNumber value="${n}" type="currency" currencySymbol="¥"/><br><!-- 以人民幣符號開頭輸出 -->
	n(type="percent"):<fmt:formatNumber value="${p}" type="percent"/><br><!-- 以百分號輸出,默認輸出 -->
	n(type="percent"):<fmt:formatNumber value="${p}" type="percent" maxFractionDigits="2" minFractionDigits="2"/><br>

自定義 JSTL 函數標籤庫

第一步:自定義一個public類和static方法

public class MyFunctions {
	/**
	 * 方法必須是public static
	 * @param name
	 * @return
	 */
	public static String sayHello(String name) {
		return "Hello " + name;
	}
}

第二步:寫一個標籤庫描述符(tld)文件,在 tld 文件中把標籤處理器描述成一個標籤 ;

<?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">
    
  <description>my functions library</description>
  <display-name>my functions</display-name>
  <tlib-version>1.0</tlib-version>
  <short-name>my</short-name><!-- 隨便寫 -->
  <uri>http://www.zte.com/functions</uri><!-- 你的方法所在,通過它找tld -->
  
  <function>
    <name>say</name><!-- 標籤名 -->
    <function-class>com.bjsxt.struts.MyFunctions</function-class><!-- 調用該方法的類(包名+類名) -->
    <function-signature>java.lang.String sayHello(java.lang.String)</function-signature><!-- 真正的函數名 -->
  </function>
  
</taglib>

第三步:編寫一個JSP實現Tag接口

<?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">
    
  <description>my functions library</description>
  <display-name>my functions</display-name>
  <tlib-version>1.0</tlib-version>
  <short-name>my</short-name><!-- 隨便寫 -->
  <uri>http://www.zte.com/functions</uri><!-- 你的方法所在,通過它找tld -->
  
  <function>
    <name>say</name><!-- 標籤名 -->
    <function-class>com.bjsxt.struts.MyFunctions</function-class><!-- 調用該方法的類(包名+類名) -->
    <function-signature>java.lang.String sayHello(java.lang.String)</function-signature><!-- 真正的函數名 -->
  </function>
  
</taglib>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章