原文鏈接http://zhhll.icu/2021/01/13/javaweb/servlet/
最全的javaweb知識全集
Servlet是java定義的Servlet標準介面
servlet容器負責Servlet和客戶的通信以及呼叫Servlet的方法
public interface Servlet {
void init(ServletConfig var1) throws ServletException;
ServletConfig getServletConfig();
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
String getServletInfo();
void destroy();
}
servlet生命周期
生命周期相關方法,servlet生命周期中的方法全是由servlet容器來呼叫的
- 構造器
- init方法
- service方法
- destory方法
init方法
init方法在第一次創建servlet時被呼叫,在后續每次請求時都不會被呼叫,
當用戶呼叫servlet的時候,該servlet的一個實體就會被創建,并且為每一個用戶產生一個新的執行緒,init()用于進行一些初始化資料的加載和處理,這些資料會被用于servlet的整個生命周期
void init(ServletConfig var1) throws ServletException;
該方法是由servlet容器呼叫的
重寫init方法
GenericServlet實作了Servlet和ServletConfig,是一個抽象類,并對init(ServletConfig var1)方法進行了一層封裝,有一個ServletConfig成員變數,在init()方法中進行了初始化,使得可以直接在GenericServlet中直接使用ServletConfig方法
而我們平時寫Servlet大多是繼承于HttpServlet類的,在對init方法進行重寫時,重寫不帶參的init()方法即可
//GenericServlet類
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public void init() throws ServletException {
}
該方法由GenericServlet的呼叫,如果需要使用到ServletConfig則呼叫getServletConfig()方法來獲取
service方法
service方法是實際處理請求的方法,servlet容器呼叫service方法來處理請求,并將回應寫會到客戶端,每次服務器接收到一個新的servlet請求時,服務器會產生一個新的執行緒來呼叫服務
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
處理請求邏輯
HttpServlet繼承了GenericServlet,重寫了service方法,將ServletRequest和ServletResponse轉換為HttpServletRequest和HttpServletResponse,并根據不同的請求方式進行分發,doGet/doPost/doHead等
servlet可以在任何協議下訪問 ,寫的Servlet必須實作Servlet介面,在http協議下可以使用HttpServlet ,用來給Web訪問的
在HttpServlet類中對于service()方法進行了處理,根據請求方式的不同,將請求分發到了不同的方法,而我們一般情況下寫Servlet也是繼承自HttpServlet的,所以在寫請求處理邏輯時,只需要重寫doGet()和doPost()方法即可
// HttpServlet類
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_get_not_supported");
this.sendMethodNotAllowed(req, resp, msg);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_post_not_supported");
this.sendMethodNotAllowed(req, resp, msg);
}
GET方法
GET方法時瀏覽器向web服務器傳遞資訊的默認方法,會在地址欄上產生很長的字串,且GET方法有大小限制,請求字串中最多只能有1024個字符
POST方法
POST方法不將請求資訊放到地址中
destroy方法
destory()方法只在servlet生命周期結束時被呼叫一次,可以在destory()方法中進行一些資源的清理,如關閉資料庫連接、停止后臺執行緒等
ServletContext介面
- 該物件代表當前WEB應用,可以獲取到web應用的資訊
- 可以使用ServletConfig的getServletContext()獲取到ServletContext
- 可以獲取web應用的初始化引數,這是全域的方法,在web.xml中配置
- 獲取web應用某個檔案的絕對路徑(在服務器上的路徑,不是部署前的方法) getRealPath
- 獲取當前應用的名稱 getContextPath
- 獲取當前web應用的某一個檔案對應的輸入流 getResourceAsStream() path是相對于當前web應用的根目錄
servlet容器
在上面介紹servlet生命周期時,多次提到了servlet容器,其實在設計Servlet時,J2EE jdk只是提供了一個標準,在javax.servlet包以及子包下,而真正的實作是由servlet容器來進行實作的,如tomcat是在servlet-api.jar中實作的
servlet容器
1、可以創建servlet,并呼叫servlet的相關生命周期方法
2、JSP、Filter、Listener
下面將以tomcat作為servlet容器為例介紹web應用
web應用
WEB-INF
靜態頁面不要放在WEB-INF下,WEB-INF是給tomcat用的
WEB-INF 對于web應用的描述
- web.xml 必須符合J2EE標準
- lib 放jar包
-
tomcat配置專案位置
tomcat映射配置任意目錄的專案
在conf下新建catalina檔案夾,新建localhost檔案夾,
在其中新建一個xml檔案,檔案名是url根路徑
path當前沒用 docBase為專案路徑(編譯之后的專案)
<Context path="" docBase="" reloadable="true">
web.xml配置servlet
load-on-startup引數指定servlet創建的時機 若為負數,則在第一次請求時被創建,若為0或者正數,在web應用被Servlet容器加載時創建實體,值越小越早被啟動
init方法有入參 ServletConfig
配置ServletConfig
<!-- 注意servlet和servlet-mapping都是成對出現的 -->
<servlet>
<servlet-name>HW</servlet-name>
<servlet-class>com.zhanghe.study.servlet.HelloWorldServlet</servlet-class>
<!-- 配置servlet初始化init時中ServletConfig引數-->
<init-param>
<param-name>name</param-name>
<param-value>john</param-value>
</init-param>
<!-- servlet加載時機 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!-- 對應servlet標簽中的servlet-name值 -->
<servlet-name>HW</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
? 獲取ServletConfig值
// 獲取指定的屬性
config.getInitParameter("name")
// 獲取所有的屬性
config.getInitParameters()
請求轉發和請求重定向
// 請求轉發
request.getRequestDispatcher(url).forward(req,resp)
// 請求重定向
response.sendRedirect(url)
本質區別:請求轉發只向服務器發起一次請求,重定向發起兩次請求
1、
請求轉發:地址是初次發出請求的地址
重定向:地址欄是最后回應的地址
2、
請求轉發:在最終的Servlet中,request物件和中轉的那個request是同一個物件
重定向:在最終的Servlet中,request物件和中轉的那個request不是同一個物件
3、
請求轉發:只能轉發到當前web應用
請求重定向:可以重定向到任何資源
4、
請求轉發:/代表當前web應用的根目錄
請求重定向:/代表當前web站點的根目錄,要使用request.getContextPath()再加上路徑
會話管理
HTTP是無狀態的協議,每次客戶端訪問web頁面時,都會打開一個單獨的連接到web服務器,服務器不會自動保存客戶端請求的任何記錄,需要使用cookie和session來將一系列的請求和回應關聯起來,維持客戶端和服務器之間的會話
cookie
Cookie是存盤在計算機上的文本檔案,用于追蹤各種資訊,記錄在客戶端,瀏覽器可以禁用cookie,可以洗掉cookie,
在服務器產生,作為回應頭的一部分回傳給客戶端,瀏覽器收到cookie后,把cookie的鍵值寫入到文本中,發送請求時瀏覽器會把cookie資訊與請求發送給服務器
cookie原理
底層原理:WEB服務器通過在HTTP回應訊息中增加Set-Cookie回應頭欄位將Cookie資訊發送給瀏覽器,瀏覽器則通過在HTTP請求資訊中增加Cookie請求頭欄位將Cookie回傳給WEB服務器
操作cookie
創建cookie
// 第一個引數是cookie的鍵,第二個引數是cookie的值
Cookie cookie = new Cookie("name","value")
resp.addCookie(cookie)
獲取cookie
Cookie[] cookies = req.getCookies();
設定cookie的一些方法
// 描述cookie的注釋
public void setComment(String purpose) {
this.comment = purpose;
}
// 設定cookie適用的域名
public void setDomain(String pattern) {
this.domain = pattern.toLowerCase(Locale.ENGLISH);
}
// 設定過期時間(單位是秒),如果不設定,cookie在當前session中有效
// 如果設定生命周期會寫在檔案里
// 如果不設定生命周期會寫在瀏覽器記憶體里,視窗關閉,cookie就沒了
public void setMaxAge(int expiry) {
this.maxAge = expiry;
}
// 設定cookie適用的路徑,如果不指定,在當前目錄及其子目錄的URL下會回傳cookie
public void setPath(String uri) {
this.path = uri;
}
// 是否只在加密的連接上(SSL)發送
public void setSecure(boolean flag) {
this.secure = flag;
}
// 設定cookie值
public void setValue(String newValue) {
this.value = https://www.cnblogs.com/life-time/p/newValue;
}
public void setVersion(int v) {
this.version = v;
}
獲取cookie屬性的方法
// 獲取cookie的注釋,如果沒有為null
public String getComment() {
return this.comment;
}
// 獲取cookie適用的域名
public String getDomain() {
return this.domain;
}
// 獲取cookie過期時間,如果為-1,cookie表示持續到瀏覽器關閉
public int getMaxAge() {
return this.maxAge;
}
// 獲取cookie適用的路徑
public String getPath() {
return this.path;
}
// 獲取是否只在加密的連接上發送
public boolean getSecure() {
return this.secure;
}
// cookie的名稱,創建后不可修改
public String getName() {
return this.name;
}
// 獲取cookie值
public String getValue() {
return this.value;
}
public int getVersion() {
return this.version;
}
洗掉cookie
設定生命周期 cookie.setMaxAge()方法設定,秒為單位,若為0,表示立即洗掉該cookie,將該cookie放到回應中回傳
注意:一個servlet設定的cookie可以被同一個路徑下或者子路徑下的servlet讀到,其他訪問不到
? 路徑是指url可以通過cookie.setPath()方法設定cookie的作用范圍
cookie適用場景
- 自動登錄,不需要填寫用戶名和密碼
- 瀏覽記錄
session
session是記錄在服務器端,獲取session需要把sessionId傳遞給服務端,通過sessionId來取到對應的session,關閉瀏覽器,session不會被銷毀,還可以通過sessionId找到該session,在同一個application下的servlet/jsp可以共享一個session,前提是同一個客戶端視窗
操作session
創建或獲取session
// 若為false,如果當前沒有關聯的session,如回傳null;若為true,如果沒有則會創建 默認是true
HttpSeesion session = request.getSession(true);
session的相關方法
// 回傳session的創建時間(單位毫秒)
long getCreationTime();
// 獲取sessionId
String getId();
// 回傳客戶端最后一次發送與該session會話相關的請求的時間(單位毫秒)
long getLastAccessedTime();
ServletContext getServletContext();
// session的過期時間,單位秒
// 也可以在web.xml中設定過期時間,單位為分鐘,tomcat默認是30分鐘
// <session-config>
// <session-timeout15></session-timeout>
// </session-config>
void setMaxInactiveInterval(int var1);
// 回傳servlet容器在客戶端訪問時保持session會話打開的最大時間間隔,單位秒
int getMaxInactiveInterval();
// 回傳seesion會話中該名稱的物件,沒有回傳null
Object getAttribute(String var1);
// 回傳該session會話中所有的名稱
Enumeration<String> getAttributeNames();
// 將物件系結到該session會話中
void setAttribute(String var1, Object var2);
// 移除指定名稱的物件
void removeAttribute(String var1);
// 使該session無效
void invalidate();
// 是否為新創建的session(客戶端還不知道該session)
boolean isNew();
// 判斷當前請求的session是否合法
req.isRequestedSessionIdValid();
// 判斷當前請求是不是從URL發出的
req.isRequestedSessionIdFromURL();
// 判斷當前請求是不是從cookie發出的
req.isRequestedSessionIdFromCookie();
session的實作方式
session有兩種實作方式
①通過cookie來實作 第一次請求時,回應在回應頭set-Cookie中 有sessionId,把sessionId放到cookie中,如果瀏覽器支持cookie,會把sessionId放到cookie中
默認是存盤在記憶體中的,沒有存盤在磁盤上,關閉瀏覽器就會失效
可以進行持久化,使用cookie.setMaxAge
②通過URL重寫來實作
response.encodeURL兩個作用
- 轉碼
- URL后加上sessionID
過濾器Filter
可以對請求和回應進行攔截,在訪問后端資源之前,攔截這些來自客戶端的請求,在發送回客戶端之前,處理這些回應
過濾器的型別
- 身份驗證過濾器
- 資料壓縮過濾器
- 加密過濾器
- 觸發訪問事件資源的過濾器
- 影像轉換過濾器
- 日志記錄和審核過濾器
- MIME-型別鏈過濾器
- Tokenizing過濾器
- 轉換XML內容的XSL/T過濾器
過濾器的使用
需要實作Filter介面
public interface Filter {
// 由servlet容器呼叫,指示一個過濾器被放入服務
void init(FilterConfig var1) throws ServletException;
// 在每次一個請求或回應在所對應的資源下時通過鏈傳遞,由容器呼叫
void doFilter(ServletRequest var1, ServletResponse var2, FilterChain var3) throws IOException, ServletException;
// 由servlet容器呼叫,指示一個過濾器從服務去除
void destroy();
}
? 在web.xml中配置寫好的Filter
<filter>
<filter-name>security</filter-name>
<filter-class>com.zhanghe.study.webstudy.filter.SecurityFilter</filter-class>
<!--用戶名-->
<init-param>
<param-name>userName</param-name>
<param-value>john</param-value>
</init-param>
</filter>
<!-- 攔截的順序與在web.xml中 filter-mapping的配置順序有關,靠前的先被呼叫 -->
<filter-mapping>
<filter-name>security</filter-name>
<url-pattern>/*</url-pattern>
<!-- 在filter-mapping中有一個dispatcher標簽,指定過濾器所攔截的資源被Servlet容器的呼叫方式
可以是REQUEST,INCLUDE,FORWARD和ERROR,默認是REQUEST
可以指定多個dispatcher來指定Filter對資源的多種呼叫方式進行攔截 -->
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
例外處理
當servlet出現例外時,servlet容器使用exception-type元素來找到與拋出的例外型別相匹配的配置
public class ExceptionHandler extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
Integer code = (Integer) req.getAttribute("javax.servlet.error.status_code");
String message = (String) req.getAttribute("javax.servlet.error.message");
System.out.println("=========");
System.out.println(throwable);
System.out.println("=========");
System.out.println(code);
System.out.println("=========");
System.out.println(message);
}
}
<!-- 配置例外處理的servlet -->
<servlet>
<servlet-name>ExceptionHandler</servlet-name>
<servlet-class>com.zhanghe.study.servlet.ExceptionHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ExceptionHandler</servlet-name>
<url-pattern>/ExceptionHandler</url-pattern>
</servlet-mapping>
<!-- 配置哪些錯誤碼會呼叫該例外處理類 -->
<error-page>
<error-code>404</error-code>
<location>/ExceptionHandler</location>
</error-page>
<!-- 配置哪些例外型別會呼叫該例外處理類 -->
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/ExceptionHandler</location>
</error-page>
如果出現例外,會在請求域中設定相應的屬性
可以使用request.getAttribute("")取出
javax.servlet.error.status_code //錯誤碼,Integer型別
javax.servlet.error.exception_type // 例外型別,Class型別
javax.servlet.error.message //例外資訊,String型別
javax.servlet.error.request_uri //出現例外的uri地址,String型別
javax.servlet.error.exception //例外,Throwable型別
javax.servlet.error.servlet_name //servlet名稱,String型別
上傳檔案
<!-- 上傳檔案一定要使用post請求
enctype需要設定為multipart/form-data
input標簽的type型別設為file
-->
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
form表單的編碼格式
①application/x-www-form-urlencoded 默認 在發送前編碼所有字符
②multipart/form-data 不對字符編碼,二進制
③text/plain 空格轉換為+號,但不對特殊字符編碼
使用讀取流的方式來讀取太過于麻煩 request.getInputStream() 獲取到的是整個請求體,需要決議各個欄位和分隔
決議multipart/form-data比較復雜
可以使用外部依賴包
commons-fileupload.jar 依賴于 commons-io.jar
<!-- 檔案上傳 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
commons-fileupload決議請求,決議成FileItem集合,無論是文本域還是檔案域
使用FileItem.isFormField()來判斷是不是一個表單域
表單域 item.getFieldName item.getString
? 非表單域 item.getFieldName item.getName item.getContentType item.isImemory item.getSize item.getInputStream
轉發和重定向
國際化
- 國際化(i18n): i18n internationalization,網站能夠提供翻譯成訪問者的語言或國籍的不同版本的內容
- 本地化(i10n): 向網站添加資源,使其適應特定的地理或文化區域,例如將網站翻譯為中文
- 區域設定:通常為語言符號后跟一個由下劃線分隔的國家符號,例如"en_US"
獲取區域
//獲取當前國家和語言
Locale locale = request.getLocale();
獲取區域設定
// 獲取該區域設定的國家
public String getCountry() {
return baseLocale.getRegion();
}
// 獲取該區域設定的國家名稱
public final String getDisplayCountry() {
return getDisplayCountry(getDefault(Category.DISPLAY));
}
// 獲取該區域設定的語言代碼
public String getLanguage() {
return baseLocale.getLanguage();
}
// 獲取該區域設定的語言名稱
public final String getDisplayLanguage() {
return getDisplayLanguage(getDefault(Category.DISPLAY));
}
// 回傳該區域設定的國家的三個字母縮寫
public String getISO3Country() throws MissingResourceException {
String country3 = getISO3Code(baseLocale.getRegion(), LocaleISOData.isoCountryTable);
if (country3 == null) {
throw new MissingResourceException("Couldn't find 3-letter country code for "
+ baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry");
}
return country3;
}
// 回傳該區域設定的語言的三個字母縮寫
public String getISO3Language() throws MissingResourceException {
String lang = baseLocale.getLanguage();
if (lang.length() == 3) {
return lang;
}
String language3 = getISO3Code(lang, LocaleISOData.isoLanguageTable);
if (language3 == null) {
throw new MissingResourceException("Couldn't find 3-letter language code for "
+ lang, "FormatData_" + toString(), "ShortLanguage");
}
return language3;
}
時間國際化
時間格式化 DateFormat
貨幣國際化
數字、貨幣格式化 NumberFormat
字串國際化
字串格式化 MessageFormat
String str = "Date: {0},Salary: {1}";
Locale locale = Locale.CHINA;
Date date = new Date();
double sa1 = 12345.12;
MessageFormat.format(str,date,sa1);
國際化配置
native2ascii命令在jdk下 可以查看ascii碼
Locale locale = Locale.CHINA;
ResourceBundle bundle = ResourceBundle.getBundle("i18n",locale);
在組態檔中i18n.properties i18n_en_US.properties i18n_zh_CN.properties
根據locale來找不同的組態檔
中文亂碼問題
GET請求 ①tomcat的server.xml檔案中,在Connector 節點中添加useBodyEncodingForURI="true" 屬性 使用請求體的編碼,然后在獲取請求內容之前使用request.setCharacterEncoding("UTF-8")
②tomcat的server.xml檔案中,在Connector 節點中添加URIEncoding="UTF-8"屬性
③tomcat的get請求默認使用ISO-8859-1來編碼,可以在獲取的時候進行轉碼,new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8")
多個請求使用同一個Servlet
第一種方案:在url加上入參method
根據method進行分發
? 第二種方案:
? web.xml使用*.do來匹配Servlet
? 根據 request.getServletPath()然后反射呼叫方法
表單的重復提交
重復提交的情況
①在表單提交到一個Servlet,Servlet又通過請求轉發的方式回應了一個頁面,此時地址欄還保留著Servlet的那個路徑,在回應頁面點擊重繪
②在回應頁面沒有到達時重復點擊提交按鈕
③點擊回傳,再點擊提交
不是重復提交的情況
①點擊回傳之后,重繪頁面,再點擊提交
如何避免表單的重復提交
使用session,生成屬性,移除屬性
HttpServletRequestWrapper類包裝原始的request物件,實作了HttpServletRequest介面的所有方法,內部呼叫了所包裝的
request物件的對應方法
相應的也有HttpServletResponseWrapper類來包裝原始的response物件
繼承HttpServletRequestWrapper,重寫
Servlet監聽器
用于監聽ServletContext、HttpSession、ServletRequest等物件的創建和銷毀,以及屬性修改
①監聽ServletContext、HttpSession、ServletRequest等物件的創建和銷毀
ServletContextListener 創建contextInitialized 銷毀contextDestroyed
HttpSessionListener 創建sessionCreated 銷毀sessionDestroyed
ServletRequestListener 創建requestInitialized 銷毀requestDestroyed
實作相應的介面,監聽不同的域物件
web.xml
<listener>
<listener-class>
場景:
ServletContextListener最常用,在當前WEB應用加載的時候對當前WEB應用的相關資源進行初始化操作:創建資料庫連接池,創建Spring的IOC容器,讀取當前WEB應用的初始化引數
②監聽域物件 ServletContext、HttpSession、ServletRequest 屬性變更的監聽器
ServletContextAttributeListener attributeAdded attributeRemoved attributeReplaced
HttpSessionAttributeListener attributeAdded attributeRemoved attributeReplaced
ServletRequestAttributeListener attributeAdded attributeRemoved attributeReplaced
ServletRequestAttributeEvent 可以getName、getValue或者值
③感知session系結的監聽器
保存到Session域中的物件可以有多種狀態:系結到Session中,從Session中解除系結;隨Session物件持久到到一個存盤設備中;隨Session物件從一個存盤設備中恢復
HttpSessionBindingListener和HttpSessionActivationListener介面,實作這兩個介面不需要在web.xml檔案中注冊
放到session中的物件實作HttpSessionBindingListener
會觸發兩個方法 系結valueBound 解除valueUnBanding
實作了HttpSessionActivationListener介面的物件可以感知自己被鈍化和被活化的事件
sessionWillPassivate 從記憶體寫到磁盤 sessionDisActivate 從磁盤中讀取出來
session會被存盤在tomcat當前專案下 .cer檔案
由于本身的博客百度沒有收錄,博客地址http://zhhll.icu
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/260473.html
標籤:Java
