• 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() {

    }

    }

     

  • 相关阅读:
    Excel设置下拉选项的方法
    Codeforces Round #218 (Div. 2) (线段树区间处理)
    手动配置S2SH三大框架报错(一)
    一种H.264高清视频的无参考视频质量评价算法(基于QP和跳过宏块数)
    UIWebView的使用
    AFNetworkIng的简单使用
    虚线边框的实现
    iOS实现简单时钟效果
    hdu 3966 Aragorn's Story
    Count on a tree
  • 原文地址:https://www.cnblogs.com/gwq369/p/5432905.html
Copyright © 2020-2023  润新知