Servlet生命週期的三個核心方法分別是 init() , service() 和 destroy()。每一個Servlet都會實現這些方法,而且在特定的運行時間調用它們。html
1)在Servlet生命週期的初始化階段,web容器經過調用init()方法來初始化Servlet實例,而且能夠傳遞一個實現 javax.servlet.ServletConfig 接口的對象給它。這個配置對象(configuration object)使Servlet可以讀取在web應用的web.xml文件裏定義的名值(name-value)初始參數。這個方法在Servlet實例的生命週期裏只調用一次。java
2)初始化後,Servlet實例就能夠處理客戶端請求了。web容器調用Servlet的service()方法來處理每個請求。service() 方法定義了可以處理的請求類型而且調用適當方法來處理這些請求。編寫Servlet的開發者必須爲這些方法提供實現。若是發出一個Servlet沒實現的請求,那麼父類的方法就會被調用而且一般會給請求方(requester)返回一個錯誤信息。web
一般,咱們不須要重寫(override)這個方法。網絡
3)最後,web容器調用destroy()方法來終結Servlet。若是你想在Servlet的生命週期內關閉或者銷燬一些文件系統或者網絡資源,你能夠調用這個方法來實現。destroy() 方法和init()方法同樣,在Servlet的生命週期裏只能調用一次。ide
以下例子post
package com.wxp.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;this
public class MyFirstServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public MyFirstServlet() {
super();
}.net
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}code
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {orm
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
try {
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>MyFirstServlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print("Servlet MyFirstServlet at");
out.print(request.getContextPath());
out.println(" </BODY>");
out.println("</HTML>");
} catch (Exception e) {
e.printStackTrace();
}finally{
out.flush();
out.close();
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } public String getServletInfo(){ return "MyFirstServlet"; } }