本文共 3524 字,大约阅读时间需要 11 分钟。
1、ServletContext 是一个接口,它表示 Servlet 上下文对象
2、一个 web 工程,只有一个 ServletContext 对象实例。 3、ServletContext 对象是一个域对象。 4、ServletContext 是在 web 工程部署启动的时候创建。在 web 工程停止的时候销毁。什么是域对象?
域对象,是可以像 Map 一样存取数据的对象,叫域对象。 这里的域指的是存取数据的操作范围,整个 web 工程。存数据 | 取数据 | 删除数据 | |
---|---|---|---|
Map | put() | get() | remove() |
域对象 | setAttribute() | getAttribute() | removeAttribute() |
1、获取 web.xml 中配置的上下文参数 context-param
2、获取当前的工程路径,格式:/工程路径 3、获取工程部署后在服务器硬盘上的绝对路径 4、像 Map 一样存取数据 ContextServlet1 web.xml 中的配置:username context password pwd ContextServlet1 loey.servlet1.ContextServlet1 ContextServlet1 /context1
ServletContext1 演示代码:
public class ContextServlet1 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1、获取web.xml中配置的上下文参数context-param ServletContext context = getServletConfig().getServletContext(); String username = context.getInitParameter("username"); System.out.println("context-param参数username的值是:" + username);//context-param参数username的值是:context System.out.println("context-param参数password的值是:" + context.getInitParameter("password"));//context-param参数password的值是:pwd // 2、获取当前的工程路径,格式: /工程路径 System.out.println("当前工程路径:" + context.getContextPath());//当前工程路径:/08-Servlet // 3、获取工程部署后在服务器硬盘上的绝对路径 /** * / 斜杠被服务器解析地址为:http://ip:port/工程名/ 映射到IDEA代码的web目录 */ System.out.println("工程部署的路径是:" + context.getRealPath("/"));//工程部署的路径是:D:\JAVA\workspace_idea\JavaWeb\out\artifacts\08_Servlet_war_exploded\ System.out.println("工程下css目录的绝对路径是:" + context.getRealPath("/css"));//工程下css目录的绝对路径是:D:\JAVA\workspace_idea\JavaWeb\out\artifacts\08_Servlet_war_exploded\css }}
ServletContext 像 Map 一样存取数据:
ContextServlet2 代码:public class ContextServlet2 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取ServletContext对象 ServletContext context = getServletContext(); System.out.println(context); System.out.println("保存之前: Context2 获取 key2的值是:" + context.getAttribute("key2")); context.setAttribute("key2","value2"); System.out.println("保存之后 Context2 获取 key2的值是:" + context.getAttribute("key2")); }}
ContextServlet2 web配置:
ContextServlet2 loey.servlet1.ContextServlet2 ContextServlet2 /context2
结果:
ContextServlet3 代码:
public class ContextServlet3 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); System.out.println(context); System.out.println("Context3中的key2的值是:" + context.getAttribute("key2")); }}
ContextServlet3 web配置:
ContextServlet3 loey.servlet1.ContextServlet3 ContextServlet3 /context3
结果:
1、先启动ContextServlet2再启动ContextServlet3再启动ContextServlet2:1、先启动ContextServlet3再启动ContextServlet2再启动ContextServlet3:
转载地址:http://uluki.baihongyu.com/