web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用,可以用于传输东西

共享数据

我在这个Servlet中保存的数据,可以在另外一个servlet中拿到

自我理解:Servlet可以创建很多个,而他们可以为了传递一些数据可以通过I/O流保存到第三方文件上,进行传输。比较麻烦,为了简化这一过程,不同的Servlet可以共用同一个Servletcontext对象来进行传输。

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
4
        //this.getInitParameter(); 初始化参数
        //this.getServletContext(); Servlet上下文
        //this.getServletConfig();  Servlet配置
        ServletContext servletContext = getServletContext();

        String username = "内河";//数据
        servletContext.setAttribute("username",username);//将一个数据保存在了ServletContext中,名字为:username,值为username

        System.out.println("你好,servlet");
    }
public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();//获取ServletContext对象
        String username = (String) servletContext.getAttribute("username");//获取节点信息

        resp.setContentType("text/html;charset=utf-8");//设置编码格式
        resp.getWriter().print(username);//打印出信息
    }

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

总结:ServletContext对象充当了交换数据的媒介,链接不同的Servlet对象

获取初始化参数

<!--配置一些web应用初始化参数-->
	<context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>
public class ServletDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();//获取ServletContext对象
        String url = servletContext.getInitParameter("url");
        resp.getWriter().print(url);
    }

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

请求转发

地址不变,内容是其他地址的东西

public class ServletDemo04 extends HttpServlet {

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext servletContext = this.getServletContext();//获取ServletContext对象
            System.out.println("进入了demo04");
            servletContext.getRequestDispatcher("/cp").forward(req,resp);//调用forword实现请求转发;

        }

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