Java基礎——JSP(二),java基礎jsp
一、JSP隱式對象概述
為了簡化jsp運算式和指令碼片斷代碼的編寫,JSP一共提供了9個預先定義的變數,這些變數也稱為隱式對象或內建對象。
在 jsp產生的Servlet源碼中,有如下聲明:
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { //這裡聲明了內建對象 final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; //有一些內建對象是在這初始化的 try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, "err_page.jsp", true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write('\r'); out.write('\n'); .... }
這裡能找到8個內建對象, 還差一個 exception。
只要在專門用於錯誤處理的頁面,才有這個 對象,將頁面設為錯誤頁: <%@ page isErrorPage="true" %>,則會發現 在上面的 _jspService 方法中又多了一個 exception 對象,Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);
* 共有九大內建對象
//九大內建對象1.request //HttpServletRequest2.response //HttpServletResponse3.pageContext //pageContext4.application //ServletContext5.session //HttpSession6.page //Object7.out //JspWriter8.exception //Throwable9.config //ServletConfig
1.request對象 //HttpServletRequest
* request 擷取請求參數的方法
-- String getParamter(String name)
-- Enumeration getParameterNames(); //得到所有請求參數的名稱
-- String [] getPrameterValues(String name) ; //取得所有的相同name的值
public class StrUtil { public static String linkListSql(String [] list){ String str="("; for(int i=0;i<list.length;i++){ if(i<list.length-1){ str+=list[i]+","; }else{ str+=list[i]; } } str+=")" ; return str; } }//dao中:public int delUsers(String[] idList) { String sql="delete from userInfo where id in "+StrUtil.linkListSql(idList); System.out.println(sql); return DBUtil.update(sql, null); }
--Map getParameterMap() //得到一個Map
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String,String[]> map =request.getParameterMap(); Set<Map.Entry<String,String[]>> entrySet=map.entrySet(); Iterator<Map.Entry<String, String[]>> it=entrySet.iterator(); while(it.hasNext()){ Map.Entry<String, String[]> item=it.next(); System.out.println(item.getKey()+":"); String [] valueList=item.getValue(); for(int i=0;i<valueList.length;i++){ System.out.println(valueList[i]); } System.out.println("--------"); } }
2.request 擷取要求標頭的方法
-- getHeader(String name) //根據要求標頭的名稱得到內容
-- Enumeration getHeaderNames() //取得所有的要求標頭名稱
-- int getIntHeader(String name) //根據名稱,得到整數類型的標題
-- Cookie [] getCookies() //取得所有與要求標頭相關的Cookie
Enumeration headList =request.getHeaderNames(); while(headList.hasMoreElements()){ String headerName=headList.nextElement().toString(); System.out.println(headerName+":"); System.out.println(request.getHeader(headerName)); System.out.println("----"); }
* request
String getContextPath() //取得Context路徑 --- /show-admin-mvc
String getMethod() //取得Http 方法(GET ,POST) --GET
String getProtocol() //取得使用的協議(HTTP/1.1,HTTP/1.0) --HTTP/1.1
String getQueryString() //取得請求的參數字串,不過HTTP的方法必須為GET --userName=f e=f&password=f e=f
String getRequestSessionId() //取得用戶端的SessionId
String getRequestURI() //取得請求的URL,但不包擴請求的參數 字串 --UserWeb/Test.jsp
String getRemoteAddr() //取得使用者的IP地址 很有用
String getRemoteHost() //取得使用者的主機名稱
int getRemotePort() //取得使用者的主機連接埠
String getRemoteUser() //取得使用者的名稱
void setCharacterEncoding(String encoding) //設定編碼格式,用來解決頁面傳遞中文的問題
3.response 對象
將處理jsp處理資料後的結果返回給用戶端,該對象實現javax.servlet.http.HttpServletResponse 介面
* 設定回應標頭的方法
void addCookie(Cookie cookie)
void addDateHeader(String name,long date)
void addHeader(String name,String value);
void addIntHeader(String name,int value);
void setHeader(String name,String value);
* 設定響應狀態代碼的方法
void sendError(int sc); 傳遞狀態代碼(status code)
void sendError(int sc,String msg)傳送狀態代碼和錯誤資訊 //response.sendError(404,"哈哈,錯了,活 gai " );
void setStatus(int sc) 設定狀態代碼
* 用於重新導向的方法
sendRedirect(String url);
4.session 對象
實現 javax.servlet.htt.HttpSession介面
setAttribute(String name,Object obj);
long getCreationTime() 取得Session產生的時間,毫秒,從1970年1月1日零時起算
String getId() //取得Session 的 Id
long getLastAccessedTime() 最得最後用這個Session發送的時間,同上
void invalidate() 取消session對象 並將其存放的內容釋放
boolean isNew() 判斷Session是否為新 (伺服器產生,但client尚未使用)
void setMaxInactiveInterval(int interval) 到期時間,以秒為單位
5 application 對象
實現javax.servlet.ServletContext 介面
伺服器啟動後它就產生了
* 容器相關資訊的方法
int getMajorVersion() //取得Container主要的Servlet API 版本 --2
int getMinorVersion //取得次版本
String getServerInfo () //取得Container 的名稱和版本
* 有關伺服器的路徑和檔案的方法
String getMimeType(String file)取得指定檔案的MIME類型
ServletContex getContext(String uripath)取得指定Local URL 的 Application context
String getRealPath(String path) 取得本地端path的絕對路徑
例如 : <% out.println(application.getRealPath("Login.jsp"));%>//C:\Program Files\Tomcat 6.0\webapps\UserWeb\Login.jsp
* 有關日誌記錄的方法
void log(String msg)將資訊寫入記錄檔中
void log(String msg,Throwable throwable)將stack trace所產生的異常資訊寫入log檔案中
6.pageContext 對象 //PageContext
提供了返回JSP頁面的其他隱式對象的方法
getPage()
getRequest()
getResponse()
getServletConfig()
getServletContext() //返回applaction隱式對象
getSession()
getException()
getOut()
pageContex 對象是通過調用 JspFactory.getPageContext 方法獲得的
描述 JSP 文檔的運行環境提供對所有其他隱式對象及其屬性的訪問
void forward (path) //可以進行跳轉, 屬於請求的轉寄 // pageContext.forward("login.jsp");
ServletConfig getServletConfig() //返回servlet設定物件(即config對象)
///例子 public void test(PageContext context){ context.getRequest().setAttribute("requestKey","這是往request放的東西"); context.getSession().setAttribute("sessionkey", "這是往session放的東西"); context.getServletContext().setAttribute("applicationKey", "這是application的"); }
7.exception 對象 // Throwable
要使用它,必須在當前版面設定 。。。 isErrorPage="true" %>
別的頁頁設定 errorPage="ErrProcess.jsp"%>
8.page對象
Object page=this 表示jsp頁面本身
9.config對象 //ServletConfig
儲存 Servlet 設定物件,是 javax.servlet.servletConfig 介面的一個執行個體。
重要方法:
Enumeration getInitParameterNames()
String getInitParameter(name)
10.out對象 JspWriter
用來向jsp頁面發送文本形式的實體內容,它是調用pageContext 的getOut()方法取得的它和以前學的 ServletResonse.getWriter方法返回的 PrintWriter 對象常相似,但兩者是不同的對象。JSP中的out 的類型為JspWriter,相當於一個帶緩衝功能的PrintWriter,相當於PrintWriter的封裝類
11.訪問各個域範圍中的屬性
在pageContext, request,session,appaction 對象中,都可以調用 setAttribute 和 getAttribute 方法來設定和檢索屬於各自域範圍內的屬性, 它們的不同之處如下:
--appaction 中的,可以被同一個web應用程式中所有的Servlet和JSP頁面訪問
--session 中的,可以被同一個會話所有的Servlet和 JSP頁面訪問
--request 中的,可以被同一個請求中的所有Servlet 和 js頁面訪問
--pageContext 中的,僅可以被當前JSP頁面的當前響應過種中調用的各個組件訪問
pageContext 類還提供了對個各域範圍的屬性進行統一管理的方法,它的setAttribute 方法有如下重載
* public void setAttribute(String name,Object value); //page範圍
* pbulic void setAttribute(String name,Object value,int scope) //scope 指定域範圍
scope 對應的常量: PageContext. //這幾個常量定義在 PageContext 類中
APPLICATION_SCOPE,
SESSION_SCOPE,
REQUEST_SCOPE,
PAGE_SCOPE
//例子pageContext.setAttribute("key",value,PageContext.SESSION_SCOPE) //相當於往session中放值
12.Mime類型
不管瀏覽器接收到的是什麼資料,實際上都是0,和 1 給成的位元據,瀏覽器不知道它,接收的是圖片,普通網頁,還是Excel文檔,因為此,web伺服器必須通過某種方式告訴瀏覽器所接收的實體內容代表的是哪種格式的資料,瀏覽器才能正確的處理,電腦應用中有多種通用資料格式,人們為每一種通用的資料格式都定義了一個名稱,稱為 MIME (Mutipurpose Internet Mail Extension 多用途Internet 郵件擴充) 類型Content-Type頭欄位用於指出實體中內容的Mime 類型,大多數Web伺服器都可以設定副檔名和Mime類型的對應關係。在tomcat 中,可以在 C:\Tomcat6.0\conf\web.xml 中找到大量的這種Mime類型的對應設定。