Servlet小結
一、Servlet的init()和構造方法僅僅調用一次,僅僅會在第一次請求時候被調用一次,或者當Servlet配置爲啓動時候最早加載則會在啓動時候調用,配置方法是:<load-on-startup>0</load-on-startup>
二、因爲Servlet只會調用構造方法一次,所以Servlet是單例的,在Servlet容器中,一個Servlet類只有一個Servlet實例存在。
三、Servlet處理請求是方式是多線程的,也就是說,一個請求會開啓一個獨立線程來處理。所以,在Servlet的處理方法應該注意線程安全。
四、Servlet能夠配置參數,在Servlet類裏能夠讀取參數。
<
init-param
>
<
param-name
>n1
</
param-name
>
<
param-value
>v1
</
param-value
>
</
init-param
>
<
init-param
>
<
param-name
>n2
</
param-name
>
<
param-value
>v2
</
param-value
>
</
init-param
>
ServletConfig cfg = getServletConfig();
String p1 = cfg.getInitParameter(
"n1");
String p2 = cfg.getInitParameter(
"n2");
五、Servlet有輸出流,輸出流分兩種,一種是字節流,一種是字符流,也能夠獲取輸入流,好比上傳文件時候就有輸入流,輸入流的只能是字節流。
ServletOutputStream os = response.getOutputStream();
PrintWriter out = response.getWriter();
ServletInputStream is = request.getInputStream();
六、一個Servlet的配置對象ServletConfig對象只有一個,配置的參數也只讀一次,在調用init()時候讀取Servlet配置,並構建ServletConfig對象。
七、ServletConfig對象只能在Servlet中訪問,不能被JSP訪問。ServletContext對象能夠被JSP訪問。
八、一個Servlet有且只有一個ServletConfig對象,一個Web應用有且僅有一個ServletContext對象,ServletContext對象在JSP中經過application內置對象來訪問。
九、ServletContext也可也配置本身參數,在web.xml中配置,在任何JSP或Servlet中均能獲取到。
<
context-param
>
<
param-name
>cn1
</
param-name
>
<
param-value
>cv1
</
param-value
>
</
context-param
>
<
context-param
>
<
param-name
>cn2
</
param-name
>
<
param-value
>cv2
</
param-value
>
</
context-param
>
ServletContext ctx= getServletContext();
String c1 = ctx.getInitParameter(
"cn1");
String c2 = ctx.getInitParameter(
"cn2");