Java Servlet 是運行在 Web 伺服器或應(yīng)用程式伺服器上的程序,它是作為來自 Web 瀏覽器或其他 HTTP 用戶端的請求和 HTTP 伺服器上的資料庫或應(yīng)用程式之間的中間層。

使用 Servlet,您可以收集來自網(wǎng)頁表單的使用者輸入,呈現(xiàn)來自資料庫或其他來源的記錄,也可以動態(tài)建立網(wǎng)頁。

Servlet 實例 語法

Servlet 是服務(wù) HTTP 請求並實作?javax.servlet.Servlet?介面的 Java 類別。 Web 應(yīng)用程式開發(fā)人員通常會編寫 Servlet 來擴充 javax.servlet.http.HttpServlet,並實作 Servlet 介面的抽象類別專門用來處理 HTTP 請求。

Servlet 實例 範例

//?導入必需的?java?庫
import?java.io.*;
import?javax.servlet.*;
import?javax.servlet.http.*;
//?擴充?HttpServlet?類
public?class?HelloWorld?extends?HttpServlet?{
?
??private?String?message;
??public?void?init()?throws?ServletException
??{
??????//?執(zhí)行必要的初始化
??????message?=?"Hello?World";
??}
??public?void?doGet(HttpServletRequest?request,
????????????????????HttpServletResponse?response)
????????????throws?ServletException,?IOException
??{
??????//?設(shè)定回應(yīng)內(nèi)容類型
??????response.setContentType("text/html");
??????//?實際的邏輯是在這裡
??????PrintWriter?out?=?response.getWriter();
??????out.println("<h1>"?+?message?+?"</h1>");
??}
??
??public?void?destroy()
??{
??????//?什麼都不做
??}}