JSP入門

說明:JSP很久就學過,但學了忘忘了學,很難受。因此這篇文章純粹是爲了記錄一些學習筆記,以便後面複習,如有記錄有誤的地方,忘指出!

 

一、什麼是JSP

 JSP即java server pages,它是JavaWeb的動態資源。JSP = html + java腳本 + jsp動作標籤(包含EL表達式)

1、JSP中java腳本

 * <% ... %>:代碼段,Java語句
 * <%= ... %>:表達式,只是表達式!表達式的值會被輸出到客戶端(現在很少有,常用EL表達式來代替)
 * <%! ... %>:定義,定義成員!例如例如成員變量,方法等(很少有,常用JSTL標籤庫的set標籤)

2、JSP真身

 * JSP也是Servlet
 * JSP會在第一次被請求時編碼成.java,再編碼成.class文件,它其實就是一個Servlet,在處理請求時執行service()方法。

  查看真身可以得到,jsp中有9個對象可以無需創建即可使用,它們就是jsp九大內置對象。

3、九大內置對象

補充:

JavaWeb三大組件:servlet、filter、listener

JSP四大作用域:page(pageContext)、request(HttpServletRequest)、session(HttpSession)、application(ServletContext)

Servlet三大作用域:request、session、application          ↵

無需在jsp中聲明即可使用的9個對象
* out(JspWriter):等同與response.getWriter(),用來向客戶端發送文本數據;
* config(ServletConfig):對應“真身”中的ServletConfig;
* page(當前JSP的真身類型):當前JSP頁面的“this”,即當前對象,引用爲Object類型;
* pageContext(PageContext):頁面上下文對象,它是最後一個沒講的域對象;
* exception(Throwable):只有在錯誤頁面中可以使用這個對象;
* request(HttpServletRequest):即HttpServletRequest類的對象;
* response(HttpServletResponse):即HttpServletResponse類的對象;
* application(ServletContext):即ServletContext類的對象;
* session(HttpSession):即HttpSession類的對象,不是每個JSP頁面中都可以使用,如果在某個JSP頁面中設置<%@page   session=”false”%>,說明這個頁面不能使用session。

補充:

pageContext對象是PageContext類型
 * 域對象:只在當前jsp頁面中有效的域,通常用來讓jsp與當前jsp中標籤之間共享數據
 * 獲取其他8個內置對象:可以獲取其他8個內置對象(調用get方法)
 * 代理其他域對象:可以用pageContext來操作其他3個域

4、JSP的三大指令(重要)

  * page指令
  * include指令
  * taglib指令

1. page指令

常用屬性:

* import:等同與import語句
  --> <%@ page import="java.util.*" %>
  --> <%@ page import="java.util.*, java.net.*" %>
  --> 在一個JSP頁面中可以給出多個page指令,而且import是可以重複出現的
   <%@ page import="java.util.*" %>
   <%@ page import="java.next.*" %>

* pageEncoding:指定當前頁面的編碼
  --> 如果pageEncoding沒有指定,那麼默認爲contentType的值;
  --> 如果pageEncoding和contentType都沒有指定,那麼默認值爲iso-8859-1
  
* contentType:等同與調用response.setContentType("text/html;charset=xxx");
  --> 如果沒有指定contentType屬性,那麼默認爲pageEncoding的值;
  --> 如果contentType和pageEncoding都沒有指定,那麼默認值爲iso-8859-1


* errorPage:如果當前頁面出現異常,那麼跳轉到errorPage指定的jsp頁面。例如:<%@ page errorPage="a.jsp" %>
* isErrorPage:上面示例中指定a.jsp爲錯誤頁面,但在a.jsp中不能使用內置對象exception,保有a.jsp中使用<%@page             isErrorPage="true"%>時,才能在a.jsp中使用錯誤頁面。
* autoFlush:當autoFlush爲true時,表示out流緩衝區滿時會自動刷新。默認爲true
* buffer:指定out流的緩衝區大小,默認爲8KB
* isELIgnored:當前JSP頁面是否忽略EL表達式,默認爲false,表示不忽略,即支持EL表達式

不常用的屬性:

* language:當前JSP編譯後的語言!默認爲java,當前也只能選擇java
* info:當前JSP的說明信息
* isThreadSafe:當前JSP是否執行只能單線程訪問,默認爲false,表示支持併發訪問
* session:當前頁面是否可以使用session,默認爲false,表示支持session的使用。
* extends:指定JSP真身的父類!

2、include指令
語法:<%@include file="頁面"%>  (靜態包含),常用作抽取出JSP重複的片段
include指令的作用是包含指定的頁面!在jsp被編譯成java文件之前會把兩個jsp文件合併,然後再編譯成一個java文件

注:請求轉發的include是動態包含,它會編譯成兩個.java文件,兩個.class文件

3、taglib指令

taglib指令是用來在當前jsp頁面中導入第三方的標籤庫(常用JSTL標籤庫)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

prefix:指定標籤前綴,這個東西可以隨意起名()
uri:指定第三方標籤庫的uri(唯一標識)

5、JSP動作標籤

