JSP程序設計(第二天)

會話跟蹤技術

http是一個無狀態的協議,服務器不會自動保存每次請求的狀態信息

實現技術:

  • session
  • 隱藏域
  • 重寫URL
  • cookie

session

會話,基於cookie實現,最大非活動間隔時間:1800s=30分鐘。

	<p>
		SessionID:<%=session.getId()%></p>
	<p>
		最大非活動間隔時間(兩次活動的間隔時間):<%=session.getMaxInactiveInterval()%></p>
	<p>
		是否新會話:<%=session.isNew()%></p>
	<p>
		上次訪問時間:<%=session.getLastAccessedTime()%></p>

四大作用域對象

**pageContext:**當前頁面有效

request:

request範圍大於pageContext,
1.動態包含頁面時,request可以取到被動作包含頁面中請求中的值,
2.轉發,轉發頁面的數據在轉發後頁面中可以取到的。
上面兩種情況,pageContext不可以。

session:

一次會話,一個瀏覽器窗口的交互。(不同的瀏覽器對應一個不同的session對象,但如果同一個瀏覽器開啓的不同窗口,也終將是一個session對象。)

application:

範圍:整個應用服務器(Tomcat容器),共享一個對象。

網站計數器

<body>

	<%
		Integer count = (Integer)application.getAttribute("count");
		if(count==null){ //第一個訪問的
            //方法1:config配置
            String sumcount = config.getInitParameter("sumcount");
			count = Integer.parseInt(sumcount);
            //方法2:直接設置局部變量
	//		count = 0;
		}
		count++;
		application.setAttribute("count", count);
		
		Integer sum = (Integer)session.getAttribute("sum");
		if(sum==null){ //第一個訪問的
			sum = 0;
		}
		sum++;
		session.setAttribute("sum", sum);
		 
	%>
	<p>
		您是第 <%=session.getAttribute("sum") %>次訪問
	</p>
	<p>
		您是本站的第  <%=application.getAttribute("count") %> 次訪問用戶
	</p>
</body>
</html>

cookie和session的區別

1.cookie的數據存放在客戶端,而session的數據存放在服務器端

2.cookie存儲在瀏覽器端的一段文本,而session在服務器,存儲的是對象

3.session實現,基於cookie.

重寫URL

重寫URL的作用是🗾即使瀏覽器關閉了

<!-- 重寫URL -->
	<a href="session.jsp">URL普通鏈接</a>
	<br>
	<a href="<%=response.encodeUrl("session.jsp")%>">測試URL重寫2</a>

session失效情況

方式1:

<%
		//銷燬:第一種方式
		session.invalidate();//銷燬session
		
	%>

方式2:

		//session的最大非活動間隔時間
        <p>
		非活動間隔時間:<%=session.getMaxInactiveInterval()%></p>

方式3:

關閉瀏覽器,本質是超時(使用session監聽器來整理)

EL表達式

EL Express LANGUAGE 表達式語言。

作用域對象 pageContext request session application
作用域範圍 page request session application
對應的EL表達式 pageScope requestScope sessionScope applicationScope

作用域對象
pageContext request session application

對應的EL表達式:
pageScope requestScope sessionScope applicationScope

1.算術運算符

\${"2"+"2" }:${"2"+"2" }		//4
\${'2'+'2' }:${'2'+'2' }		//4

2.關係表達式

<!-- 2關係表達式 -->
    \${3>2}:${3>2}
<br>
    \${3<2}:${3<2}
<br>
    \${3==2}:${3==2}
<br>
    \${3>=2}:${3>=2}
<br>
    \${3<=2}:${3<=2}
<br>
    \${3!=2}:${3!=2}
<br>
    \${3 gt 2}:${3 gt 2}
<br>
    \${3 lt 2}:${3 lt 2}
<br>
    \${3 eq 2}:${3 eq 2}
<br>
    \${3 ge 2}:${3 ge 2}
<br>
    \${3 le 2}:${3 le 2}

3.邏輯運算符

\${false && true }:${false && true }<br>
\${false || true }:${false || true }<br>
\${!false }:${!false }<br>
\${not false }:${not false }<br>
\${true or false }:${true or false }<br>
\${true and false }:${true and false }<br>

4.El表達式的兩種寫法

<%
		User user = new User();
		user.setName("zhang");
		user.setPassword("123");

		request.setAttribute("user", user);
%>
    <!-- 寫法一
    El表達式等價於:((User)pageContext.findAttribute("user")).getName();
	其中的user.name等價於user.getName();
    -->
    <p>El用戶名1:${requestScope.user.name }</p>
        
        
    <!-- 寫法二:還支持中括號 
     -->
     <p>El用戶名2:${requestScope["user"].name }</p>
	<p>El用戶名3:${requestScope["user"]["name"] }</p>

兩種寫法的區別:

如果保存的屬性名出現了特殊符號:如:name-X,name.x等
requestScope.user.name-X是會拋異常的。
requestScope[“user”][“name”][“X”]可以使用。

比如:

<%
		request.setAttribute("u.x", "王五");
%>
	<hr>
    <!-- 等價於:((U)request.getAttribute("u")).getX(); -->
	\${requestScope.u.x }==${requestScope.u.x } <br>
	\${requestScope["u"]["x"]}==${requestScope["u"]["x"]}<br> 
	\${requestScope["u.x"]}==${requestScope["u.x"]}<br>

字符串數組的語法

<%
		String[] str = {"AAA","BBB","CCC"};
		request.setAttribute("str", str);
%>
    \${str[2] }==${str[2] }<br>

集合的常見語法

<%
Map<String,Object> map = new HashMap<>();
		map.put("age",23);
		request.setAttribute("map", map);
		Set<String> set = new HashSet<>();
		set.add("正值");
		set.add("負值");
		request.setAttribute("set", set);
