• Servlet类源码说明


    servlet是学习java web不可不懂的一个类,网上各种教程都参杂太多,每次理解都感觉像把别人吐出来的食物再放在嘴里咀嚼,小编一怒之下,直接打开源码,原汁原味的芬芳扑面而来:

    /**
     * Defines methods that all servlets must implement.
     *
     * <p>A servlet is a small Java program that runs within a Web server.
     * Servlets receive and respond to requests from Web clients,
     * usually across HTTP, the HyperText Transfer Protocol. 
     *
     * <p>To implement this interface, you can write a generic servlet
     * that extends
     * <code>javax.servlet.GenericServlet</code> or an HTTP servlet that
     * extends <code>javax.servlet.http.HttpServlet</code>.
     *
     * <p>This interface defines methods to initialize a servlet,
     * to service requests, and to remove a servlet from the server.
     * These are known as life-cycle methods and are called in the
     * following sequence:
     * <ol>
     * <li>The servlet is constructed, then initialized with the <code>init</code> method.
     * <li>Any calls from clients to the <code>service</code> method are handled.
     * <li>The servlet is taken out of service, then destroyed with the 
     * <code>destroy</code> method, then garbage collected and finalized.
     * </ol>
     *
     * <p>In addition to the life-cycle methods, this interface
     * provides the <code>getServletConfig</code> method, which the servlet 
     * can use to get any startup information, and the <code>getServletInfo</code>
     * method, which allows the servlet to return basic information about itself,
     * such as author, version, and copyright.
     *
     * @author     Various
     *
     * @see     GenericServlet
     * @see     javax.servlet.http.HttpServlet
     *
     */
    
    public interface Servlet {

     1、Servlet是一个接口,定义的所有方法将被所有子类servlet实现;

    2、一个Servlet是一个小java程序必须与Web server一起运行

    3、Servlet从Web客户端获取请求并响应请求,通常通过Http(超文本传输协议);

    4、通过实现这个Servlet接口,你可以写一个通用的servlet(继承于javax.servlet.GenericServlet),或者写一个支持HTTP协议的servlet(继承javax.servlet.http.HttpServlet);

    5、这个接口定义一些方法去初始化一个servlet,去响应请求,并且可以从server中销毁servlet;

    6、这些被称为生命周期的方法,以下面的顺序执行:

    ①:构造一个servlet实例,调用 init 方法进行初始化;

    ②:调用service方法处理客户端发过来的任何请求;

    ③:调用destroy方法销毁servlet,并由垃圾回收器终结这个servlet对象。

        /**
         * Called by the servlet container to indicate to a servlet that the 
         * servlet is being placed into service.
         *
         * <p>The servlet container calls the <code>init</code>
         * method exactly once after instantiating the servlet.
         * The <code>init</code> method must complete successfully
         * before the servlet can receive any requests.
         *
         * <p>The servlet container cannot place the servlet into service
         * if the <code>init</code> method
         * <ol>
         * <li>Throws a <code>ServletException</code>
         * <li>Does not return within a time period defined by the Web server
         * </ol>
         *
         *
         * @param config            a <code>ServletConfig</code> object 
         *                    containing the servlet's
         *                     configuration and initialization parameters
         *
         * @exception ServletException     if an exception has occurred that
         *                    interferes with the servlet's normal
         *                    operation
         *
         * @see                 UnavailableException
         * @see                 #getServletConfig
         *
         */
    
    public void init(ServletConfig config) throws ServletException;

    1、被servlet容器调用来表明是一个servlet,并且这个servlet会用来实现你的业务逻辑

    2、在servlet实例创建以后 init 方法被调用,并且只被调用一次

    3、在servlet处理各种请求之前,init方法必需成功运行,否则当抛出ServletException时,servlet将不会接收到任何请求

    4、可以在init方法中传入ServletConfig初始化参数

         /**
         *
         * Returns a {@link ServletConfig} object, which contains
         * initialization and startup parameters for this servlet.
         * The <code>ServletConfig</code> object returned is the one 
         * passed to the <code>init</code> method. 
         *
         * <p>Implementations of this interface are responsible for storing the 
         * <code>ServletConfig</code> object so that this 
         * method can return it. The {@link GenericServlet}
         * class, which implements this interface, already does this.
         *
         * @return        the <code>ServletConfig</code> object
         *            that initializes this servlet
         *
         * @see         #init
         *
         */
    
    public ServletConfig getServletConfig();

     1、这个方法返回一个ServletConfig(一个接口)类的对象,包含了初始化servlet时的参数;

    2、ServletConfig这个接口的实现负责存储servlet的初始化参数

         /**
         * Called by the servlet container to allow the servlet to respond to 
         * a request.
         *
         * <p>This method is only called after the servlet's <code>init()</code>
         * method has completed successfully.
         * 
         * <p>  The status code of the response always should be set for a servlet 
         * that throws or sends an error.
         *
         * 
         * <p>Servlets typically run inside multithreaded servlet containers
         * that can handle multiple requests concurrently. Developers must 
         * be aware to synchronize access to any shared resources such as files,
         * network connections, and as well as the servlet's class and instance 
         * variables. 
         * More information on multithreaded programming in Java is available in 
         * <a href="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html">
         * the Java tutorial on multi-threaded programming</a>.
         *
         *
         * @param req     the <code>ServletRequest</code> object that contains
         *            the client's request
         *
         * @param res     the <code>ServletResponse</code> object that contains
         *            the servlet's response
         *
         * @exception ServletException     if an exception occurs that interferes
         *                    with the servlet's normal operation 
         *
         * @exception IOException         if an input or output exception occurs
         *
         */
    
    public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException;

     1、这个方法在init()方法调用成功后调用,此方法是servlet容器负责调用来授予servlet对请求进行响应

    2、Servlets通常运行在多线程的servlet容器内部可以同时处理多个请求。开发人员必须认识到同步访问任何共享资源,如文件、网络连接,以及servlet的类变量和实例变量。

     /**
         * Returns information about the servlet, such
         * as author, version, and copyright.
         * 
         * <p>The string that this method returns should
         * be plain text and not markup of any kind (such as HTML, XML,
         * etc.).
         *
         * @return         a <code>String</code> containing servlet information
         *
         */
    public String getServletInfo();

     1、此方法返回关于servlet的信息,如作者、版本、版权;

    2、这个方法返回的必须是纯字符串文本,不能带有html、xml等标记

     /**
         *
         * Called by the servlet container to indicate to a servlet that the
         * servlet is being taken out of service.  This method is
         * only called once all threads within the servlet's
         * <code>service</code> method have exited or after a timeout
         * period has passed. After the servlet container calls this 
         * method, it will not call the <code>service</code> method again
         * on this servlet.
         *
         * <p>This method gives the servlet an opportunity 
         * to clean up any resources that are being held (for example, memory,
         * file handles, threads) and make sure that any persistent state is
         * synchronized with the servlet's current state in memory.
         *
         */
    
        public void destroy();
    }

     1、此方法被servlet容器调用,指示了这个servlet已经完成业务实现,可以被销毁了

    2、此方法只被调用一次,在servlet的service方法中的线程都退出或者时间超时时调用该servlet将不再调用service方法

    3、这个方法给servlet一个机会去清理所占用的资源(内存、文件、线程),确保与servlet的当前内存状态保持同步的持续状态

    读完源码,大脑立马清晰多了。釉木友同感?

  • 相关阅读:
    [LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee
    [LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown
    [LeetCode] 1291. Sequential Digits
    [LeetCode] 188. Best Time to Buy and Sell Stock IV
    [LeetCode] 123. Best Time to Buy and Sell Stock III
    [LeetCode] 581. Shortest Unsorted Continuous Subarray
    [LeetCode] 1041. Robot Bounded In Circle
    [LeetCode] 1110. Delete Nodes And Return Forest
    [LeetCode] 421. Maximum XOR of Two Numbers in an Array
    [LeetCode] 1109. Corporate Flight Bookings
  • 原文地址:https://www.cnblogs.com/bossen/p/5943300.html
Copyright © 2020-2023  润新知