JavaWeb開發基礎Servlet API

测试开发刚哥發表於2024-07-27

Servlet版本

Oracle將Java EE(Java SE還自己保留)交給開源組織,Eclipse基金會接手。但Oracle不允許開源組織使用Java名號,所以Jakarta EE名稱於2018.02.26應運而生。

正是因為組織變化,Servlet被割裂為了2個版本,javax.servletjakarta.servlet

javax.servlet已經停止維護,但它仍然是一個非常有用和重要的技術,特別是在許多現有專案中,學習和使用它將為你提供堅實的Web開發基礎。

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

如果希望使用Jakarta EE 9或更高版本的Servlet API,則需要切換到javax.servlet

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.0.0</version>
    <scope>provided</scope>
</dependency>

本文將基於javax.servlet來介紹Servlet,從Usages來看,它仍然是使用最廣泛的。

Servlet API

Servlet API主要有2個包,javax.servlet包含了servlet和web container使用的介面和類。javax.servlet.http包含了http相關的介面和類。

javax.servlet介面列表:

  1. Servlet
  2. ServletRequest
  3. ServletResponse
  4. RequestDispatcher
  5. ServletConfig
  6. ServletContext
  7. SingleThreadModel
  8. Filter
  9. FilterConfig
  10. FilterChain
  11. ServletRequestListener
  12. ServletRequestAttributeListener
  13. ServletContextListener
  14. ServletContextAttributeListener

javax.servlet類列表:

  1. GenericServlet
  2. ServletInputStream
  3. ServletOutputStream
  4. ServletRequestWrapper
  5. ServletResponseWrapper
  6. ServletRequestEvent
  7. ServletContextEvent
  8. ServletRequestAttributeEvent
  9. ServletContextAttributeEvent
  10. ServletException
  11. UnavailableException

javax.servlet.http介面列表:

  1. HttpServletRequest
  2. HttpServletResponse
  3. HttpSession
  4. HttpSessionListener
  5. HttpSessionAttributeListener
  6. HttpSessionBindingListener
  7. HttpSessionActivationListener
  8. HttpSessionContext (deprecated now)

javax.servlet.http類列表:

  1. HttpServlet
  2. Cookie
  3. HttpServletRequestWrapper
  4. HttpServletResponseWrapper
  5. HttpSessionEvent
  6. HttpSessionBindingEvent
  7. HttpUtils (deprecated now)

Servlet介面

Servlet Interface定義了所有servlet必須具有的行為。主要方法如下:

  1. public void init(ServletConfig config) 初始化,只會被web container呼叫1次

  2. public void service(ServletRequest request, ServletResponse response) 接收請求,返回響應,每次請求都會呼叫1次

  3. public void destroy() 銷燬,只會被web container呼叫1次

  4. public ServletConfig getServletConfig() Servlet配置

  5. public String getServletInfo() Servlet資訊

以下是程式碼示例:

import java.io.*;
import javax.servlet.*;

public class First implements Servlet {
    ServletConfig config = null;

    /**
     * 初始化
     * @param config
     */
    public void init(ServletConfig config) {
        this.config = config;
        System.out.println("servlet is initialized");
    }

    /**
     * 服務
     * @param req
     * @param res
     * @throws IOException
     * @throws ServletException
     */
    public void service(ServletRequest req, ServletResponse res)
            throws IOException, ServletException {

        res.setContentType("text/html");

        PrintWriter out = res.getWriter();
        out.print("<html><body>");
        out.print("<b>hello simple servlet</b>");
        out.print("</body></html>");
    }

    /**
     * 銷燬
     */
    public void destroy() {
        System.out.println("servlet is destroyed");
    }

    /**
     * 配置
     * @return
     */
    public ServletConfig getServletConfig() {
        return config;
    }

    /**
     * 資訊
     * @return
     */
    public String getServletInfo() {
        return "copyright 2007-1010";
    }
}

GenericServlet類

GenericServlet是個抽象類,實現了Servlet, ServletConfig, Serializable介面,能處理任何請求,支援任何協議。主要方法如下:

  1. public void init(ServletConfig config) 初始化
  2. public abstract void service(ServletRequest request, ServletResponse response) 接收請求,返回響應,每次請求都會呼叫1次
  3. public void destroy() 銷燬,只會被web container呼叫1次
  4. public ServletConfig getServletConfig() Servlet配置
  5. public String getServletInfo() Servlet資訊
  6. public void init() 無參初始化
  7. public ServletContext getServletContext() Servlet上下文
  8. public String getInitParameter(String name) 根據引數name返回value
  9. public Enumeration getInitParameterNames() web.xml所有引數
  10. public String getServletName() Servlet名稱
  11. public void log(String msg) 記錄Servlet日誌
  12. public void log(String msg,Throwable t) 記錄Servlet日誌和異常堆疊

以下是程式碼示例:

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class First extends GenericServlet {
    public void service(ServletRequest req, ServletResponse res)
            throws IOException, ServletException {

        res.setContentType("text/html");

        PrintWriter out = res.getWriter();
        out.print("<html><body>");
        out.print("<b>hello generic servlet</b>");
        out.print("</body></html>");
    }
}  

HttpServlet類

HttpServlet繼承了GenericServlet抽象類。主要方法如下:

  1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type.(這裡結合英文解釋比較清楚,轉換型別後,呼叫第2個service)

  2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type.(這裡結合英文解釋比較清楚,根據不同method,呼叫doXXX()方法)

  3. protected void doGet(HttpServletRequest req, HttpServletResponse res) 處理GET請求,web container呼叫

  4. protected void doPost(HttpServletRequest req, HttpServletResponse res) 處理POST請求,web container呼叫

  5. protected void doHead(HttpServletRequest req, HttpServletResponse res) 處理HEAD請求,web container呼叫

  6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) 處理OPTIONS請求,web container呼叫

  7. protected void doPut(HttpServletRequest req, HttpServletResponse res) 處理PUT請求,web container呼叫

  8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) 處理TRACE請求,web container呼叫

  9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) 處理DELETE請求,web container呼叫

  10. protected long getLastModified(HttpServletRequest req) 上次修改時間

如果想深入學習Servlet API,可以在Maven pom.xml引入servlet包依賴,External Libraries檢視原始碼。

參考資料:

https://www.javatpoint.com/servlet-api

https://www.javatpoint.com/Servlet-interface

https://www.javatpoint.com/GenericServlet-class

https://www.javatpoint.com/HttpServlet-class

ChatGPT

相關文章