ServletContext

    ServletContext是Servlet与Servlet容器之间的通信接口。Servlet容器在启动一个Web应用时,会为它创建一个ServletContext对象。每个Web应用都用唯一对应的ServletContext对象,可以把ServletContext形象地理解为Web应用的总管家,同一个Web应用中的Servlet都共享都一个总管家,Servlet对象们可以通过这个总管家来访问容器中的各种资源。

    写了一个程序测试下:

public class TestServletContext extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		ServletContext context = this.getServletContext();
		String contextPath = context.getContextPath();
		int majorVersion = context.getMajorVersion();
		int minorVersion = context.getMinorVersion();
		String ServerInfo = context.getServerInfo();

		resp.setContentType("text/html;charset=GB2312");

		PrintWriter out = resp.getWriter();
		out.println("<html><head><title>my title</title></head>");
		out.println("<body>");
		out.println("<br>Web应用的URL入口:" + contextPath);
		out.println("<br>容器支持的Servlet的主版本号:" + majorVersion);
		out.println("<br>容器支持的Servlet的次版本号: " + minorVersion);
		out.println("<br>服务器信息: " + ServerInfo);

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

	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}

相关推荐