HttpServlet Service方法


service() 方法是執行實際任務的主要方法。Servlet 容器(即 Web 服務器)調用 service() 方法來處理來自客戶端(瀏覽器)的請求,並把格式化的響應寫回給客戶端。

每次服務器接收到一個 Servlet 請求時,服務器會產生一個新的線程並調用服務。service() 方法檢查 HTTP 請求類型(GET、POST、PUT、DELETE 等),並在適當的時候調用 doGet、doPost、doPut,doDelete 等方法。

下面是該方法的特征:

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{ }

service() 方法由容器調用,service 方法在適當的時候調用 doGet、doPost、doPut、doDelete 等方法。所以,您不用對 service() 方法做任何動作,您只需要根據來自客戶端的請求類型來重寫 doGet() 或 doPost() 即可。

 

/*     */   protected void service(HttpServletRequest req, HttpServletResponse resp)
/*     */     throws ServletException, IOException
/*     */   {
/* 568 */     String method = req.getMethod();
/*     */     
/* 570 */     if (method.equals("GET")) {
/* 571 */       long lastModified = getLastModified(req);
/* 572 */       if (lastModified == -1L)
/*     */       {
/*     */ 
/* 575 */         doGet(req, resp);
/*     */       } else {
/* 577 */         long ifModifiedSince = req.getDateHeader("If-Modified-Since");
/* 578 */         if (ifModifiedSince < lastModified / 1000L * 1000L)
/*     */         {
/*     */ 
/*     */ 
/* 582 */           maybeSetLastModified(resp, lastModified);
/* 583 */           doGet(req, resp);
/*     */         } else {
/* 585 */           resp.setStatus(304);
/*     */         }
/*     */       }
/*     */     }
/* 589 */     else if (method.equals("HEAD")) {
/* 590 */       long lastModified = getLastModified(req);
/* 591 */       maybeSetLastModified(resp, lastModified);
/* 592 */       doHead(req, resp);
/*     */     }
/* 594 */     else if (method.equals("POST")) {
/* 595 */       doPost(req, resp);
/*     */     }
/* 597 */     else if (method.equals("PUT")) {
/* 598 */       doPut(req, resp);
/*     */     }
/* 600 */     else if (method.equals("DELETE")) {
/* 601 */       doDelete(req, resp);
/*     */     }
/* 603 */     else if (method.equals("OPTIONS")) {
/* 604 */       doOptions(req, resp);
/*     */     }
/* 606 */     else if (method.equals("TRACE")) {
/* 607 */       doTrace(req, resp);
/*     */ 
/*     */ 
/*     */     }
/*     */     else
/*     */     {
/*     */ 
/*     */ 
/* 615 */       String errMsg = lStrings.getString("http.method_not_implemented");
/* 616 */       Object[] errArgs = new Object[1];
/* 617 */       errArgs[0] = method;
/* 618 */       errMsg = MessageFormat.format(errMsg, errArgs);
/*     */       
/* 620 */       resp.sendError(501, errMsg);
/*     */     }
/*     */   }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM