Servlet容器在启动时会加载Web应用,并为每个WEB应用创建唯一的ServletContext对象。可以把ServletContext看成是一个WEB应用的服务器端组件的共享内存。在ServletContext中可以存放共享数据,它提供了4个读取或设置共享数据的方法:
setAttribute(String name,Object object):把一个对象和一个属性名绑定。将这个对象存储在ServletContext中。
getAttribute(String name):根据给定的属性名返回所绑定的对象;
removeAttribute(String name):根据给定的属性名从ServletContext中删除相应的属性。
getAttribateNames():返回一个Enumeration对象。它包含了存储在ServletContext对象中的所有属性名。
package mypack;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContext extends HttpServlet {
/**
* Constructor of the object.
*/
private static final String CONTEXT_TYPE = "text/html";
private Object Integer;
public ServletContext() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @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 doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// response.setContentType("text/html");
// PrintWriter out = response.getWriter();
doPost(request, response);
}
/**
* 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 {
// 获得Context的引用
ServletContext context = (ServletContext) getServletContext();
//response.setContentType("text/html");
PrintWriter out = response.getWriter();
Integer count = (Integer) context.getAttribute("count");
if (count == null) {
count=new Integer(0);
context.setAttribute("count",new Integer(0));
}
response.setContentType(CONTEXT_TYPE);
out.print("<html><head><title>");
out.print(CONTEXT_TYPE+"</title></head><body>");
out.print("<p>This count is:"+count+"</p>");
out.print("</body>");
count=new Integer(count.intValue()+1);
context.setAttribute("count",count);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
// Put your code here
}
}