Servlet 生命周期的階段
創(chuàng)新互聯(lián)主營(yíng)渾南網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,app開發(fā)定制,渾南h5小程序定制開發(fā)搭建,渾南網(wǎng)站營(yíng)銷推廣歡迎渾南等地區(qū)企業(yè)咨詢1、通過調(diào)用“init()”方法進(jìn)行初始化;
init 方法被設(shè)計(jì)成只調(diào)用一次。它在第一次創(chuàng)建 Servlet 時(shí)被調(diào)用,在后續(xù)每次用戶請(qǐng)求時(shí)不再調(diào)用。
@Override public void init(ServletConfig config) throws ServletException { this.config = config; this.init(); }
2、調(diào)用“service()”方法來處理客戶端的請(qǐng)求;
service() 方法是執(zhí)行實(shí)際任務(wù)的主要方法。Servlet 容器(即 Web 服務(wù)器)調(diào)用 service() 方法來處理來自客戶端(瀏覽器)的請(qǐng)求,并把格式化的響應(yīng)寫回給客戶端。
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if (method.equals(METHOD_GET)) { long lastModified = getLastModified(req); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic doGet(req, resp); } else { long ifModifiedSince; try { ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE); } catch (IllegalArgumentException iae) { // Invalid date header - proceed as if none was set ifModifiedSince = -1; } if (ifModifiedSince < (lastModified / 1000 * 1000)) { // If the servlet mod time is later, call doGet() // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less maybeSetLastModified(resp, lastModified); doGet(req, resp); } else { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else if (method.equals(METHOD_HEAD)) { long lastModified = getLastModified(req); maybeSetLastModified(resp, lastModified); doHead(req, resp); } else if (method.equals(METHOD_POST)) { doPost(req, resp); } else if (method.equals(METHOD_PUT)) { doPut(req, resp); } else if (method.equals(METHOD_DELETE)) { doDelete(req, resp); } else if (method.equals(METHOD_OPTIONS)) { doOptions(req,resp); } else if (method.equals(METHOD_TRACE)) { doTrace(req,resp); } else { // // Note that this means NO servlet supports whatever // method was requested, anywhere on this server. // String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[1]; errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); } }
3、通過調(diào)用“destroy()”方法終止;
destroy() 方法只會(huì)被調(diào)用一次,在 Servlet 生命周期結(jié)束時(shí)被調(diào)用。destroy() 方法可以讓您的 Servlet 關(guān)閉數(shù)據(jù)庫(kù)連接、停止后臺(tái)線程、把 Cookie 列表或點(diǎn)擊計(jì)數(shù)器寫入到磁盤,并執(zhí)行其他類似的清理活動(dòng)。
@Override public void destroy() { // NOOP by default }
以上就是Servlet 生命周期的4個(gè)階段的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注創(chuàng)新互聯(lián)其它相關(guān)文章!