Servlet介面為所有servlet提供常見的行為。
需要實現Servlet介面來建立任何servlet(直接或間接)。它提供了3
個生命周期方法,用於初始化servlet,服務請求以及銷毀servlet和2
個非生命周期方法。
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簡單例子。
開啟Eclipse,建立一個動態網站專案(Dynamic Web Project):servletinterface,如下 -
註:有關如何在Eclipse建立動態網站專案,請參考:/10/111/3353.html
MyServlet.java
的程式碼如下所示 -
package com.yiibai;
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 可以看到類似下面的介面 -