JSP動作標籤是用來替代一部分java腳本,使非java開發人員也可以向jsp中添加動態信息

常見動作標籤:

<jsp:include>
例如:<jsp:include page="xxx"/>,用來包含指定的頁面。
例如在a.jsp中存在如下內容:<jsp:include page="b.jsp"/>
a.jsp和b.jsp分別編碼成Servlet,然後在執行Servlet時纔會執行包含過程。這也是include指令與include標籤的區別。

<jsp:forward>
例如:<jsp:forward page="xxx"/>,用來轉發到指定頁面
例如在a.jsp中存在如下內容:<jsp:fowrad page="b.jsp"/>
a.jsp中的內容不會顯示在瀏覽器上,而只是顯示b.jsp的內容。而且在<jsp:forwad>標籤下面的內容不會被執行。


<jsp:param>
該標籤是<jsp:include>和<jsp:forward>的子標籤,用來向其他頁面傳遞參數。
<jsp:include page="/b.jsp">
    <jsp:param value="zhangSan" name="username"/> 
</jsp:include>
在b.jsp中可以使用request.getParameter("username")來獲取參數值。

二、EL表達式(非常重要)

語法:${..}  

它是可以在JSP頁面中直接使用的語言,常用來代替java腳本中的<%=...%>

例如:輸出表達式的值:${1+2}  會在頁面上輸出3

判斷數組,集合,數據等是否爲空 ${empty ""} 返回true

EL一共11個內置對象

常用:

EL操作四大域的內置對象:它們是Map類型
pageScope
requestScope
sessionScope
applicationScope

${pageScope.user}:輸出pageContext.getAttribute("user")
${requestScope.user}:輸出request.getAttribute("user");
${sessionScope.user}:輸出session.getAttribute("user");
${applicationScope.user}:輸出application.getAttribute("user");

${user}   (全域查找)
依次在pageScope、requestScope、sessionScope、applicationScope中查找user
如果查找到,那麼立刻停止查找。

操作JavaBean
<%
User user = new User();
user.setUsername("zhangSan");
user.setPassword("123");
pageContext.setAttribute("user", user);  //一定要先保存到域對象中,EL表達式中才能輸出
%>
${pageScope.user.username}
${pageScope.user.password}

操作List

<%
User user = new User();
user.setUsername("zhangSan");
user.setPassword("123");
List list = new ArrayList();
list.add(user);
pageContext.setAttribute("list", list);
%>

${pageScope.list[0].username}
${pageScope.list[0].password}

操作Map
<%
User user = new User();
user.setUsername("zhangSan");
user.setPassword("123");
Map map = new HashMap();
map.put("u1", user);
pageContext.setAttribute("map", map);
%>
${pageScope.map.u1.username}
${pageScope.map.u1.password}

注:pageContext內置對象:PageContext類型   pageContext域可以獲取JSP的其他8大域對象

${pageContext.request},等同pageContext.getRequest()
${pageContext.session},等同pageContext.getSession()

${pageContext.request.contextpath},獲取項目名
${pageContext.session.id},獲取sessionId

三、EL函數庫

使用EL函數庫需要在JSP頁面中導入標籤庫:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/function"%>

<%
String[] strs = {"a", "b","c"};
List list = new ArrayList();
list.add("a");
pageContext.setAttribute("arr", strs);
pageContext.setAttribute("list", list);

%>
${fn:length(arr) }<br/><!--3-->
${fn:length(list) }<br/><!--1-->
${fn:toLowerCase("Hello") }<br/> <!-- hello -->
${fn:toUpperCase("Hello") }<br/> <!-- HELLO -->
${fn:contains("abc", "a")}<br/><!-- true -->
${fn:containsIgnoreCase("abc", "Ab")}<br/><!-- true -->
${fn:contains(arr, "a")}<br/><!-- true -->
${fn:containsIgnoreCase(list, "A")}<br/><!-- true -->
${fn:endsWith("Hello.java", ".java")}<br/><!-- true -->
${fn:startsWith("Hello.java", "Hell")}<br/><!-- true -->
${fn:indexOf("Hello-World", "-")}<br/><!-- 5 -->
${fn:join(arr, ";")}<br/><!-- a;b;c -->
${fn:replace("Hello-World", "-", "+")}<br/><!-- Hello+World -->
${fn:join(fn:split("a;b;c;", ";"), "-")}<br/><!-- a-b-c -->

${fn:substring("0123456789", 6, 9)}<br/><!-- 678 -->
${fn:substring("0123456789", 5, -1)}<br/><!-- 56789 -->
${fn:substringAfter("Hello-World", "-")}<br/><!-- World -->
${fn:substringBefore("Hello-World", "-")}<br/><!-- Hello -->
${fn:trim("     a b c     ")}<br/><!-- a b c -->

四、JSTL(JSP標準標籤庫) 重要

JSTL:JSTL是apache對EL表達式的擴展(也就是說JSTL依賴EL)

四大標籤庫:core(核心標籤庫)、fmt(格式化標籤庫)、sql(過時)、xml(過時)

core標籤庫:導入核心標籤庫<%taglib prefix="c" uri="http://java.sun.com/jstl/core"%>

