ServletContext和Web應用的關系
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
}
}