ServletContext类的四个作用

ServletContext类的四个作用

1、获取web.xml中配置的上下文参数context-param

2、获取当前的工程路径,格式:/工程路径

3、获取工程部署后在服务器硬盘上的绝对路径

4、像map一样存取数据

package LWB;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class ContextServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        1、获取web.xml中配置的上下文参数context-param
        ServletContext context=getServletConfig().getServletContext();
        String username=context.getInitParameter("username");
        String password=context.getInitParameter("password");
        System.out.println("context-param参数username的值是"+username);
        System.out.println("context-param参数username的值是"+password);
//        2、获取当前的工程路径
        System.out.println("当前工程路径"+context.getContextPath());
//        3、获取工程部署后在服务器硬盘上的绝对路径
//        "/"代表IDEA目录下的webapp目录。
        System.out.println("工程部署的路径是"+context.getRealPath("/"));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

整个web工程中只有一个servletcontext类,web工程重新部署后,servletcontext类也重新销毁和构造。重新构造后,里面的数据就没有了

package LWB;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class ContextServlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context=getServletContext();
        System.out.println("保存之前:Context1中获取域数据key1的值是"+context.getAttribute("key1"));
        context.setAttribute("key1","value1");
        System.out.println("Context1中获取域数据key1的值是"+context.getAttribute("key1"));
        System.out.println("Context1中获取域数据key1的值是"+context.getAttribute("key1"));
    }

}

posted @ 2021-05-19 14:49  ice--cream  阅读(416)  评论(0编辑  收藏  举报