常用標籤:

<c:set> 標籤:創建屬性,賦值
* <c:set var="a" value="hello"/> 創建名爲a,值爲hello的域屬性,默認範圍:page域
* <c:set var="a" value="hello" scope="session"/> 範圍爲session域

<c:out>標籤:輸出,相當於java腳本中的<%=...%>
* <c:out value="aaa"/> 輸出字符串aaa
* <c:out value="${aaa"/> 輸出域屬性aaa,其中與${aaa}相同
* <c:out value="${aaa}" default="xxx"/>如果${aaa}不存在,那麼輸出xxx字符串
* <c:out value="${aaa}" escapeXml="true"/>如果${aaa}中包含特殊字符,那麼轉義它。這可以防止javascript攻擊

<c:remove>
* <c:remove var="a"/> 刪除名爲a的域屬性
* <c:remove var="a" scope="page"/> 刪除page域中名爲a的域屬性

<c:url>  可以獲取項目名
* <c:url value="/AServlet"/> 輸出URL:/項目名/AServlet
* <c:url value="/AServlet" var="url" scope="page"/> 把生成的url保存到page域中,而不會輸出
* <c:url value="/AServlet">:輸出URL:/項目名/AServlet?username=%xx%xx%xx%xx%xx%xx,其中張三會被URL編碼
   <c:param name="username" value="張三"/>
  </c:url/>

<c:if>
* <c:if test="${條件}"> 當條件爲true時執行標籤體內容
    hello
  </c:if>

<c:choose> 相當於if...else
* <c:choose>
    <c:when test="${條件1}">a</c:when>
    <c:when test="${條件2}">b</c:when>
    <c:when test="${條件3}">c</c:when>
    <c:otherwise>d</c:otherwise>
  </c:choose>

  等同與:
  if() {
  } else if() {
  } else if() {
  } else if() {
  } else {
  }

<c:forEach>

可以用來遍歷數組、List、Map、

1. 計數循環

<c:forEach begin="1" end="10" var="i">
 ${i}
</c:forEach>
等同於
for(int i = 1; i <= 10; i++) {
  out.println(i);
}


<c:forEach begin="1" end="10" var="i" step="2">
 ${i}       
</c:forEach>
等同於
for(int i = 1; i <= 10; i+=2) {
  out.println(i);    
}

-------------

2. 遍歷數組

<%
String[] names = {"zhangSan", "liSi", "wangWu", "zhaoLiu"};
pageContext.setAttribute("ns", names);
%>
<c:forEach var="item " items="${ns } ">
    <c:out value="name: ${item } "/><br/>
</c:forEach>

-------------

3. 遍歷List

<%
    List<String> names = new ArrayList<String>();
    names.add("zhangSan");
    names.add("liSi");
    names.add("wangWu");
    names.add("zhaoLiu");
    pageContext.setAttribute("ns", names);
%>
<c:forEach var="item" items="${ns }"> 
    <c:out value="name: ${item }"/><br/>
</c:forEach>

4. 遍歷Map

<%
    Map<String,String> stu = new LinkedHashMap<String,String>();
    stu.put("number", "N_1001");
    stu.put("name", "zhangSan");
    stu.put("age", "23");
    stu.put("sex", "male");
    pageContext.setAttribute("stu", stu);
%>
<c:forEach var="item " items="${stu }">
    <c:out value="${item.key }: ${item.value } "/><br/>
</c:forEach>

5. 循環狀態對象

循環狀態對象是用來說明循環的狀態的,屬性如下:
count:int類型,當前以遍歷元素的個數;
index:int類型,當前元素的下標;
first:boolean類型,是否爲第一個元素;
last:boolean類型,是否爲最後一個元素;
current:Object類型,表示當前項目。

<c:forEach var="item" items="${ns }" varStatus="vs" >
    <c:if test="${vs.first } ">第一行:</c:if>
    <c:if test="${vs.last } ">最後一行:</c:if>
    <c:out value="第${vs.count } 行: "/>
    <c:out value="[${vs.index } ]: "/>
    <c:out value="name: ${vs.current } "/><br/>
</c:forEach>
 

格式化標籤庫fmt:導入格式化標籤庫<%taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%>

常用的標籤庫:格式化時間、數字

<% 
    Date date = new Date();
    pageContext.setAttribute("d", date);
%>
<fmt:formatDate value="${d }" pattern="yyyy-MM-dd HH:mm:ss "/>

----------------------------------------------------------------------------

<%
    double d1 = 3.5;
    double d2 = 4.4; 
    pageContext.setAttribute("d1", d1);
    pageContext.setAttribute("d2", d2);
%>
<fmt:formatNumber value="${d1 }" pattern="0.00 "/><br/>
<fmt:formatNumber value="${d2 }" pattern="#.## "/>

* pattern:0.00,表示小數不足兩位時,使用0補足兩位
* pattern:#.##,表示小數不足兩位時,有幾位顯示幾位,不會補足

 

 

 

 

 


 

發佈了16 篇原創文章 · 獲贊 8 · 訪問量 9807
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章