Servlet接口為所有servlet提供常見的行為。
需要實現(xiàn)Servlet接口來創(chuàng)建任何servlet(直接或間接)。它提供了3個生命周期方法,用于初始化servlet,服務請求以及銷毀servlet和2個非生命周期方法。
Servlet接口有5種方法。分別為:init,service和destroy是servlet的生命周期方法。這些方法由web容器調(diào)用。
| 方法 | 描述 |
|---|---|
public void init(ServletConfig config) |
初始化servlet,它是servlet的生命周期方法,由web容器調(diào)用一次。 |
public void service(ServletRequest request,ServletResponse response) |
為傳入的請求提供響應。它由Web容器的每個請求調(diào)用。 |
public void destroy() |
僅被調(diào)用一次,并且表明servlet正在被銷毀。 |
public ServletConfig getServletConfig() |
返回ServletConfig對象。 |
public String getServletInfo() |
返回有關servlet的信息,如作者,版權,版本等。 |
下面是一個通過實現(xiàn)servlet接口的Servlet簡單例子。
打開Eclipse,創(chuàng)建一個動態(tài)網(wǎng)站項目(Dynamic Web Project):servletinterface,如下 -
注:有關如何在Eclipse創(chuàng)建動態(tài)網(wǎng)站項目,請參考:http://www.yiibai.com/servlet/creating-servlet-in-eclipse-ide.html

MyServlet.java的代碼如下所示 -
package com.yiibai;
import java.io.*;
import javax.servlet.*;
/**
* 實現(xiàn)Servlet接口的Servlet
* @author Maxsu
* @url
*/
public class MyServlet implements Servlet {
ServletConfig config = null;
public void init(ServletConfig config) {
this.config = config;
System.out.println("servlet is initialized");
}
public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><body>");
out.print("<div style=\"text-align:center;\"><h2>hello simple servlet</h2></div>");
out.print("</body></html>");
}
public void destroy() {
System.out.println("servlet is destroyed");
}
public ServletConfig getServletConfig() {
return config;
}
public String getServletInfo() {
return "copyright 2012-2020";
}
}
執(zhí)行上面項目,打開瀏覽器,輸入網(wǎng)址: http://localhost:8080/servletinterface/index 可以看到類似下面的界面 -
