Servlet生命周期测试代码2

来源:互联网 发布:手机投资黄金软件 编辑:程序博客网 时间:2024/06/04 18:55
package cn.ls.javaee;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/servlet1")public class Servlet1 extends HttpServlet {    public Servlet1() {    System.out.println("Servlet1的构造方法");    }    @Override    public void init() throws ServletException {        System.out.println("servlet1初始化");    }    @Override    protected void service(HttpServletRequest req, HttpServletResponse res)            throws ServletException, IOException {        System.out.println("servlet1处理请求");    }    private void destory() {        System.out.println("Servlet1销毁");    }    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");        PrintWriter out = response.getWriter();        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");        out.println("<HTML>");        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");        out.println("  <BODY>");        out.print("    This is ");        out.print(this.getClass());        out.println(", using the GET method");        out.println("  </BODY>");        out.println("</HTML>");        out.flush();        out.close();    }    /**     * The doPost method of the servlet. <br>     *     * This method is called when a form has its tag value method equals to post.     *      * @param request the request send by the client to the server     * @param response the response send by the server to the client     * @throws ServletException if an error occurred     * @throws IOException if an error occurred     */    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");        PrintWriter out = response.getWriter();        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");        out.println("<HTML>");        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");        out.println("  <BODY>");        out.print("    This is ");        out.print(this.getClass());        out.println(", using the POST method");        out.println("  </BODY>");        out.println("</HTML>");        out.flush();        out.close();    }}

注意load-on-startup启动即加载,正数值越小优先级越高

Servlet的实例数量,默认情况下,容器只会产生一个实例
此外了解SingleThreadModel接口即可

原创粉丝点击