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

}

}

 

原文地址:https://www.cnblogs.com/gwq369/p/5432905.html