zoukankan      html  css  js  c++  java
  • ServletContext在tomcat启动的时候创建

    Servlet容器在启动时会加载web应用,并未每个web应用创建唯一的ServletContext对象。可以把ServletContext看成是一个web应用的服务器端组件的,在ServletContext中可以存放共享数据,它提供4个读取和设置共享数据的方法。

    一个例子说明:

    package mypack;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    import java.util.*;

    public class CounterServlet extends HttpServlet {

    private static final String CONTENT_TYPE = "text/html";

    public void init(ServletConfig config) throws ServletException {

    super.init(config);

    }

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    doPost(request, response);

    }

    public void doPost(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    //获得ServletContext的引用

    ServletContext context = getServletContext();

    // 从ServletContext读取count属性

    Integer count = (Integer)context.getAttribute("count");

    // 如果count属性还没有设置, 那么创建count属性,初始值为0

    // one and add it to the ServletContext

    if ( count == null ) {

    count = new Integer(0);

    context.setAttribute("count", new Integer(0));

    }

    response.setContentType(CONTENT_TYPE);

    PrintWriter out = response.getWriter();

    out.println("<html>");

    out.println("<head><title>WebCounter</title></head>");

    out.println("<body>");

    // 输出当前的count属性值

    out.println("<p>The current COUNT is : " + count + ".</p>");

    out.println("</body></html>");

    // 创建新的count对象,其值增1

    count = new Integer(count.intValue() + 1);

    // 将新的count属性存储到ServletContext中

    context.setAttribute("count", count);

    }

    public void destroy() {

    }

    }

     

  • 相关阅读:
    如何在ONENET云端搭建IOT平台
    01_接口测试介绍
    10_fiddler_待整理
    09_fiddler_慢网络测试(限制网速)
    08_Fiddler_打断点(bpu)
    07_Fiddler_post提交到主体的四种参数形式
    06_Fiddler_get请求(url详解)
    05_Fiddler的Script 脚本用法
    04_Fiddler_Composer创建和发送HTTP Request
    03_Fiddler抓包的捕获设置
  • 原文地址:https://www.cnblogs.com/gwq369/p/5432905.html
Copyright © 2011-2022 走看看