ServletConfig接口:
SevletConfig接口位於javax.servlet包中,它封裝了servlet配置信息,在servlet初始化期間被傳遞。每一個Servlet都有且只有一個ServletConfig對象。
首先配置信息為:
- getInitParameter(String name)————此方法返回String類型名稱為name的初始化參數值
- getInitParameterNames()————獲取所有初始化參數名的枚舉集合
- getServletContext()————用於獲取Servlet上下文對象
- getServletName()————返回Servlet對象的實例名
public void init(ServletConfig servletConfig) throws ServletException { System.out.println("init"); //獲取初始化參數:servlConfig String user=servletConfig.getInitParameter("user"); System.out.println("user:"+user); Enumeration<String> names=servletConfig.getInitParameterNames(); while(names.hasMoreElements()) { String name=names.nextElement(); String value=servletConfig.getInitParameter(name); System.out.println("~~"+name+":"+value); } //獲取servletConfig對象 servletContext ServletContext servletcontext=servletConfig.getServletContext(); String driver=servletcontext.getInitParameter("driver"); System.out.println("driver:"+driver); Enumeration<String> names2=servletcontext.getInitParameterNames(); while(names2.hasMoreElements()) { String name=names2.nextElement(); System.out.println("-->"+name); } //獲取當前WEB應用的某一個文件在服務器上的絕對路徑,而不是部署前的物理路徑 String realpath=servletcontext.getRealPath("/note.txt"); System.out.println(realpath); //獲取當前web應用的名稱 String contextPath = servletcontext.getContextPath(); System.out.println(contextPath); try { ClassLoader classLoader=getClass().getClassLoader(); InputStream is=classLoader.getResourceAsStream("jdbc.servlet"); System.out.println("1."+is); } catch (Exception e) { e.printStackTrace(); } //獲取當前WEB應用的某一個文件對應的輸入流:path的/為當前web應用的根目錄 try { InputStream is2=servletcontext.getResourceAsStream("/WEB-INF/classes/jdbc.servlet"); System.out.println("2."+is2); } catch (Exception e) { e.printStackTrace(); } }
輸出結果:
GET 請求和 POST 請求:
1). 使用GET方式傳遞參數:
- 在瀏覽器地址欄中輸入某個URL地址或單擊網頁上的一個超鏈接時,瀏覽器發出的HTTP請求消息的請求方式為GET。
- 如果網頁中的<form>表單元素的 method 屬性被設置為了“GET”,瀏覽器提交這個FORM表單時生成的HTTP請求消息的請求方式也為GET。
- 使用GET請求方式給WEB服務器傳遞參數的格式: http://www.boogiever.com/counter.jsp?name=ISEE&password=777
- 使用GET方式傳送的數據量一般限制在 1KB 以下。
2). 使用 POST 方式傳遞參數:
- POST 請求方式主要用於向 WEB 服務器端程序提交 FORM 表單中的數據: form 表單的 method 置為 POST
- POST 方式將各個表單字段元素及其數據作為 HTTP 消息的實體內容發送給 WEB 服務器,傳送的數據量要比使用GET方式傳送的數據量大得多。
POST /counter.jsp HTTP/1.1
referer: http://localhost:8080/Register.html
content-type: application/x-www-form-urlencoded
host: localhost:8080
content-length: 43
name=wangziyi&password=777 --請求體中傳遞參數.
Serlvet接口只定義了一個服務方法就是service,而HttpServlet類實現了該方法並且要求調用下列的方法之一:
doGet:處理GET請求
doPost:處理POST請求
當發出客戶端請求的時候,調用service 方法並傳遞一個請求和響應對象。Servlet首先判斷該請求是GET 操作還是POST 操作。然后它調用下面的一個方法:doGet 或 doPost。如果請求是GET就調用doGet方法,如果請求是POST就調用doPost方法。doGet和doPost都接受請求 (HttpServletRequest)和響應(HttpServletResponse)。
在實現登陸界面時發現form里面寫的是post而邏輯處理頁面代碼都寫在doget()里面依然可以正常運行,思考后發現是由於tomcat自動生成代碼時,dopost()里面調用了doget()方法;