ServletContext(运行环境信息)

文章目录

  • 一、 ServletContext
    • 1.1 介绍
    • 1.2 共享数据
    • 1.3 获取初始化参数
    • 1.4 请求转发
    • 1.5 读取文件


学习视频来自于:秦疆(遇见狂神说)Bilibili地址
他的自学网站:kuangstudy

我们缺乏的不是知识,而是学而不厌的态度


一、 ServletContext

1.1 介绍

web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;

1.2 共享数据

我在ServletContextDemo1 保存数据,可以在ServletContextDemo2 中取出

public class ServletContextDemo1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String data = "xdp_gacl";
        /**
         * ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,
         * 可以通过ServletConfig.getServletContext方法获得ServletContext对象。
         */
        ServletContext context = this.getServletConfig().getServletContext();//获得ServletContext对象
        context.setAttribute("data", data);  //将data存储到ServletContext对象中
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
public class ServletContextDemo2 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String data = (String) context.getAttribute("data");//从ServletContext对象中取出数据
        response.getWriter().print("data="+data);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

1.3 获取初始化参数


<context-param>
    <param-name>usernameparam-name>
    <param-value>rootparam-value>
context-param>
 ServletContext context = this.getServletContext();
 String username = context.getInitParameter("username");
 resp.getWriter().println(username);

1.4 请求转发

请求转发
浏览器地址栏不变
重定向
浏览器地址栏该表

RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");// 转发的路径
requestDispatcher.forward(req,resp); // 调用forward实现请求转发

1.5 读取文件

使用Properties类

  1. 在resources目录下新建properties文件
  2. 配置文件被打包到了同一个路径下:classes,我们俗称这个路径为classpath:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    InputStream is = context.getResourceAsStream("WEB-INF/classes/mysql.properties");
    Properties pro = new Properties();
    pro.load(is);
    String className = pro.getProperty("driverClassName");
    resp.getWriter().println("driverClassName:"+className);
}

你可能感兴趣的:(JavaEE,servlet,java)