%>
    <hr>
	\${str[2] }==${str[2] }<br>
	\${map.age }==${map.age }<br>
	\${requestScope["map"]["age"] }==${requestScope["map"]["age"]  }<br>
	\${requestScope.set }==${requestScope.set }

JSTL標籤

使用該標籤前,得先引入jar包,然後導入響應的庫,比如 核心庫,函數庫,格式化數字和日期庫等

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fun" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="a" uri="http://java.sun.com/jsp/jstl/core"%>

注意:jstl標籤默認 沒有指定scope時,默認放入pageContext。

<a:set var="content" value="'<a>xxx</a>'"></a:set>
<a:out value="${content}" escapeXml="true"></a:out>
===== ${content }

jstl標籤和EL表達式區別

  1. 提供默認值
  2. 處理特殊標記
<a:set var="age" scope="page" value="33"></a:set>
<!-- 1.提供默認值  2.處理特殊標記 -->
<a:out value="${requestScope.age}" default="18"></a:out>
::: ${pageScope.age}



<a:set var="content" value="'<a>xxx</a>'"></a:set>
<a:out value="${content}" escapeXml="true"></a:out>
===== ${content }

if判斷

<a:set var="score" value="${param.score }"></a:set>
	<a:if test="${score>=60 }">
		很棒喲
	</a:if>
	<a:if test="${score<60 }">
		繼續加油啦
	</a:if>

switch選擇

<a:choose>
		<a:when test="${score>=85 }">優秀</a:when>
		<a:when test="${score>=70 }">良好</a:when>
		<a:when test="${score>=60 }">一般</a:when>
		<a:otherwise>
			較差
		</a:otherwise>
</a:choose>

forEach增強for

<%
		String[] names = {"張三","李四","王五"};
		request.setAttribute("names", names);
%>
	<a:forEach var="v" items="${names }" >
		<div>${v }</div>
	</a:forEach>

forTokens

<!-- delims=","指定分隔符 -->
<a:forTokens var="word"  items="AAAA,BBBB,CCCC,DDDD" delims=",">
		<p>${word }</p>
</a:forTokens>

類對象屬性

<!--等價於: request.setAttribute("user" entity.User()); -->
<jsp:useBean id="user" class="entity.User" scope="request"></jsp:useBean>
	
<!-- 
	等價於:((User)request.getAttribute("user")).setName(""張三);
	target:取值是作用域中的對象(map或實體類),property:表示屬性名
--> 
<a:set target="${requestScope.user }" property="name" value="張三"></a:set>
${user.name }

重寫URL

<!-- 相當於重寫URL,類似於Cookie裏重寫URL的方法,也會獲取sessionID:<a href="<%=response.encodeUrl("add.jsp")%>"> -->
<a:url context="/jsp3" var="address" scope="request" value="/add.jsp" ></a:url>

引入

<a:import url="add.jsp"></a:import>

格式化日期數字庫

金額:<fmt:formatNumber value="12345.00066" pattern=",###.00"></fmt:formatNumber><br>
金額:<fmt:formatNumber value="12345.00066" pattern=",###.##"></fmt:formatNumber><br>
<%
	request.setAttribute("mydate", new Date());
	%>
<hr>
日期:<fmt:formatDate value="${mydate }" pattern="yyyy年MM月dd日" />
    
<!-- 設置區域 -->
美國區域:<fmt:setLocale value="en_us"/><br>
<%-- 中國區域:<fmt:setLocale value="zh_cn"/><br> --%>
數值:<fmt:formatNumber value="0.6" type="number"></fmt:formatNumber><br>
金額:<fmt:formatNumber value="0.6" type="currency"></fmt:formatNumber><br>
百分比:<fmt:formatNumber value="0.6" type="percent"></fmt:formatNumber><br>

函數庫

函數名   					函數說明   					使用舉例 
fn:contains 判斷字符串是否包含另外一個字符串 <c:if test="${fn:contains(name, searchString)}"> 
fn:containsIgnoreCase 判斷字符串是否包含另外一個字符串(大小寫無關) <c:if test="${fn:containsIgnoreCase(name, searchString)}"> 
fn:endsWith 判斷字符串是否以另外字符串結束 <c:if test="${fn:endsWith(filename, ".txt")}"> 
fn:escapeXml 把一些字符轉成XML表示,例如<字符應該轉爲< ${fn:escapeXml(param:info)} 
fn:indexOf 子字符串在母字符串中出現的位置 ${fn:indexOf(name, "-")} 
fn:join 將數組中的數據聯合成一個新字符串,並使用指定字符格開 ${fn:join(array, ";")} 
fn:length 獲取字符串的長度,或者數組的大小 ${fn:length(shoppingCart.products)} 
fn:replace 替換字符串中指定的字符 ${fn:replace(text, "-", "•")} 
fn:split 把字符串按照指定字符切分 ${fn:split(customerNames, ";")} 
fn:startsWith 判斷字符串是否以某個子串開始 <c:if test="${fn:startsWith(product.id, "100-")}"> 
fn:substring 獲取子串 ${fn:substring(zip, 6, -1)} 
fn:substringAfter 獲取從某個字符所在位置開始的子串${fn:substringAfter(zip, "-")} 
fn:substringBefore 獲取從開始到某個字符所在位置的子串 ${fn:substringBefore(zip, "-")} 
fn:toLowerCase 轉爲小寫 ${fn.toLowerCase(product.name)} 
fn:toUpperCase 轉爲大寫字符 ${fn.UpperCase(product.name)} 
fn:trim 去除字符串前後的空格 ${fn.trim(name)} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章